Spaces:
Runtime error
Runtime error
File size: 2,699 Bytes
4782147 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | import { agentRepository } from "lib/db/repository";
import { getSession } from "auth/server";
import { z } from "zod";
import { serverCache } from "lib/cache";
import { CacheKeys } from "lib/cache/cache-keys";
import { AgentCreateSchema, AgentQuerySchema } from "app-types/agent";
import { canCreateAgent } from "lib/auth/permissions";
export async function GET(request: Request) {
const session = await getSession();
if (!session?.user.id) {
return new Response("Unauthorized", { status: 401 });
}
try {
const url = new URL(request.url);
const queryParams = Object.fromEntries(url.searchParams);
const {
type,
filters: filtersParam,
limit,
} = AgentQuerySchema.parse(queryParams);
// Parse filters - can be passed as comma-separated string or single type
let filters;
if (filtersParam) {
filters = filtersParam.split(",").map((f) => f.trim());
} else {
// Fallback to single type parameter for backward compatibility
filters = [type];
}
// Use the new simplified selectAgents method with database-level filtering and limiting
const agents = await agentRepository.selectAgents(
session.user.id,
filters,
limit,
);
return Response.json(agents);
} catch (error) {
if (error instanceof z.ZodError) {
return Response.json(
{ error: "Invalid query parameters", details: error.message },
{ status: 400 },
);
}
console.error("Failed to fetch agents:", error);
return new Response("Internal Server Error", { status: 500 });
}
}
export async function POST(request: Request): Promise<Response> {
const session = await getSession();
if (!session?.user.id) {
return new Response("Unauthorized", { status: 401 });
}
// Check if user has permission to create agents
const hasPermission = await canCreateAgent();
if (!hasPermission) {
return Response.json(
{ error: "You don't have permission to create agents" },
{ status: 403 },
);
}
try {
const body = await request.json();
const data = AgentCreateSchema.parse(body);
const agent = await agentRepository.insertAgent({
...data,
userId: session.user.id,
});
serverCache.delete(CacheKeys.agentInstructions(agent.id));
return Response.json(agent);
} catch (error) {
if (error instanceof z.ZodError) {
return Response.json(
{ error: "Invalid input", details: error.message },
{ status: 400 },
);
}
console.error("Failed to upsert agent:", error);
return Response.json(
{ message: "Internal Server Error" },
{
status: 500,
},
);
}
}
|