Files
Void-Homelab/lib/api/routes/security.js
2026-06-04 21:09:12 +10:00

68 lines
2.8 KiB
JavaScript

import { Router } from 'express';
import { z } from 'zod';
import { validate } from '../validate.js';
import { asyncWrap } from '../errors.js';
import * as conversations from '../../db/repos/conversations.js';
import * as messages from '../../db/repos/messages.js';
import * as agents from '../../db/repos/agents.js';
import { runAgentTurn } from '../../ai/agent/run_turn.js';
import { personaFor } from '../../ai/personas/index.js';
const YERIN_SLUG = 'yerin';
const SECURITY_TOOLS = [
'mcp__void__audit_log', 'mcp__void__agent_inventory', 'mcp__void__pending_review',
'mcp__void__resource_exposure', 'mcp__void__token_audit'
];
async function resolveYerin() {
const agent = await agents.getBySlug(YERIN_SLUG);
const convo = await conversations.findOrCreateGlobal(agent.id, { kind: 'user', id: null });
return { agent, convo };
}
export const router = Router();
router.get('/yerin', asyncWrap(async (_req, res) => {
const { agent, convo } = await resolveYerin();
const rows = await messages.listByConversation(convo.id);
res.json({ conversation_id: convo.id, agent: { id: agent.id, slug: agent.slug, name: agent.name }, messages: rows });
}));
const turnSchema = z.object({ text: z.string().min(1) });
router.post('/yerin/turn', validate({ body: turnSchema }), asyncWrap(async (req, res) => {
const { agent, convo } = await resolveYerin();
const { text } = req.body;
const resume = (await messages.listByConversation(convo.id)).length > 0;
await messages.append(convo.id, { role: 'user', body: text });
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
const send = (event, data) => res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
const claudeExe = req.app.locals.claudeExe || process.env.CLAUDE_EXE || 'claude';
let result;
try {
result = await runAgentTurn({
agent, persona: personaFor(agent.slug), registryName: 'security',
toolNames: SECURITY_TOOLS, spaceId: null, view: null,
sessionId: convo.id, resume, userText: text, claudeExe,
home: process.env.VOID_CLAUDE_HOME || undefined,
onEvent: (e) => {
if (e.type === 'delta') send('delta', { type: 'delta', text: e.text });
else if (e.type === 'tool') send('tool', { type: 'tool', tool: e.tool, status: e.status });
else if (e.type === 'error') send('error', { type: 'error', message: e.message });
}
});
} catch (e) {
send('error', { message: String(e?.message || e) });
return res.end();
}
const assistant = await messages.append(convo.id, {
role: 'assistant', body: result.text, agent_id: agent.id,
metadata: { tool_trace: result.toolTrace, usage: result.usage }
});
send('done', { assistant_message_id: assistant.id, usage: result.usage });
res.end();
}));