1+ import { mastra } from "@/src/mastra" ;
2+ import { createAgentStreamResponse } from "@/lib/client-stream-to-ai-sdk" ;
3+ import type { UIMessage } from "ai" ;
4+
5+ export const maxDuration = 60 ;
6+
7+ interface ChatRequestBody {
8+ messages : UIMessage [ ] ;
9+ agentId ?: string ;
10+ threadId ?: string ;
11+ resourceId ?: string ;
12+ memory ?: {
13+ thread ?: string | { id : string ; resourceId ?: string } ;
14+ resource ?: string ;
15+ options ?: {
16+ lastMessages ?: number ;
17+ semanticRecall ?: boolean ;
18+ workingMemory ?: { enabled ?: boolean } ;
19+ } ;
20+ } ;
21+ maxSteps ?: number ;
22+ }
23+
24+ export async function POST ( req : Request ) {
25+ const body : ChatRequestBody = await req . json ( ) ;
26+
27+ // Get available agents dynamically from mastra
28+ const agentsMap = await mastra . getAgents ( ) ;
29+ const availableAgents = Object . keys ( agentsMap ) ;
30+
31+ // Use first available agent if none specified
32+ const agentId = body . agentId || availableAgents [ 0 ] ;
33+
34+ if ( ! agentId || ! availableAgents . includes ( agentId ) ) {
35+ return Response . json (
36+ { error : `Invalid or missing agentId. Available: ${ availableAgents . join ( ", " ) } ` } ,
37+ { status : 400 }
38+ ) ;
39+ }
40+
41+ if ( ! body . messages ?. length ) {
42+ return Response . json ( { error : "messages required" } , { status : 400 } ) ;
43+ }
44+
45+ try {
46+ return await createAgentStreamResponse ( mastra as Parameters < typeof createAgentStreamResponse > [ 0 ] , agentId , body . messages , {
47+ threadId : body . threadId ,
48+ resourceId : body . resourceId ,
49+ memory : body . memory ,
50+ maxSteps : body . maxSteps ?? 50 ,
51+ } ) ;
52+ } catch ( error ) {
53+ return Response . json (
54+ { error : error instanceof Error ? error . message : "Stream failed" } ,
55+ { status : 500 }
56+ ) ;
57+ }
58+ }
59+
60+ export async function GET ( ) {
61+ const agentsMap = await mastra . getAgents ( ) ;
62+ const availableAgents = Object . keys ( agentsMap ) ;
63+ return Response . json ( { agents : availableAgents , count : availableAgents . length } ) ;
64+ }
0 commit comments