@mastra/server 1.72.0-alpha.9 → 1.73.0-alpha.0
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/{a2a-D2BffGsK.js → a2a-Dyd6lbnr.js} +35 -23
- package/dist/a2a-Dyd6lbnr.js.map +1 -0
- package/dist/{a2a-CAQVpVxH.cjs → a2a-rSyYjbA3.cjs} +35 -24
- package/dist/a2a-rSyYjbA3.cjs.map +1 -0
- package/dist/{api-schema-manifest-C9mzZvwb.cjs → api-schema-manifest-azbFW2gh.cjs} +2 -2
- package/dist/{api-schema-manifest-C9mzZvwb.cjs.map → api-schema-manifest-azbFW2gh.cjs.map} +1 -1
- package/dist/{api-schema-manifest-CeSyB2uX.js → api-schema-manifest-btfn_x2G.js} +2 -2
- package/dist/{api-schema-manifest-CeSyB2uX.js.map → api-schema-manifest-btfn_x2G.js.map} +1 -1
- package/dist/{dist-CYk5xS3y.js → dist-B2EGPe0Y.js} +219 -42
- package/dist/dist-B2EGPe0Y.js.map +1 -0
- package/dist/{dist-CRMvLG_8.cjs → dist-BJfoL3Lt.cjs} +219 -43
- package/dist/dist-BJfoL3Lt.cjs.map +1 -0
- package/dist/docs/SKILL.md +2 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/docs/references/docs-guides-mcp-authentication-authorization.md +136 -0
- package/dist/{observability-new-endpoints-BnLi_Bdm.cjs → observability-new-endpoints-7Zd6uEZf.cjs} +106 -1
- package/dist/observability-new-endpoints-7Zd6uEZf.cjs.map +1 -0
- package/dist/{observability-new-endpoints-aUBFBO-b.js → observability-new-endpoints-lNC3o66-.js} +102 -3
- package/dist/observability-new-endpoints-lNC3o66-.js.map +1 -0
- package/dist/{processors-88oJ_4J-.js → processors-33IULT8X.js} +7 -4
- package/dist/processors-33IULT8X.js.map +1 -0
- package/dist/{processors-D6lRjS0e.cjs → processors-80HWq8nr.cjs} +7 -4
- package/dist/processors-80HWq8nr.cjs.map +1 -0
- package/dist/{routes-T4x5ibCy.cjs → routes-BaQVELB2.cjs} +4 -3
- package/dist/routes-BaQVELB2.cjs.map +1 -0
- package/dist/{routes-D5OKIMYe.js → routes-BqoNkLiT.js} +4 -3
- package/dist/routes-BqoNkLiT.js.map +1 -0
- package/dist/server/a2a/agent-card-signing.d.ts.map +1 -1
- package/dist/server/handlers/a2a.cjs +1 -1
- package/dist/server/handlers/a2a.js +1 -1
- package/dist/server/handlers/agent-builder.cjs +1 -1
- package/dist/server/handlers/agent-builder.js +1 -1
- package/dist/server/handlers/agents.cjs +2 -2
- package/dist/server/handlers/agents.cjs.map +1 -1
- package/dist/server/handlers/agents.d.ts.map +1 -1
- package/dist/server/handlers/agents.js +3 -3
- package/dist/server/handlers/agents.js.map +1 -1
- package/dist/server/handlers/conversations.cjs +1 -2
- package/dist/server/handlers/conversations.cjs.map +1 -1
- package/dist/server/handlers/conversations.d.ts.map +1 -1
- package/dist/server/handlers/conversations.js +1 -2
- package/dist/server/handlers/conversations.js.map +1 -1
- package/dist/server/handlers/observability-new-endpoints.cjs +2 -1
- package/dist/server/handlers/observability-new-endpoints.d.ts +96 -0
- package/dist/server/handlers/observability-new-endpoints.d.ts.map +1 -1
- package/dist/server/handlers/observability-new-endpoints.js +2 -2
- package/dist/server/handlers/observability-shared.cjs +17 -0
- package/dist/server/handlers/observability-shared.cjs.map +1 -1
- package/dist/server/handlers/observability-shared.d.ts +9 -0
- package/dist/server/handlers/observability-shared.d.ts.map +1 -1
- package/dist/server/handlers/observability-shared.js +16 -1
- package/dist/server/handlers/observability-shared.js.map +1 -1
- package/dist/server/handlers/observability.cjs +3 -1
- package/dist/server/handlers/observability.cjs.map +1 -1
- package/dist/server/handlers/observability.js +3 -2
- package/dist/server/handlers/observability.js.map +1 -1
- package/dist/server/handlers/processors.cjs +3 -1
- package/dist/server/handlers/processors.cjs.map +1 -1
- package/dist/server/handlers/processors.d.ts +6 -3
- package/dist/server/handlers/processors.d.ts.map +1 -1
- package/dist/server/handlers/processors.js +3 -1
- package/dist/server/handlers/processors.js.map +1 -1
- package/dist/server/handlers/responses.adapter.cjs +1 -2
- package/dist/server/handlers/responses.adapter.cjs.map +1 -1
- package/dist/server/handlers/responses.adapter.d.ts.map +1 -1
- package/dist/server/handlers/responses.adapter.js +1 -2
- package/dist/server/handlers/responses.adapter.js.map +1 -1
- package/dist/server/handlers/responses.cjs +1 -2
- package/dist/server/handlers/responses.cjs.map +1 -1
- package/dist/server/handlers/responses.d.ts.map +1 -1
- package/dist/server/handlers/responses.js +1 -2
- package/dist/server/handlers/responses.js.map +1 -1
- package/dist/server/handlers/system.cjs +1 -1
- package/dist/server/handlers/system.js +1 -1
- package/dist/server/handlers.cjs +1 -1
- package/dist/server/handlers.js +1 -1
- package/dist/server/schemas/index.cjs +1 -1
- package/dist/server/schemas/index.js +1 -1
- package/dist/server/schemas/processors.d.ts +4 -0
- package/dist/server/schemas/processors.d.ts.map +1 -1
- package/dist/server/server-adapter/index.cjs +1 -1
- package/dist/server/server-adapter/index.js +1 -1
- package/dist/server/server-adapter/routes/observability.d.ts +95 -0
- package/dist/server/server-adapter/routes/observability.d.ts.map +1 -1
- package/dist/server/server-adapter/routes/processors.d.ts +6 -3
- package/dist/server/server-adapter/routes/processors.d.ts.map +1 -1
- package/package.json +9 -9
- package/dist/a2a-CAQVpVxH.cjs.map +0 -1
- package/dist/a2a-D2BffGsK.js.map +0 -1
- package/dist/dist-CRMvLG_8.cjs.map +0 -1
- package/dist/dist-CYk5xS3y.js.map +0 -1
- package/dist/observability-new-endpoints-BnLi_Bdm.cjs.map +0 -1
- package/dist/observability-new-endpoints-aUBFBO-b.js.map +0 -1
- package/dist/processors-88oJ_4J-.js.map +0 -1
- package/dist/processors-D6lRjS0e.cjs.map +0 -1
- package/dist/routes-D5OKIMYe.js.map +0 -1
- package/dist/routes-T4x5ibCy.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"observability.js","names":["store"],"sources":["../../../src/server/handlers/observability.ts"],"sourcesContent":["import { extractTrajectoryFromTrace, listScoresResponseSchema } from '@mastra/core/evals';\nimport { scoreTraces } from '@mastra/core/evals/scoreTraces';\nimport {\n tracesFilterSchema,\n tracesOrderBySchema,\n spanIdsSchema,\n listTracesResponseSchema,\n scoreTracesRequestSchema,\n scoreTracesResponseSchema,\n getTraceArgsSchema,\n getTraceResponseSchema,\n getTraceLightResponseSchema,\n getSpanArgsSchema,\n getSpanResponseSchema,\n dateRangeSchema,\n toTraceSpans,\n traceSpanSchema,\n} from '@mastra/core/storage';\n// `branches*`, `listBranches*`, and `getBranch*` schemas are new in\n// @mastra/core@1.32.0; route them through a shim that tolerates older cores\n// (see ./observability-storage-schemas.ts for full rationale).\nimport { z } from 'zod/v4';\nimport { HTTPException } from '../http-exception';\nimport type { ServerRoute } from '../server-adapter/routes';\nimport { createRoute, pickParams, wrapSchemaForQueryParams } from '../server-adapter/routes/route-builder';\nimport { handleError } from './error';\nimport { paginationArgsSchema } from './observability-list-query-schemas';\nimport {\n assertObservabilityDeltaSupported,\n createObservabilityListQuerySchema,\n getObservabilityStore,\n getScoresStore,\n getStorage,\n OBSERVABILITY_LIST_ENDPOINTS,\n} from './observability-shared';\nimport {\n branchesFilterSchema,\n branchesOrderBySchema,\n listBranchesResponseSchema,\n getBranchArgsSchema,\n getBranchResponseSchema,\n listTracesLightResponseSchema,\n batchDeleteTracesArgsSchema,\n batchDeleteTracesResponseSchema,\n} from './observability-storage-schemas';\n\nexport * from './observability-new-endpoints';\n\n// ============================================================================\n// Legacy Parameter Support (backward compatibility with main branch API)\n// ============================================================================\n\n/**\n * Legacy query parameters from the old API (main branch).\n * These are accepted for backward compatibility and transformed to new format.\n */\nconst legacyQueryParamsSchema = z.object({\n // Old: dateRange was in pagination, now it's startedAt in filters\n dateRange: dateRangeSchema.optional(),\n // Old: name matched span names like \"agent run: 'myAgent'\"\n name: z.string().optional(),\n // entityType needs preprocessing to handle legacy 'workflow' value\n entityType: z.preprocess(val => (val === 'workflow' ? 'workflow_run' : val), z.string().optional()),\n});\n\n/**\n * Transforms legacy query parameters to the new format.\n * - dateRange -> startedAt (if startedAt not already set)\n * - name=\"agent run: 'x'\" -> entityId='x', entityType='agent'\n * - name=\"workflow run: 'x'\" -> entityId='x', entityType='workflow_run'\n * - entityType='workflow' -> entityType='workflow_run' (enum value fix)\n */\nfunction transformLegacyParams(params: Record<string, unknown>): Record<string, unknown> {\n const result = { ...params };\n\n // Transform old entityType='workflow' -> 'workflow_run' to support direct handler usage in tests\n if (result.entityType === 'workflow') {\n result.entityType = 'workflow_run';\n }\n\n // Transform old dateRange -> new startedAt\n if (params.dateRange && !params.startedAt) {\n result.startedAt = params.dateRange;\n delete result.dateRange;\n }\n\n // Transform old name -> entityId + entityType\n // Old format: name matched span names like \"agent run: 'myAgent'\" or \"workflow run: 'myWorkflow'\"\n if (typeof params.name === 'string' && !params.entityId) {\n const agentMatch = params.name.match(/^agent run: '([^']+)'$/);\n const workflowMatch = params.name.match(/^workflow run: '([^']+)'$/);\n\n if (agentMatch) {\n result.entityId = agentMatch[1];\n result.entityType = 'agent';\n } else if (workflowMatch) {\n result.entityId = workflowMatch[1];\n result.entityType = 'workflow_run';\n }\n delete result.name;\n }\n\n return result;\n}\n\n// ============================================================================\n// Route Definitions (new pattern - handlers defined inline with createRoute)\n// ============================================================================\n\n/** Filter shape shared by the full and lightweight trace list routes. */\nconst tracesListFilterSchema = tracesFilterSchema.extend({\n ...legacyQueryParamsSchema.shape, // Accept legacy params for backward compatibility\n entityType: z.preprocess(\n value => (value === 'workflow' ? 'workflow_run' : value),\n tracesFilterSchema.shape.entityType,\n ),\n});\n\nconst listTracesQueryParamSchema = createObservabilityListQuerySchema(tracesListFilterSchema, tracesOrderBySchema);\n\n/** Route: GET /observability/traces - paginated trace listing with filtering and sorting. */\nexport const LIST_TRACES_ROUTE: ServerRoute = createRoute({\n method: 'GET',\n path: '/observability/traces',\n responseType: 'json',\n queryParamSchema: listTracesQueryParamSchema,\n responseSchema: listTracesResponseSchema,\n summary: 'List traces',\n description:\n 'Returns a paginated list of traces with optional filtering and sorting. In delta mode, returns only newly listed traces matching the filters.',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, mode, after, limit, ...params }) => {\n try {\n // Transform legacy params to new format before processing\n const transformedParams = transformLegacyParams(params);\n\n const filters = pickParams(tracesFilterSchema, transformedParams);\n const observabilityStore = await getObservabilityStore(mastra);\n if (mode === 'delta') {\n assertObservabilityDeltaSupported(observabilityStore, OBSERVABILITY_LIST_ENDPOINTS.traces);\n return await observabilityStore.listTraces({\n mode,\n filters,\n after: typeof after === 'string' ? after : undefined,\n limit,\n });\n }\n\n const pagination = pickParams(paginationArgsSchema, transformedParams);\n const orderBy = pickParams(tracesOrderBySchema, transformedParams);\n return await observabilityStore.listTraces({ filters, pagination, orderBy });\n } catch (error) {\n return handleError(error, 'Error listing traces');\n }\n },\n});\n\n/** Route: GET /observability/traces/light - paginated lightweight trace listing with filtering and sorting. */\nexport const LIST_TRACES_LIGHT_ROUTE = createRoute({\n method: 'GET',\n path: '/observability/traces/light',\n responseType: 'json',\n queryParamSchema: listTracesQueryParamSchema,\n responseSchema: listTracesLightResponseSchema,\n summary: 'List lightweight traces',\n description:\n 'Returns a paginated list of lightweight traces with optional filtering and sorting. In delta mode, returns only newly listed traces matching the filters.',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, mode, after, limit, ...params }) => {\n try {\n const transformedParams = transformLegacyParams(params);\n\n const filters = pickParams(tracesFilterSchema, transformedParams);\n const observabilityStore = await getObservabilityStore(mastra);\n\n // Every current store answers `listTracesLight` — stores without a dedicated\n // implementation inherit the base class's projection fallback. This guard is\n // only for an older `@mastra/core` whose base class predates the method, where\n // calling it would throw `TypeError: ... is not a function`; there we fall back\n // to `listTraces` so consumers still get a response.\n const store = observabilityStore as { listTracesLight?: unknown };\n const supportsLight = typeof store.listTracesLight === 'function';\n\n if (mode === 'delta') {\n assertObservabilityDeltaSupported(observabilityStore, OBSERVABILITY_LIST_ENDPOINTS.traces);\n const deltaArgs = {\n mode,\n filters,\n after: typeof after === 'string' ? after : undefined,\n limit,\n } as const;\n return supportsLight\n ? await observabilityStore.listTracesLight(deltaArgs)\n : await observabilityStore.listTraces(deltaArgs);\n }\n\n const pagination = pickParams(paginationArgsSchema, transformedParams);\n const orderBy = pickParams(tracesOrderBySchema, transformedParams);\n\n if (!supportsLight) {\n return await observabilityStore.listTraces({ filters, pagination, orderBy });\n }\n return await observabilityStore.listTracesLight({ filters, pagination, orderBy });\n } catch (error) {\n return handleError(error, 'Error listing lightweight traces');\n }\n },\n});\n\n/** Route: GET /observability/branches - paginated branch-anchor span listing across all traces. */\nexport const LIST_BRANCHES_ROUTE = createRoute({\n method: 'GET',\n path: '/observability/branches',\n responseType: 'json',\n queryParamSchema: createObservabilityListQuerySchema(branchesFilterSchema, branchesOrderBySchema),\n responseSchema: listBranchesResponseSchema,\n summary: 'List trace branches',\n description:\n 'Returns a paginated list of branch-anchor spans (e.g., AGENT_RUN, WORKFLOW_RUN, TOOL_CALL) across all traces. Unlike listTraces (one row per root-rooted trace), each row here is a single anchor span -- including ones nested under a different root entity. In delta mode, returns only newly listed branch rows matching the filters.',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, mode, after, limit, ...params }) => {\n try {\n const filters = pickParams(branchesFilterSchema, params);\n const observabilityStore = await getObservabilityStore(mastra);\n if (mode === 'delta') {\n assertObservabilityDeltaSupported(observabilityStore, OBSERVABILITY_LIST_ENDPOINTS.branches);\n return await observabilityStore.listBranches({\n mode,\n filters,\n after: typeof after === 'string' ? after : undefined,\n limit,\n });\n }\n\n const pagination = pickParams(paginationArgsSchema, params);\n const orderBy = pickParams(branchesOrderBySchema, params);\n return await observabilityStore.listBranches({ filters, pagination, orderBy });\n } catch (error) {\n return handleError(error, 'Error listing branches');\n }\n },\n});\n\n/** Route: GET /observability/traces/:traceId/branches/:spanId - retrieve the subtree rooted at a span. */\nexport const GET_BRANCH_ROUTE = createRoute({\n method: 'GET',\n path: '/observability/traces/:traceId/branches/:spanId',\n responseType: 'json',\n pathParamSchema: getBranchArgsSchema.pick({ traceId: true, spanId: true }),\n queryParamSchema: wrapSchemaForQueryParams(getBranchArgsSchema.pick({ depth: true })),\n responseSchema: getBranchResponseSchema,\n summary: 'Get trace branch by span ID',\n description:\n 'Returns the subtree of spans rooted at the given span. The optional `depth` query param bounds descendant levels below the anchor (0 = anchor only; omitted = full subtree).',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, traceId, spanId, depth }) => {\n try {\n const observabilityStore = await getObservabilityStore(mastra);\n const branch = await observabilityStore.getBranch({ traceId, spanId, depth });\n\n if (!branch) {\n throw new HTTPException(404, { message: `Branch not found for span '${spanId}' in trace '${traceId}'` });\n }\n\n return branch;\n } catch (error) {\n return handleError(error, 'Error getting branch');\n }\n },\n});\n/** Route: GET /observability/traces/:traceId - retrieve a single trace with all spans. */\nexport const GET_TRACE_ROUTE: ServerRoute = createRoute({\n method: 'GET',\n path: '/observability/traces/:traceId',\n responseType: 'json',\n pathParamSchema: getTraceArgsSchema,\n responseSchema: getTraceResponseSchema.extend({ spans: z.array(traceSpanSchema) }),\n summary: 'Get AI trace by ID',\n description: 'Returns a complete AI trace with all spans by trace ID',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, traceId }) => {\n try {\n const observabilityStore = await getObservabilityStore(mastra);\n const trace = await observabilityStore.getTrace({ traceId });\n\n if (!trace) {\n throw new HTTPException(404, { message: `Trace with ID '${traceId}' not found` });\n }\n\n // Stored SpanRecords carry no status field; derive it from error/endedAt so\n // trace-detail spans match the status shown in trace list rows.\n return { ...trace, spans: toTraceSpans(trace.spans) };\n } catch (error) {\n return handleError(error, 'Error getting trace');\n }\n },\n});\n\n/** Route: GET /observability/traces/:traceId/light - lightweight trace for timeline rendering. */\nexport const GET_TRACE_LIGHT_ROUTE: ServerRoute = createRoute({\n method: 'GET',\n path: '/observability/traces/:traceId/light',\n responseType: 'json',\n pathParamSchema: getTraceArgsSchema,\n responseSchema: getTraceLightResponseSchema,\n summary: 'Get lightweight AI trace by ID',\n description:\n 'Returns a trace with lightweight span data (timeline fields only, excludes input/output/attributes/metadata/tags/links)',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, traceId }) => {\n try {\n const observabilityStore = await getObservabilityStore(mastra);\n const trace = await observabilityStore.getTraceLight({ traceId });\n\n if (!trace) {\n throw new HTTPException(404, { message: `Trace with ID '${traceId}' not found` });\n }\n\n return trace;\n } catch (error) {\n return handleError(error, 'Error getting lightweight trace');\n }\n },\n});\n\n/** Route: GET /observability/traces/:traceId/spans/:spanId - get a single span with full details. */\nexport const GET_SPAN_ROUTE: ServerRoute = createRoute({\n method: 'GET',\n path: '/observability/traces/:traceId/spans/:spanId',\n responseType: 'json',\n pathParamSchema: getSpanArgsSchema,\n responseSchema: getSpanResponseSchema,\n summary: 'Get a single span by ID',\n description: 'Returns a complete span record with all details by trace ID and span ID',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, traceId, spanId }) => {\n try {\n const observabilityStore = await getObservabilityStore(mastra);\n const span = await observabilityStore.getSpan({ traceId, spanId });\n\n if (!span) {\n throw new HTTPException(404, { message: `Span not found` });\n }\n\n return span;\n } catch (error) {\n return handleError(error, 'Error getting span');\n }\n },\n});\n\n/** Route: GET /observability/traces/:traceId/trajectory - extract trajectory from a trace. */\nexport const GET_TRACE_TRAJECTORY_ROUTE = createRoute({\n method: 'GET',\n path: '/observability/traces/:traceId/trajectory',\n responseType: 'json',\n pathParamSchema: getTraceArgsSchema,\n responseSchema: z.object({\n steps: z.array(z.unknown()),\n totalDurationMs: z.number().optional(),\n rawOutput: z.unknown().optional(),\n rawWorkflowResult: z.unknown().optional(),\n }),\n summary: 'Extract trajectory from trace',\n description: 'Extracts a structured trajectory (ordered steps) from a trace by analyzing its spans',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, traceId }) => {\n try {\n const observabilityStore = await getObservabilityStore(mastra);\n const trace = await observabilityStore.getTrace({ traceId });\n\n if (!trace) {\n throw new HTTPException(404, { message: `Trace with ID '${traceId}' not found` });\n }\n\n const trajectory = extractTrajectoryFromTrace(trace.spans);\n return trajectory;\n } catch (error) {\n return handleError(error, 'Error extracting trajectory from trace');\n }\n },\n});\n\n/** Route: POST /observability/traces/delete - batch delete traces with cross-signal cascade. */\nexport const DELETE_TRACES_ROUTE: ServerRoute = createRoute({\n method: 'POST',\n path: '/observability/traces/delete',\n responseType: 'json',\n bodySchema: batchDeleteTracesArgsSchema.pick({ traceIds: true }),\n responseSchema: batchDeleteTracesResponseSchema,\n maxBodySize: 256 * 1024,\n summary: 'Delete traces',\n description:\n 'Deletes traces by ID, cascading to all associated data: spans, trace roots/branches, and signal events (scores, feedback, metrics, logs) that reference the deleted traces. Signals without a trace ID are untouched. Experiment traces are deleted like any other trace. On ClickHouse-backed stores, deletes are lightweight and reads may briefly return deleted rows until the delete is fully applied.',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, traceIds }) => {\n try {\n const observabilityStore = await getObservabilityStore(mastra);\n await observabilityStore.batchDeleteTraces({ traceIds });\n return { success: true as const };\n } catch (error) {\n return handleError(error, 'Error deleting traces');\n }\n },\n});\n\n/** Route: POST /observability/traces/score - score traces using a specified scorer (fire-and-forget). */\nexport const SCORE_TRACES_ROUTE = createRoute({\n method: 'POST',\n path: '/observability/traces/score',\n responseType: 'json',\n bodySchema: scoreTracesRequestSchema,\n responseSchema: scoreTracesResponseSchema,\n summary: 'Score traces',\n description: 'Scores one or more traces using a specified scorer (fire-and-forget)',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, ...params }) => {\n try {\n // Validate storage exists before starting background task\n getStorage(mastra);\n\n const { scorerName, targets } = params;\n\n const scorer = mastra.getScorerById(scorerName);\n if (!scorer) {\n throw new HTTPException(404, { message: `Scorer '${scorerName}' not found` });\n }\n\n scoreTraces({\n scorerId: scorer.config.id || scorer.config.name,\n targets,\n mastra,\n }).catch(error => {\n const logger = mastra.getLogger();\n logger?.error(`Background trace scoring failed: ${error.message}`, error);\n });\n\n return {\n status: 'success',\n message: `Scoring started for ${targets.length} ${targets.length === 1 ? 'trace' : 'traces'}`,\n traceCount: targets.length,\n };\n } catch (error) {\n return handleError(error, 'Error processing trace scoring');\n }\n },\n});\n\nexport const LIST_SCORES_BY_SPAN_ROUTE = createRoute({\n method: 'GET',\n path: '/observability/traces/:traceId/:spanId/scores',\n responseType: 'json',\n pathParamSchema: spanIdsSchema,\n // List endpoints accept optional query params; use partial() to allow empty queries.\n queryParamSchema: wrapSchemaForQueryParams(paginationArgsSchema.partial()),\n responseSchema: listScoresResponseSchema,\n summary: 'List scores by span',\n description: 'Returns all scores for a specific span within a trace',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, ...params }) => {\n try {\n const pagination = pickParams(paginationArgsSchema, params);\n const spanIds = pickParams(spanIdsSchema, params);\n\n const scoresStore = await getScoresStore(mastra);\n\n return await scoresStore.listScoresBySpan({\n ...spanIds,\n pagination,\n });\n } catch (error) {\n return handleError(error, 'Error getting scores by span');\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,MAAM,0BAA0B,EAAE,OAAO;CAEvC,WAAW,gBAAgB,SAAS;CAEpC,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS;CAE1B,YAAY,EAAE,YAAW,QAAQ,QAAQ,aAAa,iBAAiB,KAAM,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC;AACpG,CAAC;;;;;;;;AASD,SAAS,sBAAsB,QAA0D;CACvF,MAAM,SAAS,EAAE,GAAG,OAAO;CAG3B,IAAI,OAAO,eAAe,YACxB,OAAO,aAAa;CAItB,IAAI,OAAO,aAAa,CAAC,OAAO,WAAW;EACzC,OAAO,YAAY,OAAO;EAC1B,OAAO,OAAO;CACh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AO,EAAE,QAAQ,GAAG,aAAa;EACxC,IAAI;GAEF,WAAW,MAAM;GAEjB,MAAM,EAAE,YAAY,YAAY;GAEhC,MAAM,SAAS,OAAO,cAAc,UAAU;GAC9C,IAAI,CAAC,QACH,MAAM,IAAI,cAAc,KAAK,EAAE,SAAS,WAAW,WAAW,aAAa,CAAC;GAG9E,YAAY;IACV,UAAU,OAAO,OAAO,MAAM,OAAO,OAAO;IAC5C;IACA;GACF,CAAC,CAAC,CAAC,OAAM,UAAS;IAEhB,OADsB,UACjB,CAAC,EAAE,MAAM,oCAAoC,MAAM,WAAW,KAAK;GAC1E,CAAC;GAED,OAAO;IACL,QAAQ;IACR,SAAS,uBAAuB,QAAQ,OAAO,GAAG,QAAQ,WAAW,IAAI,UAAU;IACnF,YAAY,QAAQ;GACtB;EACF,SAAS,OAAO;GACd,OAAO,YAAY,OAAO,gCAAgC;EAC5D;CACF;AACF,CAAC;AAED,MAAa,4BAA4B,YAAY;CACnD,QAAQ;CACR,MAAM;CACN,cAAc;CACd,iBAAiB;CAEjB,kBAAkB,yBAAyB,qBAAqB,QAAQ,CAAC;CACzE,gBAAgB;CAChB,SAAS;CACT,aAAa;CACb,MAAM,CAAC,eAAe;CACtB,cAAc;CACd,SAAS,OAAO,EAAE,QAAQ,GAAG,aAAa;EACxC,IAAI;GACF,MAAM,aAAa,WAAW,sBAAsB,MAAM;GAC1D,MAAM,UAAU,WAAW,eAAe,MAAM;GAIhD,OAAO,OAAM,MAFa,eAAe,MAAM,EAAA,CAEtB,iBAAiB;IACxC,GAAG;IACH;GACF,CAAC;EACH,SAAS,OAAO;GACd,OAAO,YAAY,OAAO,8BAA8B;EAC1D;CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"observability.js","names":["store"],"sources":["../../../src/server/handlers/observability.ts"],"sourcesContent":["import { extractTrajectoryFromTrace, listScoresResponseSchema } from '@mastra/core/evals';\nimport { scoreTraces } from '@mastra/core/evals/scoreTraces';\nimport {\n tracesFilterSchema,\n tracesOrderBySchema,\n spanIdsSchema,\n listTracesResponseSchema,\n scoreTracesRequestSchema,\n scoreTracesResponseSchema,\n getTraceArgsSchema,\n getTraceResponseSchema,\n getTraceLightResponseSchema,\n getSpanArgsSchema,\n getSpanResponseSchema,\n dateRangeSchema,\n toTraceSpans,\n traceSpanSchema,\n} from '@mastra/core/storage';\n// `branches*`, `listBranches*`, and `getBranch*` schemas are new in\n// @mastra/core@1.32.0; route them through a shim that tolerates older cores\n// (see ./observability-storage-schemas.ts for full rationale).\nimport { z } from 'zod/v4';\nimport { HTTPException } from '../http-exception';\nimport type { ServerRoute } from '../server-adapter/routes';\nimport { createRoute, pickParams, wrapSchemaForQueryParams } from '../server-adapter/routes/route-builder';\nimport { handleError } from './error';\nimport { paginationArgsSchema } from './observability-list-query-schemas';\nimport {\n assertObservabilityDeltaSupported,\n createObservabilityListQuerySchema,\n getObservabilityStore,\n getScoresStore,\n getStorage,\n OBSERVABILITY_LIST_ENDPOINTS,\n} from './observability-shared';\nimport {\n branchesFilterSchema,\n branchesOrderBySchema,\n listBranchesResponseSchema,\n getBranchArgsSchema,\n getBranchResponseSchema,\n listTracesLightResponseSchema,\n batchDeleteTracesArgsSchema,\n batchDeleteTracesResponseSchema,\n} from './observability-storage-schemas';\n\nexport * from './observability-new-endpoints';\n\n// ============================================================================\n// Legacy Parameter Support (backward compatibility with main branch API)\n// ============================================================================\n\n/**\n * Legacy query parameters from the old API (main branch).\n * These are accepted for backward compatibility and transformed to new format.\n */\nconst legacyQueryParamsSchema = z.object({\n // Old: dateRange was in pagination, now it's startedAt in filters\n dateRange: dateRangeSchema.optional(),\n // Old: name matched span names like \"agent run: 'myAgent'\"\n name: z.string().optional(),\n // entityType needs preprocessing to handle legacy 'workflow' value\n entityType: z.preprocess(val => (val === 'workflow' ? 'workflow_run' : val), z.string().optional()),\n});\n\n/**\n * Transforms legacy query parameters to the new format.\n * - dateRange -> startedAt (if startedAt not already set)\n * - name=\"agent run: 'x'\" -> entityId='x', entityType='agent'\n * - name=\"workflow run: 'x'\" -> entityId='x', entityType='workflow_run'\n * - entityType='workflow' -> entityType='workflow_run' (enum value fix)\n */\nfunction transformLegacyParams(params: Record<string, unknown>): Record<string, unknown> {\n const result = { ...params };\n\n // Transform old entityType='workflow' -> 'workflow_run' to support direct handler usage in tests\n if (result.entityType === 'workflow') {\n result.entityType = 'workflow_run';\n }\n\n // Transform old dateRange -> new startedAt\n if (params.dateRange && !params.startedAt) {\n result.startedAt = params.dateRange;\n delete result.dateRange;\n }\n\n // Transform old name -> entityId + entityType\n // Old format: name matched span names like \"agent run: 'myAgent'\" or \"workflow run: 'myWorkflow'\"\n if (typeof params.name === 'string' && !params.entityId) {\n const agentMatch = params.name.match(/^agent run: '([^']+)'$/);\n const workflowMatch = params.name.match(/^workflow run: '([^']+)'$/);\n\n if (agentMatch) {\n result.entityId = agentMatch[1];\n result.entityType = 'agent';\n } else if (workflowMatch) {\n result.entityId = workflowMatch[1];\n result.entityType = 'workflow_run';\n }\n delete result.name;\n }\n\n return result;\n}\n\n// ============================================================================\n// Route Definitions (new pattern - handlers defined inline with createRoute)\n// ============================================================================\n\n/** Filter shape shared by the full and lightweight trace list routes. */\nconst tracesListFilterSchema = tracesFilterSchema.extend({\n ...legacyQueryParamsSchema.shape, // Accept legacy params for backward compatibility\n entityType: z.preprocess(\n value => (value === 'workflow' ? 'workflow_run' : value),\n tracesFilterSchema.shape.entityType,\n ),\n});\n\nconst listTracesQueryParamSchema = createObservabilityListQuerySchema(tracesListFilterSchema, tracesOrderBySchema);\n\n/** Route: GET /observability/traces - paginated trace listing with filtering and sorting. */\nexport const LIST_TRACES_ROUTE: ServerRoute = createRoute({\n method: 'GET',\n path: '/observability/traces',\n responseType: 'json',\n queryParamSchema: listTracesQueryParamSchema,\n responseSchema: listTracesResponseSchema,\n summary: 'List traces',\n description:\n 'Returns a paginated list of traces with optional filtering and sorting. In delta mode, returns only newly listed traces matching the filters.',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, mode, after, limit, ...params }) => {\n try {\n // Transform legacy params to new format before processing\n const transformedParams = transformLegacyParams(params);\n\n const filters = pickParams(tracesFilterSchema, transformedParams);\n const observabilityStore = await getObservabilityStore(mastra);\n if (mode === 'delta') {\n assertObservabilityDeltaSupported(observabilityStore, OBSERVABILITY_LIST_ENDPOINTS.traces);\n return await observabilityStore.listTraces({\n mode,\n filters,\n after: typeof after === 'string' ? after : undefined,\n limit,\n });\n }\n\n const pagination = pickParams(paginationArgsSchema, transformedParams);\n const orderBy = pickParams(tracesOrderBySchema, transformedParams);\n return await observabilityStore.listTraces({ filters, pagination, orderBy });\n } catch (error) {\n return handleError(error, 'Error listing traces');\n }\n },\n});\n\n/** Route: GET /observability/traces/light - paginated lightweight trace listing with filtering and sorting. */\nexport const LIST_TRACES_LIGHT_ROUTE = createRoute({\n method: 'GET',\n path: '/observability/traces/light',\n responseType: 'json',\n queryParamSchema: listTracesQueryParamSchema,\n responseSchema: listTracesLightResponseSchema,\n summary: 'List lightweight traces',\n description:\n 'Returns a paginated list of lightweight traces with optional filtering and sorting. In delta mode, returns only newly listed traces matching the filters.',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, mode, after, limit, ...params }) => {\n try {\n const transformedParams = transformLegacyParams(params);\n\n const filters = pickParams(tracesFilterSchema, transformedParams);\n const observabilityStore = await getObservabilityStore(mastra);\n\n // Every current store answers `listTracesLight` — stores without a dedicated\n // implementation inherit the base class's projection fallback. This guard is\n // only for an older `@mastra/core` whose base class predates the method, where\n // calling it would throw `TypeError: ... is not a function`; there we fall back\n // to `listTraces` so consumers still get a response.\n const store = observabilityStore as { listTracesLight?: unknown };\n const supportsLight = typeof store.listTracesLight === 'function';\n\n if (mode === 'delta') {\n assertObservabilityDeltaSupported(observabilityStore, OBSERVABILITY_LIST_ENDPOINTS.traces);\n const deltaArgs = {\n mode,\n filters,\n after: typeof after === 'string' ? after : undefined,\n limit,\n } as const;\n return supportsLight\n ? await observabilityStore.listTracesLight(deltaArgs)\n : await observabilityStore.listTraces(deltaArgs);\n }\n\n const pagination = pickParams(paginationArgsSchema, transformedParams);\n const orderBy = pickParams(tracesOrderBySchema, transformedParams);\n\n if (!supportsLight) {\n return await observabilityStore.listTraces({ filters, pagination, orderBy });\n }\n return await observabilityStore.listTracesLight({ filters, pagination, orderBy });\n } catch (error) {\n return handleError(error, 'Error listing lightweight traces');\n }\n },\n});\n\n/** Route: GET /observability/branches - paginated branch-anchor span listing across all traces. */\nexport const LIST_BRANCHES_ROUTE = createRoute({\n method: 'GET',\n path: '/observability/branches',\n responseType: 'json',\n queryParamSchema: createObservabilityListQuerySchema(branchesFilterSchema, branchesOrderBySchema),\n responseSchema: listBranchesResponseSchema,\n summary: 'List trace branches',\n description:\n 'Returns a paginated list of branch-anchor spans (e.g., AGENT_RUN, WORKFLOW_RUN, TOOL_CALL) across all traces. Unlike listTraces (one row per root-rooted trace), each row here is a single anchor span -- including ones nested under a different root entity. In delta mode, returns only newly listed branch rows matching the filters.',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, mode, after, limit, ...params }) => {\n try {\n const filters = pickParams(branchesFilterSchema, params);\n const observabilityStore = await getObservabilityStore(mastra);\n if (mode === 'delta') {\n assertObservabilityDeltaSupported(observabilityStore, OBSERVABILITY_LIST_ENDPOINTS.branches);\n return await observabilityStore.listBranches({\n mode,\n filters,\n after: typeof after === 'string' ? after : undefined,\n limit,\n });\n }\n\n const pagination = pickParams(paginationArgsSchema, params);\n const orderBy = pickParams(branchesOrderBySchema, params);\n return await observabilityStore.listBranches({ filters, pagination, orderBy });\n } catch (error) {\n return handleError(error, 'Error listing branches');\n }\n },\n});\n\n/** Route: GET /observability/traces/:traceId/branches/:spanId - retrieve the subtree rooted at a span. */\nexport const GET_BRANCH_ROUTE = createRoute({\n method: 'GET',\n path: '/observability/traces/:traceId/branches/:spanId',\n responseType: 'json',\n pathParamSchema: getBranchArgsSchema.pick({ traceId: true, spanId: true }),\n queryParamSchema: wrapSchemaForQueryParams(getBranchArgsSchema.pick({ depth: true })),\n responseSchema: getBranchResponseSchema,\n summary: 'Get trace branch by span ID',\n description:\n 'Returns the subtree of spans rooted at the given span. The optional `depth` query param bounds descendant levels below the anchor (0 = anchor only; omitted = full subtree).',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, traceId, spanId, depth }) => {\n try {\n const observabilityStore = await getObservabilityStore(mastra);\n const branch = await observabilityStore.getBranch({ traceId, spanId, depth });\n\n if (!branch) {\n throw new HTTPException(404, { message: `Branch not found for span '${spanId}' in trace '${traceId}'` });\n }\n\n return branch;\n } catch (error) {\n return handleError(error, 'Error getting branch');\n }\n },\n});\n/** Route: GET /observability/traces/:traceId - retrieve a single trace with all spans. */\nexport const GET_TRACE_ROUTE: ServerRoute = createRoute({\n method: 'GET',\n path: '/observability/traces/:traceId',\n responseType: 'json',\n pathParamSchema: getTraceArgsSchema,\n responseSchema: getTraceResponseSchema.extend({ spans: z.array(traceSpanSchema) }),\n summary: 'Get AI trace by ID',\n description: 'Returns a complete AI trace with all spans by trace ID',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, traceId }) => {\n try {\n const observabilityStore = await getObservabilityStore(mastra);\n const trace = await observabilityStore.getTrace({ traceId });\n\n if (!trace) {\n throw new HTTPException(404, { message: `Trace with ID '${traceId}' not found` });\n }\n\n // Stored SpanRecords carry no status field; derive it from error/endedAt so\n // trace-detail spans match the status shown in trace list rows.\n return { ...trace, spans: toTraceSpans(trace.spans) };\n } catch (error) {\n return handleError(error, 'Error getting trace');\n }\n },\n});\n\n/** Route: GET /observability/traces/:traceId/light - lightweight trace for timeline rendering. */\nexport const GET_TRACE_LIGHT_ROUTE: ServerRoute = createRoute({\n method: 'GET',\n path: '/observability/traces/:traceId/light',\n responseType: 'json',\n pathParamSchema: getTraceArgsSchema,\n responseSchema: getTraceLightResponseSchema,\n summary: 'Get lightweight AI trace by ID',\n description:\n 'Returns a trace with lightweight span data (timeline fields only, excludes input/output/attributes/metadata/tags/links)',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, traceId }) => {\n try {\n const observabilityStore = await getObservabilityStore(mastra);\n const trace = await observabilityStore.getTraceLight({ traceId });\n\n if (!trace) {\n throw new HTTPException(404, { message: `Trace with ID '${traceId}' not found` });\n }\n\n return trace;\n } catch (error) {\n return handleError(error, 'Error getting lightweight trace');\n }\n },\n});\n\n/** Route: GET /observability/traces/:traceId/spans/:spanId - get a single span with full details. */\nexport const GET_SPAN_ROUTE: ServerRoute = createRoute({\n method: 'GET',\n path: '/observability/traces/:traceId/spans/:spanId',\n responseType: 'json',\n pathParamSchema: getSpanArgsSchema,\n responseSchema: getSpanResponseSchema,\n summary: 'Get a single span by ID',\n description: 'Returns a complete span record with all details by trace ID and span ID',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, traceId, spanId }) => {\n try {\n const observabilityStore = await getObservabilityStore(mastra);\n const span = await observabilityStore.getSpan({ traceId, spanId });\n\n if (!span) {\n throw new HTTPException(404, { message: `Span not found` });\n }\n\n return span;\n } catch (error) {\n return handleError(error, 'Error getting span');\n }\n },\n});\n\n/** Route: GET /observability/traces/:traceId/trajectory - extract trajectory from a trace. */\nexport const GET_TRACE_TRAJECTORY_ROUTE = createRoute({\n method: 'GET',\n path: '/observability/traces/:traceId/trajectory',\n responseType: 'json',\n pathParamSchema: getTraceArgsSchema,\n responseSchema: z.object({\n steps: z.array(z.unknown()),\n totalDurationMs: z.number().optional(),\n rawOutput: z.unknown().optional(),\n rawWorkflowResult: z.unknown().optional(),\n }),\n summary: 'Extract trajectory from trace',\n description: 'Extracts a structured trajectory (ordered steps) from a trace by analyzing its spans',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, traceId }) => {\n try {\n const observabilityStore = await getObservabilityStore(mastra);\n const trace = await observabilityStore.getTrace({ traceId });\n\n if (!trace) {\n throw new HTTPException(404, { message: `Trace with ID '${traceId}' not found` });\n }\n\n const trajectory = extractTrajectoryFromTrace(trace.spans);\n return trajectory;\n } catch (error) {\n return handleError(error, 'Error extracting trajectory from trace');\n }\n },\n});\n\n/** Route: POST /observability/traces/delete - batch delete traces with cross-signal cascade. */\nexport const DELETE_TRACES_ROUTE: ServerRoute = createRoute({\n method: 'POST',\n path: '/observability/traces/delete',\n responseType: 'json',\n bodySchema: batchDeleteTracesArgsSchema.pick({ traceIds: true }),\n responseSchema: batchDeleteTracesResponseSchema,\n maxBodySize: 256 * 1024,\n summary: 'Delete traces',\n description:\n 'Deletes traces by ID, cascading to all associated data: spans, trace roots/branches, and signal events (scores, feedback, metrics, logs) that reference the deleted traces. Signals without a trace ID are untouched. Experiment traces are deleted like any other trace. On ClickHouse-backed stores, deletes are lightweight and reads may briefly return deleted rows until the delete is fully applied.',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, traceIds }) => {\n try {\n const observabilityStore = await getObservabilityStore(mastra);\n await observabilityStore.batchDeleteTraces({ traceIds });\n return { success: true as const };\n } catch (error) {\n return handleError(error, 'Error deleting traces');\n }\n },\n});\n\n/** Route: POST /observability/traces/score - score traces using a specified scorer (fire-and-forget). */\nexport const SCORE_TRACES_ROUTE = createRoute({\n method: 'POST',\n path: '/observability/traces/score',\n responseType: 'json',\n bodySchema: scoreTracesRequestSchema,\n responseSchema: scoreTracesResponseSchema,\n summary: 'Score traces',\n description: 'Scores one or more traces using a specified scorer (fire-and-forget)',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, ...params }) => {\n try {\n // Validate storage exists before starting background task\n getStorage(mastra);\n\n const { scorerName, targets } = params;\n\n const scorer = mastra.getScorerById(scorerName);\n if (!scorer) {\n throw new HTTPException(404, { message: `Scorer '${scorerName}' not found` });\n }\n\n scoreTraces({\n scorerId: scorer.config.id || scorer.config.name,\n targets,\n mastra,\n }).catch(error => {\n const logger = mastra.getLogger();\n logger?.error(`Background trace scoring failed: ${error.message}`, error);\n });\n\n return {\n status: 'success',\n message: `Scoring started for ${targets.length} ${targets.length === 1 ? 'trace' : 'traces'}`,\n traceCount: targets.length,\n };\n } catch (error) {\n return handleError(error, 'Error processing trace scoring');\n }\n },\n});\n\nexport const LIST_SCORES_BY_SPAN_ROUTE = createRoute({\n method: 'GET',\n path: '/observability/traces/:traceId/:spanId/scores',\n responseType: 'json',\n pathParamSchema: spanIdsSchema,\n // List endpoints accept optional query params; use partial() to allow empty queries.\n queryParamSchema: wrapSchemaForQueryParams(paginationArgsSchema.partial()),\n responseSchema: listScoresResponseSchema,\n summary: 'List scores by span',\n description: 'Returns all scores for a specific span within a trace',\n tags: ['Observability'],\n requiresAuth: true,\n handler: async ({ mastra, ...params }) => {\n try {\n const pagination = pickParams(paginationArgsSchema, params);\n const spanIds = pickParams(spanIdsSchema, params);\n\n const scoresStore = await getScoresStore(mastra);\n\n return await scoresStore.listScoresBySpan({\n ...spanIds,\n pagination,\n });\n } catch (error) {\n return handleError(error, 'Error getting scores by span');\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,MAAM,0BAA0B,EAAE,OAAO;CAEvC,WAAW,gBAAgB,SAAS;CAEpC,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS;CAE1B,YAAY,EAAE,YAAW,QAAQ,QAAQ,aAAa,iBAAiB,KAAM,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC;AACpG,CAAC;;;;;;;;AASD,SAAS,sBAAsB,QAA0D;CACvF,MAAM,SAAS,EAAE,GAAG,OAAO;CAG3B,IAAI,OAAO,eAAe,YACxB,OAAO,aAAa;CAItB,IAAI,OAAO,aAAa,CAAC,OAAO,WAAW;EACzC,OAAO,YAAY,OAAO;EAC1B,OAAO,OAAO;CAChB;CAIA,IAAI,OAAO,OAAO,SAAS,YAAY,CAAC,OAAO,UAAU;EACvD,MAAM,aAAa,OAAO,KAAK,MAAM,wBAAwB;EAC7D,MAAM,gBAAgB,OAA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;GAC9C,IAAI,CAAC,QACH,MAAM,IAAI,cAAc,KAAK,EAAE,SAAS,WAAW,WAAW,aAAa,CAAC;GAG9E,YAAY;IACV,UAAU,OAAO,OAAO,MAAM,OAAO,OAAO;IAC5C;IACA;GACF,CAAC,CAAC,CAAC,OAAM,UAAS;IAEhB,OADsB,UACjB,CAAC,EAAE,MAAM,oCAAoC,MAAM,WAAW,KAAK;GAC1E,CAAC;GAED,OAAO;IACL,QAAQ;IACR,SAAS,uBAAuB,QAAQ,OAAO,GAAG,QAAQ,WAAW,IAAI,UAAU;IACnF,YAAY,QAAQ;GACtB;EACF,SAAS,OAAO;GACd,OAAO,YAAY,OAAO,gCAAgC;EAC5D;CACF;AACF,CAAC;AAED,MAAa,4BAA4B,YAAY;CACnD,QAAQ;CACR,MAAM;CACN,cAAc;CACd,iBAAiB;CAEjB,kBAAkB,yBAAyB,qBAAqB,QAAQ,CAAC;CACzE,gBAAgB;CAChB,SAAS;CACT,aAAa;CACb,MAAM,CAAC,eAAe;CACtB,cAAc;CACd,SAAS,OAAO,EAAE,QAAQ,GAAG,aAAa;EACxC,IAAI;GACF,MAAM,aAAa,WAAW,sBAAsB,MAAM;GAC1D,MAAM,UAAU,WAAW,eAAe,MAAM;GAIhD,OAAO,OAAM,MAFa,eAAe,MAAM,EAAA,CAEtB,iBAAiB;IACxC,GAAG;IACH;GACF,CAAC;EACH,SAAS,OAAO;GACd,OAAO,YAAY,OAAO,8BAA8B;EAC1D;CACF;AACF,CAAC"}
|
|
@@ -3,7 +3,7 @@ require("../../rolldown-runtime-Bd6kNlEP.cjs");
|
|
|
3
3
|
const require_http_exception = require("../../http-exception-CKDHupKw.cjs");
|
|
4
4
|
const require_route_builder = require("../../route-builder-2yrD15TL.cjs");
|
|
5
5
|
const require_server_handlers_error = require("./error.cjs");
|
|
6
|
-
const require_processors = require("../../processors-
|
|
6
|
+
const require_processors = require("../../processors-80HWq8nr.cjs");
|
|
7
7
|
let _mastra_core_agent = require("@mastra/core/agent");
|
|
8
8
|
let _mastra_core_processors = require("@mastra/core/processors");
|
|
9
9
|
//#region src/server/handlers/processors.ts
|
|
@@ -39,6 +39,7 @@ function detectProcessorPhases(processor) {
|
|
|
39
39
|
if (typeof processor.processOutputResult === "function") phases.push("outputResult");
|
|
40
40
|
if (typeof processor.processOutputStep === "function") phases.push("outputStep");
|
|
41
41
|
if (typeof processor.processToolResult === "function") phases.push("toolResult");
|
|
42
|
+
if (typeof processor.processLLMRequest === "function") phases.push("llmRequest");
|
|
42
43
|
return phases;
|
|
43
44
|
}
|
|
44
45
|
const LIST_PROCESSORS_ROUTE = require_route_builder.createRoute({
|
|
@@ -139,6 +140,7 @@ const EXECUTE_PROCESSOR_ROUTE = require_route_builder.createRoute({
|
|
|
139
140
|
const { phase, messages } = bodyParams;
|
|
140
141
|
if (!processorId) throw new require_http_exception.HTTPException(400, { message: "Processor ID is required" });
|
|
141
142
|
if (!phase) throw new require_http_exception.HTTPException(400, { message: "Phase is required" });
|
|
143
|
+
if (phase === "llmRequest") throw new require_http_exception.HTTPException(400, { message: "llmRequest phase cannot be executed directly. It runs on the provider prompt during an agent call." });
|
|
142
144
|
if (!messages || !Array.isArray(messages)) throw new require_http_exception.HTTPException(400, { message: "Messages array is required" });
|
|
143
145
|
let processor;
|
|
144
146
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"processors.cjs","names":["createRoute","listProcessorsResponseSchema","handleError","processorIdPathParams","serializedProcessorDetailSchema","HTTPException","executeProcessorBodySchema","executeProcessorResponseSchema","MessageList"],"sources":["../../../src/server/handlers/processors.ts"],"sourcesContent":["import { MessageList } from '@mastra/core/agent';\nimport type { MessageInput } from '@mastra/core/agent/message-list';\nimport { isProcessorWorkflow } from '@mastra/core/processors';\nimport type { Processor, ProcessorWorkflow } from '@mastra/core/processors';\n\nimport { HTTPException } from '../http-exception';\nimport {\n listProcessorsResponseSchema,\n serializedProcessorDetailSchema,\n processorIdPathParams,\n executeProcessorBodySchema,\n executeProcessorResponseSchema,\n} from '../schemas/processors';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { handleError } from './error';\n\n// ============================================================================\n// Route Definitions\n// ============================================================================\n\ntype ProcessorPhase = 'input' | 'inputStep' | 'outputStream' | 'outputResult' | 'outputStep' | 'toolResult';\n\n/**\n * Helper to extract text from messages for outputStep testing.\n * In real usage, the `text` field contains the assistant's response text.\n */\nfunction extractTextFromMessages(messages: unknown[]): string {\n if (!messages || !Array.isArray(messages) || messages.length === 0) {\n return '';\n }\n const firstMessage = messages[0] as any;\n if (firstMessage?.content?.parts) {\n const textParts = firstMessage.content.parts\n .filter((part: any) => part?.type === 'text')\n .map((part: any) => part?.text || '');\n return textParts.join('');\n }\n return '';\n}\n\n/**\n * Helper to detect phases for a processor.\n * For individual processors, checks which methods are implemented.\n * For workflow processors, returns all phases since createStep handles each phase\n * and it's a no-op if the underlying processor doesn't implement it.\n */\nfunction detectProcessorPhases(processor: any): ProcessorPhase[] {\n // Check if it's a workflow processor\n if (isProcessorWorkflow(processor)) {\n // Workflow processors can potentially handle all phases\n // The createStep in workflows handles each phase and it's a no-op if not implemented\n return ['input', 'inputStep', 'outputStream', 'outputResult', 'outputStep', 'toolResult'];\n }\n\n // For individual processors, detect by checking which methods exist\n const phases: ProcessorPhase[] = [];\n if (typeof processor.processInput === 'function') {\n phases.push('input');\n }\n if (typeof processor.processInputStep === 'function') {\n phases.push('inputStep');\n }\n if (typeof processor.processOutputStream === 'function') {\n phases.push('outputStream');\n }\n if (typeof processor.processOutputResult === 'function') {\n phases.push('outputResult');\n }\n if (typeof processor.processOutputStep === 'function') {\n phases.push('outputStep');\n }\n if (typeof processor.processToolResult === 'function') {\n phases.push('toolResult');\n }\n return phases;\n}\n\nexport const LIST_PROCESSORS_ROUTE = createRoute({\n method: 'GET',\n path: '/processors',\n responseType: 'json',\n responseSchema: listProcessorsResponseSchema,\n summary: 'List all processors',\n description: 'Returns a list of all available individual processors',\n tags: ['Processors'],\n requiresAuth: true,\n handler: async ({ mastra }) => {\n try {\n const processors = mastra.listProcessors() || {};\n const processorConfigurations = mastra.listProcessorConfigurations();\n const result: Record<\n string,\n {\n id: string;\n name?: string;\n description?: string;\n phases: ProcessorPhase[];\n agentIds: string[];\n configurations: Array<{ agentId: string; type: 'input' | 'output' }>;\n isWorkflow: boolean;\n }\n > = {};\n\n // Iterate through all individual processors registered with Mastra\n for (const [processorKey, processorEntry] of Object.entries(processors)) {\n const processor = processorEntry as Processor | ProcessorWorkflow;\n const processorId = processor.id || processorKey;\n\n // Check if it's a workflow processor\n const isWorkflow = isProcessorWorkflow(processor);\n\n // Detect phases (handles both individual processors and workflow processors)\n const phases = detectProcessorPhases(processor);\n\n // Get agent configurations for this processor\n const configs = processorConfigurations.get(processorId) || [];\n const agentIds = [...new Set(configs.map(c => c.agentId))];\n const configurations = configs.map(c => ({ agentId: c.agentId, type: c.type }));\n\n result[processorId] = {\n id: processorId,\n name: processor.name || processorId,\n description: processor.description,\n phases,\n agentIds,\n configurations,\n isWorkflow,\n };\n }\n\n return result;\n } catch (error) {\n return handleError(error, 'Error getting processors');\n }\n },\n});\n\nexport const GET_PROCESSOR_BY_ID_ROUTE = createRoute({\n method: 'GET',\n path: '/processors/:processorId',\n responseType: 'json',\n pathParamSchema: processorIdPathParams,\n responseSchema: serializedProcessorDetailSchema,\n summary: 'Get processor by ID',\n description: 'Returns details for a specific processor including its phases and configurations',\n tags: ['Processors'],\n requiresAuth: true,\n handler: async ({ mastra, processorId }) => {\n try {\n // Get the processor from Mastra's registered processors\n let processorEntry: Processor | ProcessorWorkflow | undefined;\n try {\n processorEntry = mastra.getProcessorById(processorId) as Processor | ProcessorWorkflow;\n } catch {\n // getProcessorById throws if not found, try by key\n const processors = mastra.listProcessors() || {};\n processorEntry = processors[processorId as keyof typeof processors] as Processor | ProcessorWorkflow;\n }\n\n if (!processorEntry) {\n throw new HTTPException(404, { message: 'Processor not found' });\n }\n\n // Check if it's a workflow processor\n const isWorkflow = isProcessorWorkflow(processorEntry);\n\n // Detect phases (handles both individual processors and workflow processors)\n const phases = detectProcessorPhases(processorEntry);\n\n // Get agent configurations for this processor\n const configs = mastra.getProcessorConfigurations(processorId);\n const agents = mastra.listAgents() || {};\n const configurations = configs.map(c => ({\n agentId: c.agentId,\n agentName: agents[c.agentId]?.name || c.agentId,\n type: c.type,\n }));\n\n return {\n id: processorEntry.id,\n name: processorEntry.name || processorEntry.id,\n description: processorEntry.description,\n phases,\n configurations,\n isWorkflow,\n };\n } catch (error) {\n return handleError(error, 'Error getting processor');\n }\n },\n});\n\nexport const EXECUTE_PROCESSOR_ROUTE = createRoute({\n method: 'POST',\n path: '/processors/:processorId/execute',\n responseType: 'json',\n pathParamSchema: processorIdPathParams,\n bodySchema: executeProcessorBodySchema,\n responseSchema: executeProcessorResponseSchema,\n summary: 'Execute processor',\n description: 'Executes a specific processor with the provided input data',\n tags: ['Processors'],\n requiresAuth: true,\n handler: async ({ mastra, processorId, ...bodyParams }) => {\n try {\n const { phase, messages } = bodyParams;\n\n if (!processorId) {\n throw new HTTPException(400, { message: 'Processor ID is required' });\n }\n\n if (!phase) {\n throw new HTTPException(400, { message: 'Phase is required' });\n }\n\n if (!messages || !Array.isArray(messages)) {\n throw new HTTPException(400, { message: 'Messages array is required' });\n }\n\n // Get the processor from Mastra's registered processors\n let processor;\n try {\n processor = mastra.getProcessorById(processorId);\n } catch {\n // getProcessorById throws if not found, try by key\n const processors = mastra.listProcessors() || {};\n processor = processors[processorId as keyof typeof processors];\n }\n\n if (!processor) {\n throw new HTTPException(404, { message: 'Processor not found' });\n }\n\n const messageList = new MessageList();\n messageList.add(messages as unknown as MessageInput[], 'input');\n\n // Check if this is a workflow processor\n if (isProcessorWorkflow(processor)) {\n // Execute workflow processor\n try {\n // Build inputData based on phase - each phase has different required fields\n const baseInputData = {\n phase: phase as 'input' | 'inputStep' | 'outputStream' | 'outputResult' | 'outputStep' | 'toolResult',\n messages: messageList.get.all.db(),\n messageList,\n retryCount: 0,\n };\n let inputData: typeof baseInputData & Record<string, unknown> = baseInputData;\n\n // Add phase-specific fields\n switch (phase) {\n case 'input':\n inputData = {\n ...inputData,\n systemMessages: [],\n };\n break;\n case 'inputStep':\n inputData = {\n ...inputData,\n stepNumber: 0,\n systemMessages: [],\n steps: [],\n model: '',\n tools: {},\n toolChoice: undefined,\n activeTools: [],\n providerOptions: undefined,\n modelSettings: undefined,\n structuredOutput: undefined,\n };\n break;\n case 'outputResult':\n inputData = {\n ...inputData,\n state: {},\n result: {\n text: extractTextFromMessages(messages),\n usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },\n finishReason: 'unknown',\n steps: [],\n },\n };\n break;\n case 'outputStep':\n inputData = {\n ...inputData,\n stepNumber: 0,\n systemMessages: [],\n steps: [],\n finishReason: 'stop',\n toolCalls: [],\n text: extractTextFromMessages(messages),\n };\n break;\n case 'outputStream':\n inputData = {\n ...inputData,\n part: null,\n streamParts: [],\n state: {},\n };\n break;\n case 'toolResult':\n inputData = {\n ...inputData,\n stepNumber: 0,\n toolName: '',\n toolCallId: '',\n args: undefined,\n toolResultValue: undefined,\n providerExecuted: false,\n systemMessages: [],\n steps: [],\n };\n break;\n }\n\n const run = await processor.createRun();\n const result = await run.start({\n inputData,\n });\n\n // Check for tripwire status\n if (result.status === 'tripwire') {\n return {\n success: false,\n phase,\n tripwire: {\n triggered: true,\n reason: result.tripwire.reason || `Tripwire triggered in workflow ${processor.id}`,\n metadata: result.tripwire.metadata,\n },\n messages,\n messageList: {\n messages,\n },\n };\n }\n\n // Check for execution failure\n if (result.status !== 'success') {\n throw new HTTPException(500, {\n message: `Processor workflow ${processor.id} failed with status: ${result.status}`,\n });\n }\n\n // Extract output from workflow result\n const output = result.result;\n let outputMessages = messages;\n\n if (output && typeof output === 'object') {\n if ('messages' in output && Array.isArray(output.messages)) {\n outputMessages = output.messages;\n } else if ('messageList' in output && output.messageList instanceof MessageList) {\n outputMessages = output.messageList.get.all.db();\n }\n }\n\n return {\n success: true,\n phase,\n messages: outputMessages,\n messageList: {\n messages: outputMessages,\n },\n };\n } catch (error: any) {\n // Re-throw HTTP exceptions\n if (error instanceof HTTPException) {\n throw error;\n }\n throw new HTTPException(500, {\n message: `Error executing processor workflow: ${error.message}`,\n });\n }\n }\n\n // Handle individual processor execution\n // Create the abort function for tripwire support\n let tripwireTriggered = false;\n let tripwireReason: string | undefined;\n let tripwireMetadata: unknown;\n\n const abort = (reason?: string, options?: { retry?: boolean; metadata?: unknown }) => {\n tripwireTriggered = true;\n tripwireReason = reason;\n tripwireMetadata = options?.metadata;\n throw new Error(`TRIPWIRE:${reason || 'Processor aborted'}`);\n };\n\n // Build the context based on phase\n const baseContext = {\n abort,\n retryCount: 0,\n messages: messageList.get.all.db(),\n messageList,\n state: {},\n };\n\n try {\n let result: any;\n\n // Execute the specific phase method on the individual processor\n switch (phase) {\n case 'input':\n if (!processor.processInput) {\n throw new HTTPException(400, { message: 'Processor does not support input phase' });\n }\n result = await processor.processInput({\n ...baseContext,\n systemMessages: [],\n });\n break;\n\n case 'inputStep':\n if (!processor.processInputStep) {\n throw new HTTPException(400, { message: 'Processor does not support inputStep phase' });\n }\n result = await processor.processInputStep({\n ...baseContext,\n systemMessages: [],\n stepNumber: 0,\n steps: [],\n // Pass empty/default values for all inputStep fields\n model: '' as any,\n tools: {},\n toolChoice: undefined,\n activeTools: [],\n providerOptions: undefined,\n modelSettings: undefined,\n structuredOutput: undefined,\n });\n break;\n\n case 'outputResult':\n if (!processor.processOutputResult) {\n throw new HTTPException(400, { message: 'Processor does not support outputResult phase' });\n }\n result = await processor.processOutputResult({\n ...baseContext,\n state: {},\n result: {\n text: extractTextFromMessages(messages),\n usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },\n finishReason: 'unknown',\n steps: [],\n },\n });\n break;\n\n case 'outputStep':\n if (!processor.processOutputStep) {\n throw new HTTPException(400, { message: 'Processor does not support outputStep phase' });\n }\n result = await processor.processOutputStep({\n ...baseContext,\n systemMessages: [],\n stepNumber: 0,\n steps: [],\n finishReason: 'stop',\n toolCalls: [],\n text: extractTextFromMessages(messages),\n usage: { inputTokens: undefined, outputTokens: undefined, totalTokens: undefined },\n });\n break;\n\n case 'outputStream':\n // outputStream is for streaming chunks, not a simple execute\n throw new HTTPException(400, {\n message: 'outputStream phase cannot be executed directly. Use streaming instead.',\n });\n\n default:\n throw new HTTPException(400, { message: `Unknown phase: ${phase}` });\n }\n\n // Process the result\n let outputMessages = messages;\n if (result) {\n if (Array.isArray(result)) {\n outputMessages = result;\n } else if (result.get && result.get.all && typeof result.get.all.db === 'function') {\n // It's a MessageList\n outputMessages = result.get.all.db();\n } else if (result.messages) {\n outputMessages = result.messages;\n }\n }\n\n return {\n success: true,\n phase,\n messages: outputMessages,\n messageList: {\n messages: outputMessages,\n },\n };\n } catch (error: any) {\n // Check if it's a tripwire\n if (tripwireTriggered || error.message?.startsWith('TRIPWIRE:')) {\n return {\n success: false,\n phase,\n tripwire: {\n triggered: true,\n reason: tripwireReason || error.message?.replace('TRIPWIRE:', ''),\n metadata: tripwireMetadata,\n },\n messages,\n messageList: {\n messages,\n },\n };\n }\n throw error;\n }\n } catch (error) {\n return handleError(error, 'Error executing processor');\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;AA0BA,SAAS,wBAAwB,UAA6B;CAC5D,IAAI,CAAC,YAAY,CAAC,MAAM,QAAQ,QAAQ,KAAK,SAAS,WAAW,GAC/D,OAAO;CAET,MAAM,eAAe,SAAS;CAC9B,IAAI,cAAc,SAAS,OAIzB,OAHkB,aAAa,QAAQ,MACpC,QAAQ,SAAc,MAAM,SAAS,MAAM,CAAC,CAC5C,KAAK,SAAc,MAAM,QAAQ,EACrB,CAAC,CAAC,KAAK,EAAE;CAE1B,OAAO;AACT;;;;;;;AAQA,SAAS,sBAAsB,WAAkC;CAE/D,KAAA,GAAA,wBAAA,oBAAA,CAAwB,SAAS,GAG/B,OAAO;EAAC;EAAS;EAAa;EAAgB;EAAgB;EAAc;CAAY;CAI1F,MAA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,EAAE,SAAS,8CAA8C,CAAC;MAEzF,SAAS,MAAM,UAAU,kBAAkB;OACzC,GAAG;OACH,gBAAgB,CAAC;OACjB,YAAY;OACZ,OAAO,CAAC;OACR,cAAc;OACd,WAAW,CAAC;OACZ,MAAM,wBAAwB,QAAQ;OACtC,OAAO;QAAE,aAAa,KAAA;QAAW,cAAc,KAAA;QAAW,aAAa,KAAA;OAAU;MACnF,CAAC;MACD;KAEF,KAAK,gBAEH,MAAM,IAAIA,uBAAAA,cAAc,KAAK,EAC3B,SAAS,yEACX,CAAC;KAEH,SACE,MAAM,IAAIA,uBAAAA,cAAc,KAAK,EAAE,SAAS,kBAAkB,QAAQ,CAAC;IACvE;IAGA,IAAI,iBAAiB;IACrB,IAAI,QACE;SAAA,MAAM,QAAQ,MAAM,GACtB,iBAAiB;UACZ,IAAI,OAAO,OAAO,OAAO,IAAI,OAAO,OAAO,OAAO,IAAI,IAAI,OAAO,YAEtE,iBAAiB,OAAO,IAAI,IAAI,GAAG;UAC9B,IAAI,OAAO,UAChB,iBAAiB,OAAO;IAAA;IAI5B,OAAO;KACL,SAAS;KACT;KACA,UAAU;KACV,aAAa,EACX,UAAU,eACZ;IACF;GACF,SAAS,OAAY;IAEnB,IAAI,qBAAqB,MAAM,SAAS,WAAW,WAAW,GAC5D,OAAO;KACL,SAAS;KACT;KACA,UAAU;MACR,WAAW;MACX,QAAQ,kBAAkB,MAAM,SAAS,QAAQ,aAAa,EAAE;MAChE,UAAU;KACZ;KACA;KACA,aAAa,EACX,SACF;IACF;IAEF,MAAM;GACR;EACF,SAAS,OAAO;GACd,OAAOH,8BAAAA,YAAY,OAAO,2BAA2B;EACvD;CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"processors.cjs","names":["createRoute","listProcessorsResponseSchema","handleError","processorIdPathParams","serializedProcessorDetailSchema","HTTPException","executeProcessorBodySchema","executeProcessorResponseSchema","MessageList"],"sources":["../../../src/server/handlers/processors.ts"],"sourcesContent":["import { MessageList } from '@mastra/core/agent';\nimport type { MessageInput } from '@mastra/core/agent/message-list';\nimport { isProcessorWorkflow } from '@mastra/core/processors';\nimport type { Processor, ProcessorWorkflow } from '@mastra/core/processors';\n\nimport { HTTPException } from '../http-exception';\nimport {\n listProcessorsResponseSchema,\n serializedProcessorDetailSchema,\n processorIdPathParams,\n executeProcessorBodySchema,\n executeProcessorResponseSchema,\n} from '../schemas/processors';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { handleError } from './error';\n\n// ============================================================================\n// Route Definitions\n// ============================================================================\n\ntype ProcessorPhase =\n | 'input'\n | 'inputStep'\n | 'outputStream'\n | 'outputResult'\n | 'outputStep'\n | 'toolResult'\n | 'llmRequest';\n\n/**\n * Helper to extract text from messages for outputStep testing.\n * In real usage, the `text` field contains the assistant's response text.\n */\nfunction extractTextFromMessages(messages: unknown[]): string {\n if (!messages || !Array.isArray(messages) || messages.length === 0) {\n return '';\n }\n const firstMessage = messages[0] as any;\n if (firstMessage?.content?.parts) {\n const textParts = firstMessage.content.parts\n .filter((part: any) => part?.type === 'text')\n .map((part: any) => part?.text || '');\n return textParts.join('');\n }\n return '';\n}\n\n/**\n * Helper to detect phases for a processor.\n * For individual processors, checks which methods are implemented.\n * For workflow processors, returns all phases since createStep handles each phase\n * and it's a no-op if the underlying processor doesn't implement it.\n */\nfunction detectProcessorPhases(processor: any): ProcessorPhase[] {\n // Check if it's a workflow processor\n if (isProcessorWorkflow(processor)) {\n // Workflow processors can potentially handle all phases\n // The createStep in workflows handles each phase and it's a no-op if not implemented\n return ['input', 'inputStep', 'outputStream', 'outputResult', 'outputStep', 'toolResult'];\n }\n\n // For individual processors, detect by checking which methods exist\n const phases: ProcessorPhase[] = [];\n if (typeof processor.processInput === 'function') {\n phases.push('input');\n }\n if (typeof processor.processInputStep === 'function') {\n phases.push('inputStep');\n }\n if (typeof processor.processOutputStream === 'function') {\n phases.push('outputStream');\n }\n if (typeof processor.processOutputResult === 'function') {\n phases.push('outputResult');\n }\n if (typeof processor.processOutputStep === 'function') {\n phases.push('outputStep');\n }\n if (typeof processor.processToolResult === 'function') {\n phases.push('toolResult');\n }\n if (typeof processor.processLLMRequest === 'function') {\n phases.push('llmRequest');\n }\n return phases;\n}\n\nexport const LIST_PROCESSORS_ROUTE = createRoute({\n method: 'GET',\n path: '/processors',\n responseType: 'json',\n responseSchema: listProcessorsResponseSchema,\n summary: 'List all processors',\n description: 'Returns a list of all available individual processors',\n tags: ['Processors'],\n requiresAuth: true,\n handler: async ({ mastra }) => {\n try {\n const processors = mastra.listProcessors() || {};\n const processorConfigurations = mastra.listProcessorConfigurations();\n const result: Record<\n string,\n {\n id: string;\n name?: string;\n description?: string;\n phases: ProcessorPhase[];\n agentIds: string[];\n configurations: Array<{ agentId: string; type: 'input' | 'output' }>;\n isWorkflow: boolean;\n }\n > = {};\n\n // Iterate through all individual processors registered with Mastra\n for (const [processorKey, processorEntry] of Object.entries(processors)) {\n const processor = processorEntry as Processor | ProcessorWorkflow;\n const processorId = processor.id || processorKey;\n\n // Check if it's a workflow processor\n const isWorkflow = isProcessorWorkflow(processor);\n\n // Detect phases (handles both individual processors and workflow processors)\n const phases = detectProcessorPhases(processor);\n\n // Get agent configurations for this processor\n const configs = processorConfigurations.get(processorId) || [];\n const agentIds = [...new Set(configs.map(c => c.agentId))];\n const configurations = configs.map(c => ({ agentId: c.agentId, type: c.type }));\n\n result[processorId] = {\n id: processorId,\n name: processor.name || processorId,\n description: processor.description,\n phases,\n agentIds,\n configurations,\n isWorkflow,\n };\n }\n\n return result;\n } catch (error) {\n return handleError(error, 'Error getting processors');\n }\n },\n});\n\nexport const GET_PROCESSOR_BY_ID_ROUTE = createRoute({\n method: 'GET',\n path: '/processors/:processorId',\n responseType: 'json',\n pathParamSchema: processorIdPathParams,\n responseSchema: serializedProcessorDetailSchema,\n summary: 'Get processor by ID',\n description: 'Returns details for a specific processor including its phases and configurations',\n tags: ['Processors'],\n requiresAuth: true,\n handler: async ({ mastra, processorId }) => {\n try {\n // Get the processor from Mastra's registered processors\n let processorEntry: Processor | ProcessorWorkflow | undefined;\n try {\n processorEntry = mastra.getProcessorById(processorId) as Processor | ProcessorWorkflow;\n } catch {\n // getProcessorById throws if not found, try by key\n const processors = mastra.listProcessors() || {};\n processorEntry = processors[processorId as keyof typeof processors] as Processor | ProcessorWorkflow;\n }\n\n if (!processorEntry) {\n throw new HTTPException(404, { message: 'Processor not found' });\n }\n\n // Check if it's a workflow processor\n const isWorkflow = isProcessorWorkflow(processorEntry);\n\n // Detect phases (handles both individual processors and workflow processors)\n const phases = detectProcessorPhases(processorEntry);\n\n // Get agent configurations for this processor\n const configs = mastra.getProcessorConfigurations(processorId);\n const agents = mastra.listAgents() || {};\n const configurations = configs.map(c => ({\n agentId: c.agentId,\n agentName: agents[c.agentId]?.name || c.agentId,\n type: c.type,\n }));\n\n return {\n id: processorEntry.id,\n name: processorEntry.name || processorEntry.id,\n description: processorEntry.description,\n phases,\n configurations,\n isWorkflow,\n };\n } catch (error) {\n return handleError(error, 'Error getting processor');\n }\n },\n});\n\nexport const EXECUTE_PROCESSOR_ROUTE = createRoute({\n method: 'POST',\n path: '/processors/:processorId/execute',\n responseType: 'json',\n pathParamSchema: processorIdPathParams,\n bodySchema: executeProcessorBodySchema,\n responseSchema: executeProcessorResponseSchema,\n summary: 'Execute processor',\n description: 'Executes a specific processor with the provided input data',\n tags: ['Processors'],\n requiresAuth: true,\n handler: async ({ mastra, processorId, ...bodyParams }) => {\n try {\n const { phase, messages } = bodyParams;\n\n if (!processorId) {\n throw new HTTPException(400, { message: 'Processor ID is required' });\n }\n\n if (!phase) {\n throw new HTTPException(400, { message: 'Phase is required' });\n }\n\n if (phase === 'llmRequest') {\n // processLLMRequest operates on the provider prompt, not on messages\n throw new HTTPException(400, {\n message: 'llmRequest phase cannot be executed directly. It runs on the provider prompt during an agent call.',\n });\n }\n\n if (!messages || !Array.isArray(messages)) {\n throw new HTTPException(400, { message: 'Messages array is required' });\n }\n\n // Get the processor from Mastra's registered processors\n let processor;\n try {\n processor = mastra.getProcessorById(processorId);\n } catch {\n // getProcessorById throws if not found, try by key\n const processors = mastra.listProcessors() || {};\n processor = processors[processorId as keyof typeof processors];\n }\n\n if (!processor) {\n throw new HTTPException(404, { message: 'Processor not found' });\n }\n\n const messageList = new MessageList();\n messageList.add(messages as unknown as MessageInput[], 'input');\n\n // Check if this is a workflow processor\n if (isProcessorWorkflow(processor)) {\n // Execute workflow processor\n try {\n // Build inputData based on phase - each phase has different required fields\n const baseInputData = {\n phase: phase as 'input' | 'inputStep' | 'outputStream' | 'outputResult' | 'outputStep' | 'toolResult',\n messages: messageList.get.all.db(),\n messageList,\n retryCount: 0,\n };\n let inputData: typeof baseInputData & Record<string, unknown> = baseInputData;\n\n // Add phase-specific fields\n switch (phase) {\n case 'input':\n inputData = {\n ...inputData,\n systemMessages: [],\n };\n break;\n case 'inputStep':\n inputData = {\n ...inputData,\n stepNumber: 0,\n systemMessages: [],\n steps: [],\n model: '',\n tools: {},\n toolChoice: undefined,\n activeTools: [],\n providerOptions: undefined,\n modelSettings: undefined,\n structuredOutput: undefined,\n };\n break;\n case 'outputResult':\n inputData = {\n ...inputData,\n state: {},\n result: {\n text: extractTextFromMessages(messages),\n usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },\n finishReason: 'unknown',\n steps: [],\n },\n };\n break;\n case 'outputStep':\n inputData = {\n ...inputData,\n stepNumber: 0,\n systemMessages: [],\n steps: [],\n finishReason: 'stop',\n toolCalls: [],\n text: extractTextFromMessages(messages),\n };\n break;\n case 'outputStream':\n inputData = {\n ...inputData,\n part: null,\n streamParts: [],\n state: {},\n };\n break;\n case 'toolResult':\n inputData = {\n ...inputData,\n stepNumber: 0,\n toolName: '',\n toolCallId: '',\n args: undefined,\n toolResultValue: undefined,\n providerExecuted: false,\n systemMessages: [],\n steps: [],\n };\n break;\n }\n\n const run = await processor.createRun();\n const result = await run.start({\n inputData,\n });\n\n // Check for tripwire status\n if (result.status === 'tripwire') {\n return {\n success: false,\n phase,\n tripwire: {\n triggered: true,\n reason: result.tripwire.reason || `Tripwire triggered in workflow ${processor.id}`,\n metadata: result.tripwire.metadata,\n },\n messages,\n messageList: {\n messages,\n },\n };\n }\n\n // Check for execution failure\n if (result.status !== 'success') {\n throw new HTTPException(500, {\n message: `Processor workflow ${processor.id} failed with status: ${result.status}`,\n });\n }\n\n // Extract output from workflow result\n const output = result.result;\n let outputMessages = messages;\n\n if (output && typeof output === 'object') {\n if ('messages' in output && Array.isArray(output.messages)) {\n outputMessages = output.messages;\n } else if ('messageList' in output && output.messageList instanceof MessageList) {\n outputMessages = output.messageList.get.all.db();\n }\n }\n\n return {\n success: true,\n phase,\n messages: outputMessages,\n messageList: {\n messages: outputMessages,\n },\n };\n } catch (error: any) {\n // Re-throw HTTP exceptions\n if (error instanceof HTTPException) {\n throw error;\n }\n throw new HTTPException(500, {\n message: `Error executing processor workflow: ${error.message}`,\n });\n }\n }\n\n // Handle individual processor execution\n // Create the abort function for tripwire support\n let tripwireTriggered = false;\n let tripwireReason: string | undefined;\n let tripwireMetadata: unknown;\n\n const abort = (reason?: string, options?: { retry?: boolean; metadata?: unknown }) => {\n tripwireTriggered = true;\n tripwireReason = reason;\n tripwireMetadata = options?.metadata;\n throw new Error(`TRIPWIRE:${reason || 'Processor aborted'}`);\n };\n\n // Build the context based on phase\n const baseContext = {\n abort,\n retryCount: 0,\n messages: messageList.get.all.db(),\n messageList,\n state: {},\n };\n\n try {\n let result: any;\n\n // Execute the specific phase method on the individual processor\n switch (phase) {\n case 'input':\n if (!processor.processInput) {\n throw new HTTPException(400, { message: 'Processor does not support input phase' });\n }\n result = await processor.processInput({\n ...baseContext,\n systemMessages: [],\n });\n break;\n\n case 'inputStep':\n if (!processor.processInputStep) {\n throw new HTTPException(400, { message: 'Processor does not support inputStep phase' });\n }\n result = await processor.processInputStep({\n ...baseContext,\n systemMessages: [],\n stepNumber: 0,\n steps: [],\n // Pass empty/default values for all inputStep fields\n model: '' as any,\n tools: {},\n toolChoice: undefined,\n activeTools: [],\n providerOptions: undefined,\n modelSettings: undefined,\n structuredOutput: undefined,\n });\n break;\n\n case 'outputResult':\n if (!processor.processOutputResult) {\n throw new HTTPException(400, { message: 'Processor does not support outputResult phase' });\n }\n result = await processor.processOutputResult({\n ...baseContext,\n state: {},\n result: {\n text: extractTextFromMessages(messages),\n usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },\n finishReason: 'unknown',\n steps: [],\n },\n });\n break;\n\n case 'outputStep':\n if (!processor.processOutputStep) {\n throw new HTTPException(400, { message: 'Processor does not support outputStep phase' });\n }\n result = await processor.processOutputStep({\n ...baseContext,\n systemMessages: [],\n stepNumber: 0,\n steps: [],\n finishReason: 'stop',\n toolCalls: [],\n text: extractTextFromMessages(messages),\n usage: { inputTokens: undefined, outputTokens: undefined, totalTokens: undefined },\n });\n break;\n\n case 'outputStream':\n // outputStream is for streaming chunks, not a simple execute\n throw new HTTPException(400, {\n message: 'outputStream phase cannot be executed directly. Use streaming instead.',\n });\n\n default:\n throw new HTTPException(400, { message: `Unknown phase: ${phase}` });\n }\n\n // Process the result\n let outputMessages = messages;\n if (result) {\n if (Array.isArray(result)) {\n outputMessages = result;\n } else if (result.get && result.get.all && typeof result.get.all.db === 'function') {\n // It's a MessageList\n outputMessages = result.get.all.db();\n } else if (result.messages) {\n outputMessages = result.messages;\n }\n }\n\n return {\n success: true,\n phase,\n messages: outputMessages,\n messageList: {\n messages: outputMessages,\n },\n };\n } catch (error: any) {\n // Check if it's a tripwire\n if (tripwireTriggered || error.message?.startsWith('TRIPWIRE:')) {\n return {\n success: false,\n phase,\n tripwire: {\n triggered: true,\n reason: tripwireReason || error.message?.replace('TRIPWIRE:', ''),\n metadata: tripwireMetadata,\n },\n messages,\n messageList: {\n messages,\n },\n };\n }\n throw error;\n }\n } catch (error) {\n return handleError(error, 'Error executing processor');\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;AAiCA,SAAS,wBAAwB,UAA6B;CAC5D,IAAI,C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OAAO;KACL,SAAS;KACT;KACA,UAAU;KACV,aAAa,EACX,UAAU,eACZ;IACF;GACF,SAAS,OAAY;IAEnB,IAAI,qBAAqB,MAAM,SAAS,WAAW,WAAW,GAC5D,OAAO;KACL,SAAS;KACT;KACA,UAAU;MACR,WAAW;MACX,QAAQ,kBAAkB,MAAM,SAAS,QAAQ,aAAa,EAAE;MAChE,UAAU;KACZ;KACA;KACA,aAAa,EACX,SACF;IACF;IAEF,MAAM;GACR;EACF,SAAS,OAAO;GACd,OAAOH,8BAAAA,YAAY,OAAO,2BAA2B;EACvD;CACF;AACF,CAAC"}
|
|
@@ -8,7 +8,7 @@ export declare const LIST_PROCESSORS_ROUTE: Omit<import("@mastra/core/server").A
|
|
|
8
8
|
id: string;
|
|
9
9
|
name?: string | undefined;
|
|
10
10
|
description?: string | undefined;
|
|
11
|
-
phases: ("input" | "inputStep" | "outputResult" | "outputStep" | "outputStream" | "toolResult")[];
|
|
11
|
+
phases: ("input" | "inputStep" | "llmRequest" | "outputResult" | "outputStep" | "outputStream" | "toolResult")[];
|
|
12
12
|
agentIds: string[];
|
|
13
13
|
configurations: {
|
|
14
14
|
agentId: string;
|
|
@@ -33,6 +33,7 @@ export declare const LIST_PROCESSORS_ROUTE: Omit<import("@mastra/core/server").A
|
|
|
33
33
|
phases: import("zod").ZodArray<import("zod").ZodEnum<{
|
|
34
34
|
input: "input";
|
|
35
35
|
inputStep: "inputStep";
|
|
36
|
+
llmRequest: "llmRequest";
|
|
36
37
|
outputResult: "outputResult";
|
|
37
38
|
outputStep: "outputStep";
|
|
38
39
|
outputStream: "outputStream";
|
|
@@ -63,7 +64,7 @@ export declare const GET_PROCESSOR_BY_ID_ROUTE: Omit<import("@mastra/core/server
|
|
|
63
64
|
id: string;
|
|
64
65
|
name?: string | undefined;
|
|
65
66
|
description?: string | undefined;
|
|
66
|
-
phases: ("input" | "inputStep" | "outputResult" | "outputStep" | "outputStream" | "toolResult")[];
|
|
67
|
+
phases: ("input" | "inputStep" | "llmRequest" | "outputResult" | "outputStep" | "outputStream" | "toolResult")[];
|
|
67
68
|
configurations: {
|
|
68
69
|
agentId: string;
|
|
69
70
|
agentName: string;
|
|
@@ -90,6 +91,7 @@ export declare const GET_PROCESSOR_BY_ID_ROUTE: Omit<import("@mastra/core/server
|
|
|
90
91
|
phases: import("zod").ZodArray<import("zod").ZodEnum<{
|
|
91
92
|
input: "input";
|
|
92
93
|
inputStep: "inputStep";
|
|
94
|
+
llmRequest: "llmRequest";
|
|
93
95
|
outputResult: "outputResult";
|
|
94
96
|
outputStep: "outputStep";
|
|
95
97
|
outputStream: "outputStream";
|
|
@@ -117,7 +119,7 @@ export declare const EXECUTE_PROCESSOR_ROUTE: Omit<import("@mastra/core/server")
|
|
|
117
119
|
handler(params: {
|
|
118
120
|
processorId: string;
|
|
119
121
|
} & {
|
|
120
|
-
phase: "input" | "inputStep" | "outputResult" | "outputStep" | "outputStream" | "toolResult";
|
|
122
|
+
phase: "input" | "inputStep" | "llmRequest" | "outputResult" | "outputStep" | "outputStream" | "toolResult";
|
|
121
123
|
messages: {
|
|
122
124
|
[x: string]: unknown;
|
|
123
125
|
id: string;
|
|
@@ -184,6 +186,7 @@ export declare const EXECUTE_PROCESSOR_ROUTE: Omit<import("@mastra/core/server")
|
|
|
184
186
|
phase: import("zod").ZodEnum<{
|
|
185
187
|
input: "input";
|
|
186
188
|
inputStep: "inputStep";
|
|
189
|
+
llmRequest: "llmRequest";
|
|
187
190
|
outputResult: "outputResult";
|
|
188
191
|
outputStep: "outputStep";
|
|
189
192
|
outputStream: "outputStream";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"processors.d.ts","sourceRoot":"","sources":["../../../src/server/handlers/processors.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"processors.d.ts","sourceRoot":"","sources":["../../../src/server/handlers/processors.ts"],"names":[],"mappings":"AAuFA,eAAO,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0DhC,CAAC;AAEH,eAAO,MAAM,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqDpC,CAAC;AAEH,eAAO,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgVlC,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
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 "./error.js";
|
|
4
|
-
import { a as processorIdPathParams, n as executeProcessorResponseSchema, o as serializedProcessorDetailSchema, r as listProcessorsResponseSchema, t as executeProcessorBodySchema } from "../../processors-
|
|
4
|
+
import { a as processorIdPathParams, n as executeProcessorResponseSchema, o as serializedProcessorDetailSchema, r as listProcessorsResponseSchema, t as executeProcessorBodySchema } from "../../processors-33IULT8X.js";
|
|
5
5
|
import { MessageList } from "@mastra/core/agent";
|
|
6
6
|
import { isProcessorWorkflow } from "@mastra/core/processors";
|
|
7
7
|
//#region src/server/handlers/processors.ts
|
|
@@ -37,6 +37,7 @@ function detectProcessorPhases(processor) {
|
|
|
37
37
|
if (typeof processor.processOutputResult === "function") phases.push("outputResult");
|
|
38
38
|
if (typeof processor.processOutputStep === "function") phases.push("outputStep");
|
|
39
39
|
if (typeof processor.processToolResult === "function") phases.push("toolResult");
|
|
40
|
+
if (typeof processor.processLLMRequest === "function") phases.push("llmRequest");
|
|
40
41
|
return phases;
|
|
41
42
|
}
|
|
42
43
|
const LIST_PROCESSORS_ROUTE = createRoute({
|
|
@@ -137,6 +138,7 @@ const EXECUTE_PROCESSOR_ROUTE = createRoute({
|
|
|
137
138
|
const { phase, messages } = bodyParams;
|
|
138
139
|
if (!processorId) throw new HTTPException(400, { message: "Processor ID is required" });
|
|
139
140
|
if (!phase) throw new HTTPException(400, { message: "Phase is required" });
|
|
141
|
+
if (phase === "llmRequest") throw new HTTPException(400, { message: "llmRequest phase cannot be executed directly. It runs on the provider prompt during an agent call." });
|
|
140
142
|
if (!messages || !Array.isArray(messages)) throw new HTTPException(400, { message: "Messages array is required" });
|
|
141
143
|
let processor;
|
|
142
144
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"processors.js","names":[],"sources":["../../../src/server/handlers/processors.ts"],"sourcesContent":["import { MessageList } from '@mastra/core/agent';\nimport type { MessageInput } from '@mastra/core/agent/message-list';\nimport { isProcessorWorkflow } from '@mastra/core/processors';\nimport type { Processor, ProcessorWorkflow } from '@mastra/core/processors';\n\nimport { HTTPException } from '../http-exception';\nimport {\n listProcessorsResponseSchema,\n serializedProcessorDetailSchema,\n processorIdPathParams,\n executeProcessorBodySchema,\n executeProcessorResponseSchema,\n} from '../schemas/processors';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { handleError } from './error';\n\n// ============================================================================\n// Route Definitions\n// ============================================================================\n\ntype ProcessorPhase = 'input' | 'inputStep' | 'outputStream' | 'outputResult' | 'outputStep' | 'toolResult';\n\n/**\n * Helper to extract text from messages for outputStep testing.\n * In real usage, the `text` field contains the assistant's response text.\n */\nfunction extractTextFromMessages(messages: unknown[]): string {\n if (!messages || !Array.isArray(messages) || messages.length === 0) {\n return '';\n }\n const firstMessage = messages[0] as any;\n if (firstMessage?.content?.parts) {\n const textParts = firstMessage.content.parts\n .filter((part: any) => part?.type === 'text')\n .map((part: any) => part?.text || '');\n return textParts.join('');\n }\n return '';\n}\n\n/**\n * Helper to detect phases for a processor.\n * For individual processors, checks which methods are implemented.\n * For workflow processors, returns all phases since createStep handles each phase\n * and it's a no-op if the underlying processor doesn't implement it.\n */\nfunction detectProcessorPhases(processor: any): ProcessorPhase[] {\n // Check if it's a workflow processor\n if (isProcessorWorkflow(processor)) {\n // Workflow processors can potentially handle all phases\n // The createStep in workflows handles each phase and it's a no-op if not implemented\n return ['input', 'inputStep', 'outputStream', 'outputResult', 'outputStep', 'toolResult'];\n }\n\n // For individual processors, detect by checking which methods exist\n const phases: ProcessorPhase[] = [];\n if (typeof processor.processInput === 'function') {\n phases.push('input');\n }\n if (typeof processor.processInputStep === 'function') {\n phases.push('inputStep');\n }\n if (typeof processor.processOutputStream === 'function') {\n phases.push('outputStream');\n }\n if (typeof processor.processOutputResult === 'function') {\n phases.push('outputResult');\n }\n if (typeof processor.processOutputStep === 'function') {\n phases.push('outputStep');\n }\n if (typeof processor.processToolResult === 'function') {\n phases.push('toolResult');\n }\n return phases;\n}\n\nexport const LIST_PROCESSORS_ROUTE = createRoute({\n method: 'GET',\n path: '/processors',\n responseType: 'json',\n responseSchema: listProcessorsResponseSchema,\n summary: 'List all processors',\n description: 'Returns a list of all available individual processors',\n tags: ['Processors'],\n requiresAuth: true,\n handler: async ({ mastra }) => {\n try {\n const processors = mastra.listProcessors() || {};\n const processorConfigurations = mastra.listProcessorConfigurations();\n const result: Record<\n string,\n {\n id: string;\n name?: string;\n description?: string;\n phases: ProcessorPhase[];\n agentIds: string[];\n configurations: Array<{ agentId: string; type: 'input' | 'output' }>;\n isWorkflow: boolean;\n }\n > = {};\n\n // Iterate through all individual processors registered with Mastra\n for (const [processorKey, processorEntry] of Object.entries(processors)) {\n const processor = processorEntry as Processor | ProcessorWorkflow;\n const processorId = processor.id || processorKey;\n\n // Check if it's a workflow processor\n const isWorkflow = isProcessorWorkflow(processor);\n\n // Detect phases (handles both individual processors and workflow processors)\n const phases = detectProcessorPhases(processor);\n\n // Get agent configurations for this processor\n const configs = processorConfigurations.get(processorId) || [];\n const agentIds = [...new Set(configs.map(c => c.agentId))];\n const configurations = configs.map(c => ({ agentId: c.agentId, type: c.type }));\n\n result[processorId] = {\n id: processorId,\n name: processor.name || processorId,\n description: processor.description,\n phases,\n agentIds,\n configurations,\n isWorkflow,\n };\n }\n\n return result;\n } catch (error) {\n return handleError(error, 'Error getting processors');\n }\n },\n});\n\nexport const GET_PROCESSOR_BY_ID_ROUTE = createRoute({\n method: 'GET',\n path: '/processors/:processorId',\n responseType: 'json',\n pathParamSchema: processorIdPathParams,\n responseSchema: serializedProcessorDetailSchema,\n summary: 'Get processor by ID',\n description: 'Returns details for a specific processor including its phases and configurations',\n tags: ['Processors'],\n requiresAuth: true,\n handler: async ({ mastra, processorId }) => {\n try {\n // Get the processor from Mastra's registered processors\n let processorEntry: Processor | ProcessorWorkflow | undefined;\n try {\n processorEntry = mastra.getProcessorById(processorId) as Processor | ProcessorWorkflow;\n } catch {\n // getProcessorById throws if not found, try by key\n const processors = mastra.listProcessors() || {};\n processorEntry = processors[processorId as keyof typeof processors] as Processor | ProcessorWorkflow;\n }\n\n if (!processorEntry) {\n throw new HTTPException(404, { message: 'Processor not found' });\n }\n\n // Check if it's a workflow processor\n const isWorkflow = isProcessorWorkflow(processorEntry);\n\n // Detect phases (handles both individual processors and workflow processors)\n const phases = detectProcessorPhases(processorEntry);\n\n // Get agent configurations for this processor\n const configs = mastra.getProcessorConfigurations(processorId);\n const agents = mastra.listAgents() || {};\n const configurations = configs.map(c => ({\n agentId: c.agentId,\n agentName: agents[c.agentId]?.name || c.agentId,\n type: c.type,\n }));\n\n return {\n id: processorEntry.id,\n name: processorEntry.name || processorEntry.id,\n description: processorEntry.description,\n phases,\n configurations,\n isWorkflow,\n };\n } catch (error) {\n return handleError(error, 'Error getting processor');\n }\n },\n});\n\nexport const EXECUTE_PROCESSOR_ROUTE = createRoute({\n method: 'POST',\n path: '/processors/:processorId/execute',\n responseType: 'json',\n pathParamSchema: processorIdPathParams,\n bodySchema: executeProcessorBodySchema,\n responseSchema: executeProcessorResponseSchema,\n summary: 'Execute processor',\n description: 'Executes a specific processor with the provided input data',\n tags: ['Processors'],\n requiresAuth: true,\n handler: async ({ mastra, processorId, ...bodyParams }) => {\n try {\n const { phase, messages } = bodyParams;\n\n if (!processorId) {\n throw new HTTPException(400, { message: 'Processor ID is required' });\n }\n\n if (!phase) {\n throw new HTTPException(400, { message: 'Phase is required' });\n }\n\n if (!messages || !Array.isArray(messages)) {\n throw new HTTPException(400, { message: 'Messages array is required' });\n }\n\n // Get the processor from Mastra's registered processors\n let processor;\n try {\n processor = mastra.getProcessorById(processorId);\n } catch {\n // getProcessorById throws if not found, try by key\n const processors = mastra.listProcessors() || {};\n processor = processors[processorId as keyof typeof processors];\n }\n\n if (!processor) {\n throw new HTTPException(404, { message: 'Processor not found' });\n }\n\n const messageList = new MessageList();\n messageList.add(messages as unknown as MessageInput[], 'input');\n\n // Check if this is a workflow processor\n if (isProcessorWorkflow(processor)) {\n // Execute workflow processor\n try {\n // Build inputData based on phase - each phase has different required fields\n const baseInputData = {\n phase: phase as 'input' | 'inputStep' | 'outputStream' | 'outputResult' | 'outputStep' | 'toolResult',\n messages: messageList.get.all.db(),\n messageList,\n retryCount: 0,\n };\n let inputData: typeof baseInputData & Record<string, unknown> = baseInputData;\n\n // Add phase-specific fields\n switch (phase) {\n case 'input':\n inputData = {\n ...inputData,\n systemMessages: [],\n };\n break;\n case 'inputStep':\n inputData = {\n ...inputData,\n stepNumber: 0,\n systemMessages: [],\n steps: [],\n model: '',\n tools: {},\n toolChoice: undefined,\n activeTools: [],\n providerOptions: undefined,\n modelSettings: undefined,\n structuredOutput: undefined,\n };\n break;\n case 'outputResult':\n inputData = {\n ...inputData,\n state: {},\n result: {\n text: extractTextFromMessages(messages),\n usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },\n finishReason: 'unknown',\n steps: [],\n },\n };\n break;\n case 'outputStep':\n inputData = {\n ...inputData,\n stepNumber: 0,\n systemMessages: [],\n steps: [],\n finishReason: 'stop',\n toolCalls: [],\n text: extractTextFromMessages(messages),\n };\n break;\n case 'outputStream':\n inputData = {\n ...inputData,\n part: null,\n streamParts: [],\n state: {},\n };\n break;\n case 'toolResult':\n inputData = {\n ...inputData,\n stepNumber: 0,\n toolName: '',\n toolCallId: '',\n args: undefined,\n toolResultValue: undefined,\n providerExecuted: false,\n systemMessages: [],\n steps: [],\n };\n break;\n }\n\n const run = await processor.createRun();\n const result = await run.start({\n inputData,\n });\n\n // Check for tripwire status\n if (result.status === 'tripwire') {\n return {\n success: false,\n phase,\n tripwire: {\n triggered: true,\n reason: result.tripwire.reason || `Tripwire triggered in workflow ${processor.id}`,\n metadata: result.tripwire.metadata,\n },\n messages,\n messageList: {\n messages,\n },\n };\n }\n\n // Check for execution failure\n if (result.status !== 'success') {\n throw new HTTPException(500, {\n message: `Processor workflow ${processor.id} failed with status: ${result.status}`,\n });\n }\n\n // Extract output from workflow result\n const output = result.result;\n let outputMessages = messages;\n\n if (output && typeof output === 'object') {\n if ('messages' in output && Array.isArray(output.messages)) {\n outputMessages = output.messages;\n } else if ('messageList' in output && output.messageList instanceof MessageList) {\n outputMessages = output.messageList.get.all.db();\n }\n }\n\n return {\n success: true,\n phase,\n messages: outputMessages,\n messageList: {\n messages: outputMessages,\n },\n };\n } catch (error: any) {\n // Re-throw HTTP exceptions\n if (error instanceof HTTPException) {\n throw error;\n }\n throw new HTTPException(500, {\n message: `Error executing processor workflow: ${error.message}`,\n });\n }\n }\n\n // Handle individual processor execution\n // Create the abort function for tripwire support\n let tripwireTriggered = false;\n let tripwireReason: string | undefined;\n let tripwireMetadata: unknown;\n\n const abort = (reason?: string, options?: { retry?: boolean; metadata?: unknown }) => {\n tripwireTriggered = true;\n tripwireReason = reason;\n tripwireMetadata = options?.metadata;\n throw new Error(`TRIPWIRE:${reason || 'Processor aborted'}`);\n };\n\n // Build the context based on phase\n const baseContext = {\n abort,\n retryCount: 0,\n messages: messageList.get.all.db(),\n messageList,\n state: {},\n };\n\n try {\n let result: any;\n\n // Execute the specific phase method on the individual processor\n switch (phase) {\n case 'input':\n if (!processor.processInput) {\n throw new HTTPException(400, { message: 'Processor does not support input phase' });\n }\n result = await processor.processInput({\n ...baseContext,\n systemMessages: [],\n });\n break;\n\n case 'inputStep':\n if (!processor.processInputStep) {\n throw new HTTPException(400, { message: 'Processor does not support inputStep phase' });\n }\n result = await processor.processInputStep({\n ...baseContext,\n systemMessages: [],\n stepNumber: 0,\n steps: [],\n // Pass empty/default values for all inputStep fields\n model: '' as any,\n tools: {},\n toolChoice: undefined,\n activeTools: [],\n providerOptions: undefined,\n modelSettings: undefined,\n structuredOutput: undefined,\n });\n break;\n\n case 'outputResult':\n if (!processor.processOutputResult) {\n throw new HTTPException(400, { message: 'Processor does not support outputResult phase' });\n }\n result = await processor.processOutputResult({\n ...baseContext,\n state: {},\n result: {\n text: extractTextFromMessages(messages),\n usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },\n finishReason: 'unknown',\n steps: [],\n },\n });\n break;\n\n case 'outputStep':\n if (!processor.processOutputStep) {\n throw new HTTPException(400, { message: 'Processor does not support outputStep phase' });\n }\n result = await processor.processOutputStep({\n ...baseContext,\n systemMessages: [],\n stepNumber: 0,\n steps: [],\n finishReason: 'stop',\n toolCalls: [],\n text: extractTextFromMessages(messages),\n usage: { inputTokens: undefined, outputTokens: undefined, totalTokens: undefined },\n });\n break;\n\n case 'outputStream':\n // outputStream is for streaming chunks, not a simple execute\n throw new HTTPException(400, {\n message: 'outputStream phase cannot be executed directly. Use streaming instead.',\n });\n\n default:\n throw new HTTPException(400, { message: `Unknown phase: ${phase}` });\n }\n\n // Process the result\n let outputMessages = messages;\n if (result) {\n if (Array.isArray(result)) {\n outputMessages = result;\n } else if (result.get && result.get.all && typeof result.get.all.db === 'function') {\n // It's a MessageList\n outputMessages = result.get.all.db();\n } else if (result.messages) {\n outputMessages = result.messages;\n }\n }\n\n return {\n success: true,\n phase,\n messages: outputMessages,\n messageList: {\n messages: outputMessages,\n },\n };\n } catch (error: any) {\n // Check if it's a tripwire\n if (tripwireTriggered || error.message?.startsWith('TRIPWIRE:')) {\n return {\n success: false,\n phase,\n tripwire: {\n triggered: true,\n reason: tripwireReason || error.message?.replace('TRIPWIRE:', ''),\n metadata: tripwireMetadata,\n },\n messages,\n messageList: {\n messages,\n },\n };\n }\n throw error;\n }\n } catch (error) {\n return handleError(error, 'Error executing processor');\n }\n },\n});\n"],"mappings":";;;;;;;;;;;AA0BA,SAAS,wBAAwB,UAA6B;CAC5D,IAAI,CAAC,YAAY,CAAC,MAAM,QAAQ,QAAQ,KAAK,SAAS,WAAW,GAC/D,OAAO;CAET,MAAM,eAAe,SAAS;CAC9B,IAAI,cAAc,SAAS,OAIzB,OAHkB,aAAa,QAAQ,MACpC,QAAQ,SAAc,MAAM,SAAS,MAAM,CAAC,CAC5C,KAAK,SAAc,MAAM,QAAQ,EACrB,CAAC,CAAC,KAAK,EAAE;CAE1B,OAAO;AACT;;;;;;;AAQA,SAAS,sBAAsB,WAAkC;CAE/D,IAAI,oBAAoB,SAAS,GAG/B,OAAO;EAAC;EAAS;EAAa;EAAgB;EAAgB;EAAc;CAAY;CAI1F,MAAM,SAA2B,CAAC;CAClC,IAAI,OAAO,UAAU,iBAAiB,YACpC,OAAO,KAAK,OAAO;CAErB,IAAI,OAAO,UAAU,qBAAqB,YACxC,OAAO,KAAK,WAAW;CAEzB,IAAI,OAAO,UAAU,wBAAwB,YAC3C,OAAO,KAAK,cAAc;CAE5B,IAAI,OAAO,UAAU,wBAAwB,YAC3C,OAAO,KAAK,cAAc;CAE5B,IAAI,OAAO,UAAU,sBAAsB,YACzC,OAAO,KAAK,YAAY;CAE1B,IAAI,OAAO,UAAU,sBAAsB,YACzC,OAAO,KAAK,YAAY;CAE1B,OAAO;AACT;AAEA,MAAa,wBAAwB,YAAY;CAC/C,QAAQ;CACR,MAAM;CACN,cAAc;CACd,gBAAgB;CAChB,SAAS;CACT,aAAa;CACb,MAAM,CAAC,YAAY;CACnB,cAAc;CACd,SAAS,OAAO,EAAE,aAAa;EAC7B,IAAI;GACF,MAAM,aAAa,OAAO,eAAe,KAAK,CAAC;GAC/C,MAAM,0BAA0B,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ACX,SACF;IACF;IAEF,MAAM;GACR;EACF,SAAS,OAAO;GACd,OAAO,YAAY,OAAO,2BAA2B;EACvD;CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"processors.js","names":[],"sources":["../../../src/server/handlers/processors.ts"],"sourcesContent":["import { MessageList } from '@mastra/core/agent';\nimport type { MessageInput } from '@mastra/core/agent/message-list';\nimport { isProcessorWorkflow } from '@mastra/core/processors';\nimport type { Processor, ProcessorWorkflow } from '@mastra/core/processors';\n\nimport { HTTPException } from '../http-exception';\nimport {\n listProcessorsResponseSchema,\n serializedProcessorDetailSchema,\n processorIdPathParams,\n executeProcessorBodySchema,\n executeProcessorResponseSchema,\n} from '../schemas/processors';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { handleError } from './error';\n\n// ============================================================================\n// Route Definitions\n// ============================================================================\n\ntype ProcessorPhase =\n | 'input'\n | 'inputStep'\n | 'outputStream'\n | 'outputResult'\n | 'outputStep'\n | 'toolResult'\n | 'llmRequest';\n\n/**\n * Helper to extract text from messages for outputStep testing.\n * In real usage, the `text` field contains the assistant's response text.\n */\nfunction extractTextFromMessages(messages: unknown[]): string {\n if (!messages || !Array.isArray(messages) || messages.length === 0) {\n return '';\n }\n const firstMessage = messages[0] as any;\n if (firstMessage?.content?.parts) {\n const textParts = firstMessage.content.parts\n .filter((part: any) => part?.type === 'text')\n .map((part: any) => part?.text || '');\n return textParts.join('');\n }\n return '';\n}\n\n/**\n * Helper to detect phases for a processor.\n * For individual processors, checks which methods are implemented.\n * For workflow processors, returns all phases since createStep handles each phase\n * and it's a no-op if the underlying processor doesn't implement it.\n */\nfunction detectProcessorPhases(processor: any): ProcessorPhase[] {\n // Check if it's a workflow processor\n if (isProcessorWorkflow(processor)) {\n // Workflow processors can potentially handle all phases\n // The createStep in workflows handles each phase and it's a no-op if not implemented\n return ['input', 'inputStep', 'outputStream', 'outputResult', 'outputStep', 'toolResult'];\n }\n\n // For individual processors, detect by checking which methods exist\n const phases: ProcessorPhase[] = [];\n if (typeof processor.processInput === 'function') {\n phases.push('input');\n }\n if (typeof processor.processInputStep === 'function') {\n phases.push('inputStep');\n }\n if (typeof processor.processOutputStream === 'function') {\n phases.push('outputStream');\n }\n if (typeof processor.processOutputResult === 'function') {\n phases.push('outputResult');\n }\n if (typeof processor.processOutputStep === 'function') {\n phases.push('outputStep');\n }\n if (typeof processor.processToolResult === 'function') {\n phases.push('toolResult');\n }\n if (typeof processor.processLLMRequest === 'function') {\n phases.push('llmRequest');\n }\n return phases;\n}\n\nexport const LIST_PROCESSORS_ROUTE = createRoute({\n method: 'GET',\n path: '/processors',\n responseType: 'json',\n responseSchema: listProcessorsResponseSchema,\n summary: 'List all processors',\n description: 'Returns a list of all available individual processors',\n tags: ['Processors'],\n requiresAuth: true,\n handler: async ({ mastra }) => {\n try {\n const processors = mastra.listProcessors() || {};\n const processorConfigurations = mastra.listProcessorConfigurations();\n const result: Record<\n string,\n {\n id: string;\n name?: string;\n description?: string;\n phases: ProcessorPhase[];\n agentIds: string[];\n configurations: Array<{ agentId: string; type: 'input' | 'output' }>;\n isWorkflow: boolean;\n }\n > = {};\n\n // Iterate through all individual processors registered with Mastra\n for (const [processorKey, processorEntry] of Object.entries(processors)) {\n const processor = processorEntry as Processor | ProcessorWorkflow;\n const processorId = processor.id || processorKey;\n\n // Check if it's a workflow processor\n const isWorkflow = isProcessorWorkflow(processor);\n\n // Detect phases (handles both individual processors and workflow processors)\n const phases = detectProcessorPhases(processor);\n\n // Get agent configurations for this processor\n const configs = processorConfigurations.get(processorId) || [];\n const agentIds = [...new Set(configs.map(c => c.agentId))];\n const configurations = configs.map(c => ({ agentId: c.agentId, type: c.type }));\n\n result[processorId] = {\n id: processorId,\n name: processor.name || processorId,\n description: processor.description,\n phases,\n agentIds,\n configurations,\n isWorkflow,\n };\n }\n\n return result;\n } catch (error) {\n return handleError(error, 'Error getting processors');\n }\n },\n});\n\nexport const GET_PROCESSOR_BY_ID_ROUTE = createRoute({\n method: 'GET',\n path: '/processors/:processorId',\n responseType: 'json',\n pathParamSchema: processorIdPathParams,\n responseSchema: serializedProcessorDetailSchema,\n summary: 'Get processor by ID',\n description: 'Returns details for a specific processor including its phases and configurations',\n tags: ['Processors'],\n requiresAuth: true,\n handler: async ({ mastra, processorId }) => {\n try {\n // Get the processor from Mastra's registered processors\n let processorEntry: Processor | ProcessorWorkflow | undefined;\n try {\n processorEntry = mastra.getProcessorById(processorId) as Processor | ProcessorWorkflow;\n } catch {\n // getProcessorById throws if not found, try by key\n const processors = mastra.listProcessors() || {};\n processorEntry = processors[processorId as keyof typeof processors] as Processor | ProcessorWorkflow;\n }\n\n if (!processorEntry) {\n throw new HTTPException(404, { message: 'Processor not found' });\n }\n\n // Check if it's a workflow processor\n const isWorkflow = isProcessorWorkflow(processorEntry);\n\n // Detect phases (handles both individual processors and workflow processors)\n const phases = detectProcessorPhases(processorEntry);\n\n // Get agent configurations for this processor\n const configs = mastra.getProcessorConfigurations(processorId);\n const agents = mastra.listAgents() || {};\n const configurations = configs.map(c => ({\n agentId: c.agentId,\n agentName: agents[c.agentId]?.name || c.agentId,\n type: c.type,\n }));\n\n return {\n id: processorEntry.id,\n name: processorEntry.name || processorEntry.id,\n description: processorEntry.description,\n phases,\n configurations,\n isWorkflow,\n };\n } catch (error) {\n return handleError(error, 'Error getting processor');\n }\n },\n});\n\nexport const EXECUTE_PROCESSOR_ROUTE = createRoute({\n method: 'POST',\n path: '/processors/:processorId/execute',\n responseType: 'json',\n pathParamSchema: processorIdPathParams,\n bodySchema: executeProcessorBodySchema,\n responseSchema: executeProcessorResponseSchema,\n summary: 'Execute processor',\n description: 'Executes a specific processor with the provided input data',\n tags: ['Processors'],\n requiresAuth: true,\n handler: async ({ mastra, processorId, ...bodyParams }) => {\n try {\n const { phase, messages } = bodyParams;\n\n if (!processorId) {\n throw new HTTPException(400, { message: 'Processor ID is required' });\n }\n\n if (!phase) {\n throw new HTTPException(400, { message: 'Phase is required' });\n }\n\n if (phase === 'llmRequest') {\n // processLLMRequest operates on the provider prompt, not on messages\n throw new HTTPException(400, {\n message: 'llmRequest phase cannot be executed directly. It runs on the provider prompt during an agent call.',\n });\n }\n\n if (!messages || !Array.isArray(messages)) {\n throw new HTTPException(400, { message: 'Messages array is required' });\n }\n\n // Get the processor from Mastra's registered processors\n let processor;\n try {\n processor = mastra.getProcessorById(processorId);\n } catch {\n // getProcessorById throws if not found, try by key\n const processors = mastra.listProcessors() || {};\n processor = processors[processorId as keyof typeof processors];\n }\n\n if (!processor) {\n throw new HTTPException(404, { message: 'Processor not found' });\n }\n\n const messageList = new MessageList();\n messageList.add(messages as unknown as MessageInput[], 'input');\n\n // Check if this is a workflow processor\n if (isProcessorWorkflow(processor)) {\n // Execute workflow processor\n try {\n // Build inputData based on phase - each phase has different required fields\n const baseInputData = {\n phase: phase as 'input' | 'inputStep' | 'outputStream' | 'outputResult' | 'outputStep' | 'toolResult',\n messages: messageList.get.all.db(),\n messageList,\n retryCount: 0,\n };\n let inputData: typeof baseInputData & Record<string, unknown> = baseInputData;\n\n // Add phase-specific fields\n switch (phase) {\n case 'input':\n inputData = {\n ...inputData,\n systemMessages: [],\n };\n break;\n case 'inputStep':\n inputData = {\n ...inputData,\n stepNumber: 0,\n systemMessages: [],\n steps: [],\n model: '',\n tools: {},\n toolChoice: undefined,\n activeTools: [],\n providerOptions: undefined,\n modelSettings: undefined,\n structuredOutput: undefined,\n };\n break;\n case 'outputResult':\n inputData = {\n ...inputData,\n state: {},\n result: {\n text: extractTextFromMessages(messages),\n usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },\n finishReason: 'unknown',\n steps: [],\n },\n };\n break;\n case 'outputStep':\n inputData = {\n ...inputData,\n stepNumber: 0,\n systemMessages: [],\n steps: [],\n finishReason: 'stop',\n toolCalls: [],\n text: extractTextFromMessages(messages),\n };\n break;\n case 'outputStream':\n inputData = {\n ...inputData,\n part: null,\n streamParts: [],\n state: {},\n };\n break;\n case 'toolResult':\n inputData = {\n ...inputData,\n stepNumber: 0,\n toolName: '',\n toolCallId: '',\n args: undefined,\n toolResultValue: undefined,\n providerExecuted: false,\n systemMessages: [],\n steps: [],\n };\n break;\n }\n\n const run = await processor.createRun();\n const result = await run.start({\n inputData,\n });\n\n // Check for tripwire status\n if (result.status === 'tripwire') {\n return {\n success: false,\n phase,\n tripwire: {\n triggered: true,\n reason: result.tripwire.reason || `Tripwire triggered in workflow ${processor.id}`,\n metadata: result.tripwire.metadata,\n },\n messages,\n messageList: {\n messages,\n },\n };\n }\n\n // Check for execution failure\n if (result.status !== 'success') {\n throw new HTTPException(500, {\n message: `Processor workflow ${processor.id} failed with status: ${result.status}`,\n });\n }\n\n // Extract output from workflow result\n const output = result.result;\n let outputMessages = messages;\n\n if (output && typeof output === 'object') {\n if ('messages' in output && Array.isArray(output.messages)) {\n outputMessages = output.messages;\n } else if ('messageList' in output && output.messageList instanceof MessageList) {\n outputMessages = output.messageList.get.all.db();\n }\n }\n\n return {\n success: true,\n phase,\n messages: outputMessages,\n messageList: {\n messages: outputMessages,\n },\n };\n } catch (error: any) {\n // Re-throw HTTP exceptions\n if (error instanceof HTTPException) {\n throw error;\n }\n throw new HTTPException(500, {\n message: `Error executing processor workflow: ${error.message}`,\n });\n }\n }\n\n // Handle individual processor execution\n // Create the abort function for tripwire support\n let tripwireTriggered = false;\n let tripwireReason: string | undefined;\n let tripwireMetadata: unknown;\n\n const abort = (reason?: string, options?: { retry?: boolean; metadata?: unknown }) => {\n tripwireTriggered = true;\n tripwireReason = reason;\n tripwireMetadata = options?.metadata;\n throw new Error(`TRIPWIRE:${reason || 'Processor aborted'}`);\n };\n\n // Build the context based on phase\n const baseContext = {\n abort,\n retryCount: 0,\n messages: messageList.get.all.db(),\n messageList,\n state: {},\n };\n\n try {\n let result: any;\n\n // Execute the specific phase method on the individual processor\n switch (phase) {\n case 'input':\n if (!processor.processInput) {\n throw new HTTPException(400, { message: 'Processor does not support input phase' });\n }\n result = await processor.processInput({\n ...baseContext,\n systemMessages: [],\n });\n break;\n\n case 'inputStep':\n if (!processor.processInputStep) {\n throw new HTTPException(400, { message: 'Processor does not support inputStep phase' });\n }\n result = await processor.processInputStep({\n ...baseContext,\n systemMessages: [],\n stepNumber: 0,\n steps: [],\n // Pass empty/default values for all inputStep fields\n model: '' as any,\n tools: {},\n toolChoice: undefined,\n activeTools: [],\n providerOptions: undefined,\n modelSettings: undefined,\n structuredOutput: undefined,\n });\n break;\n\n case 'outputResult':\n if (!processor.processOutputResult) {\n throw new HTTPException(400, { message: 'Processor does not support outputResult phase' });\n }\n result = await processor.processOutputResult({\n ...baseContext,\n state: {},\n result: {\n text: extractTextFromMessages(messages),\n usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },\n finishReason: 'unknown',\n steps: [],\n },\n });\n break;\n\n case 'outputStep':\n if (!processor.processOutputStep) {\n throw new HTTPException(400, { message: 'Processor does not support outputStep phase' });\n }\n result = await processor.processOutputStep({\n ...baseContext,\n systemMessages: [],\n stepNumber: 0,\n steps: [],\n finishReason: 'stop',\n toolCalls: [],\n text: extractTextFromMessages(messages),\n usage: { inputTokens: undefined, outputTokens: undefined, totalTokens: undefined },\n });\n break;\n\n case 'outputStream':\n // outputStream is for streaming chunks, not a simple execute\n throw new HTTPException(400, {\n message: 'outputStream phase cannot be executed directly. Use streaming instead.',\n });\n\n default:\n throw new HTTPException(400, { message: `Unknown phase: ${phase}` });\n }\n\n // Process the result\n let outputMessages = messages;\n if (result) {\n if (Array.isArray(result)) {\n outputMessages = result;\n } else if (result.get && result.get.all && typeof result.get.all.db === 'function') {\n // It's a MessageList\n outputMessages = result.get.all.db();\n } else if (result.messages) {\n outputMessages = result.messages;\n }\n }\n\n return {\n success: true,\n phase,\n messages: outputMessages,\n messageList: {\n messages: outputMessages,\n },\n };\n } catch (error: any) {\n // Check if it's a tripwire\n if (tripwireTriggered || error.message?.startsWith('TRIPWIRE:')) {\n return {\n success: false,\n phase,\n tripwire: {\n triggered: true,\n reason: tripwireReason || error.message?.replace('TRIPWIRE:', ''),\n metadata: tripwireMetadata,\n },\n messages,\n messageList: {\n messages,\n },\n };\n }\n throw error;\n }\n } catch (error) {\n return handleError(error, 'Error executing processor');\n }\n },\n});\n"],"mappings":";;;;;;;;;;;AAiCA,SAAS,wBAAwB,UAA6B;CAC5D,IAAI,CAAC,YAAY,CAAC,MAAM,QAAQ,QAAQ,KAAK,SAAS,WAAW,GAC/D,OAAO;CAET,MAAM,eAAe,SAAS;CAC9B,IAAI,cAAc,SAAS,OAIzB,OAHkB,aAAa,QAAQ,MACpC,QAAQ,SAAc,MAAM,SAAS,MAAM,CAAC,CAC5C,KAAK,SAAc,MAAM,QAAQ,EACrB,CAAC,CAAC,KAAK,EAAE;CAE1B,OAAO;AACT;;;;;;;AAQA,SAAS,sBAAsB,WAAkC;CAE/D,IAAI,oBAAoB,SAAS,GAG/B,OAAO;EAAC;EAAS;EAAa;EAAgB;EAAgB;EAAc;CAAY;CAI1F,MAAM,SAA2B,CAAC;CAClC,IAAI,OAAO,UAAU,iBAAiB,YACpC,OAAO,KAAK,OAAO;CAErB,IAAI,OAAO,UAAU,qBAAqB,YACxC,OAAO,KAAK,WAAW;CAEzB,IAAI,OAAO,UAAU,wBAAwB,YAC3C,OAAO,KAAK,cAAc;CAE5B,IAAI,OAAO,UAAU,wBAAwB,YAC3C,OAAO,KAAK,cAAc;CAE5B,IAAI,OAAO,UAAU,sBAAsB,YACzC,OAAO,KAAK,YAAY;CAE1B,IAAI,OAAO,UAAU,sBAAsB,YACzC,OAAO,KAAK,YAAY;CAE1B,IAAI,OAAO,UAAU,sBAAsB,YACzC,OAAO,KAAK,YAAY;CAE1B,OAAO;AACT;AAEA,MAAa,wBAAwB,YAAY;CAC/C,QAAQ;CACR,MAAM;CACN,cAAc;CACd,gBAAgB;CAChB,SAAS;CACT,aAAa;CACb,MAAM,CAAC,YAAY;CACnB,cAAc;CACd,SAAS,OAAO,EAAE,aAAa;EAC7B,IAAI;GACF,MAAM,aAAa,OAAO,eAAe,KAAK,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AAU;MACR,WAAW;MACX,QAAQ,kBAAkB,MAAM,SAAS,QAAQ,aAAa,EAAE;MAChE,UAAU;KACZ;KACA;KACA,aAAa,EACX,SACF;IACF;IAEF,MAAM;GACR;EACF,SAAS,OAAO;GACd,OAAO,YAAY,OAAO,2BAA2B;EACvD;CACF;AACF,CAAC"}
|
|
@@ -2,7 +2,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
2
2
|
require("../../rolldown-runtime-Bd6kNlEP.cjs");
|
|
3
3
|
let _mastra_core_utils_zod_to_json = require("@mastra/core/utils/zod-to-json");
|
|
4
4
|
let _mastra_core_tools = require("@mastra/core/tools");
|
|
5
|
-
let crypto = require("crypto");
|
|
6
5
|
//#region src/server/handlers/responses.adapter.ts
|
|
7
6
|
/**
|
|
8
7
|
* Flattens Responses API message content into the plain-text shape Mastra agent
|
|
@@ -280,7 +279,7 @@ function mapMastraMessagesToResponseOutputItems({ messages, outputMessageId, sta
|
|
|
280
279
|
* Creates a stable assistant-message-backed response identifier.
|
|
281
280
|
*/
|
|
282
281
|
function createMessageId() {
|
|
283
|
-
return `msg_${
|
|
282
|
+
return `msg_${globalThis.crypto.randomUUID()}`;
|
|
284
283
|
}
|
|
285
284
|
/**
|
|
286
285
|
* Maps Responses API input into the plain execution messages Mastra agents expect.
|