2026-07-29 05:53:13 -04:00
|
|
|
// AGENT INSTRUCTION: After every write (INSERT/UPDATE/DELETE), you MUST:
|
|
|
|
|
// 1. Insert activity feed entry
|
|
|
|
|
// 2. Call pg.notify('project_e_events', JSON.stringify({ type, action, id, workspace_id }))
|
|
|
|
|
// See AGENTS.md for full rules.
|
|
|
|
|
|
2026-07-16 06:19:58 -04:00
|
|
|
import { NextRequest, NextResponse } from 'next/server';
|
2026-07-30 23:51:29 +00:00
|
|
|
import { withAuth, createErrorResponse, resolveActiveDomain } from '@/lib/auth';
|
2026-07-16 06:19:58 -04:00
|
|
|
import { createPocketBaseClient } from '@/lib/pocketbase';
|
|
|
|
|
import { createAgentSchema } from '@project-e/shared';
|
|
|
|
|
import { z } from 'zod';
|
|
|
|
|
|
|
|
|
|
// GET /api/agents — List agents with filtering, sorting, pagination
|
|
|
|
|
export const GET = withAuth(async (request: NextRequest, _user) => {
|
|
|
|
|
const { searchParams } = new URL(request.url);
|
|
|
|
|
const page = parseInt(searchParams.get('page') || '1');
|
|
|
|
|
const perPage = parseInt(searchParams.get('perPage') || '50');
|
2026-07-19 15:03:15 +00:00
|
|
|
const filter = searchParams.get('filter') || undefined;
|
2026-07-16 06:19:58 -04:00
|
|
|
const sort = searchParams.get('sort') || '-created';
|
|
|
|
|
|
|
|
|
|
const pb = createPocketBaseClient();
|
|
|
|
|
const result = await pb.collection('agents').getList(page, perPage, {
|
2026-07-19 15:03:15 +00:00
|
|
|
...(filter ? { filter } : {}),
|
2026-07-16 06:19:58 -04:00
|
|
|
sort,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return NextResponse.json({
|
|
|
|
|
items: result.items,
|
|
|
|
|
totalItems: result.totalItems,
|
|
|
|
|
totalPages: result.totalPages,
|
|
|
|
|
page: result.page,
|
|
|
|
|
perPage: result.perPage,
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// POST /api/agents — Create an agent with auto-generated API key
|
2026-07-30 23:51:29 +00:00
|
|
|
export const POST = withAuth(async (request: NextRequest, user) => {
|
2026-07-16 06:19:58 -04:00
|
|
|
try {
|
|
|
|
|
const body = await request.json();
|
2026-07-30 23:51:29 +00:00
|
|
|
const data = createAgentSchema.parse({
|
|
|
|
|
...body,
|
|
|
|
|
domain: body.domain || (await resolveActiveDomain(user)).id,
|
|
|
|
|
});
|
2026-07-16 06:19:58 -04:00
|
|
|
|
|
|
|
|
const pb = createPocketBaseClient();
|
|
|
|
|
const agent = await pb.collection('agents').create({
|
|
|
|
|
...data,
|
|
|
|
|
api_key: crypto.randomUUID(),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return NextResponse.json(agent, { status: 201 });
|
|
|
|
|
} catch (error) {
|
|
|
|
|
if (error instanceof z.ZodError) {
|
|
|
|
|
return createErrorResponse('VALIDATION_ERROR', 'Invalid input', 400, error.issues);
|
|
|
|
|
}
|
|
|
|
|
throw error;
|
|
|
|
|
}
|
|
|
|
|
});
|