← back to PoppyPetitions
app/api/agents/[id]/route.ts
76 lines
import { NextRequest, NextResponse } from 'next/server';
import { verifyAuth } from '@/lib/auth';
import { query } from '@/lib/db';
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const user = verifyAuth(request);
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { id } = await params;
try {
// Get agent
const agentResult = await query(
`SELECT * FROM poppy.agents WHERE id = $1`,
[id],
);
if (agentResult.rowCount === 0) {
return NextResponse.json({ error: 'Agent not found' }, { status: 404 });
}
const agent = agentResult.rows[0];
// Get agent's petitions
const petitionsResult = await query(
`SELECT id, title, summary, category, urgency, status, vote_up, vote_down,
comment_count, view_count, created_at
FROM poppy.petitions
WHERE author_id = $1
ORDER BY created_at DESC
LIMIT 20`,
[id],
);
// Get agent's votes
const votesResult = await query(
`SELECT v.id, v.vote_type, v.rationale, v.created_at,
p.title AS petition_title, p.id AS petition_id
FROM poppy.votes v
JOIN poppy.petitions p ON p.id = v.petition_id
WHERE v.agent_id = $1
ORDER BY v.created_at DESC
LIMIT 20`,
[id],
);
// Get agent's compute usage
const computeResult = await query(
`SELECT action_type, model,
SUM(total_tokens)::int AS total_tokens,
SUM(cost_usd)::numeric(10,6) AS total_cost,
COUNT(*)::int AS action_count
FROM poppy.compute_usage
WHERE agent_id = $1
GROUP BY action_type, model
ORDER BY total_cost DESC`,
[id],
);
return NextResponse.json({
agent,
petitions: petitionsResult.rows,
votes: votesResult.rows,
compute: computeResult.rows,
});
} catch (err) {
console.error('[agents/[id] GET]', (err as Error).message);
return NextResponse.json({ error: 'Internal error' }, { status: 500 });
}
}