feat(yerin): global security chat endpoint /api/security/yerin
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -28,6 +28,7 @@ import { router as weatherRouter } from './routes/weather.js';
|
|||||||
import { router as hostRouter } from './routes/host.js';
|
import { router as hostRouter } from './routes/host.js';
|
||||||
import { router as speedtestRouter } from './routes/speedtest.js';
|
import { router as speedtestRouter } from './routes/speedtest.js';
|
||||||
import { router as healthRouter } from './routes/health.js';
|
import { router as healthRouter } from './routes/health.js';
|
||||||
|
import { router as securityRouter } from './routes/security.js';
|
||||||
|
|
||||||
export function mountApi(app) {
|
export function mountApi(app) {
|
||||||
const api = Router();
|
const api = Router();
|
||||||
@@ -39,6 +40,7 @@ export function mountApi(app) {
|
|||||||
api.use('/spaces/:space_id/pages', pagesBySpaceRouter);
|
api.use('/spaces/:space_id/pages', pagesBySpaceRouter);
|
||||||
api.use('/spaces/:space_id/resources', resourcesBySpaceRouter);
|
api.use('/spaces/:space_id/resources', resourcesBySpaceRouter);
|
||||||
api.use('/spaces/:space_id/companion', companionRouter);
|
api.use('/spaces/:space_id/companion', companionRouter);
|
||||||
|
api.use('/security', securityRouter);
|
||||||
api.use('/projects', projectsRouter);
|
api.use('/projects', projectsRouter);
|
||||||
api.use('/projects/:project_id/tasks', tasksByProjectRouter);
|
api.use('/projects/:project_id/tasks', tasksByProjectRouter);
|
||||||
api.use('/tasks', tasksRouter);
|
api.use('/tasks', tasksRouter);
|
||||||
|
|||||||
67
lib/api/routes/security.js
Normal file
67
lib/api/routes/security.js
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
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();
|
||||||
|
}));
|
||||||
39
tests/api/security_yerin.test.js
Normal file
39
tests/api/security_yerin.test.js
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import { describe, it, expect, beforeAll } from 'vitest';
|
||||||
|
import { fileURLToPath } from 'url';
|
||||||
|
import request from 'supertest';
|
||||||
|
import { pool } from '../../lib/db/pool.js';
|
||||||
|
import { createApp } from '../../server.js';
|
||||||
|
import { resetDb } from '../helpers/db.js';
|
||||||
|
import { migrateUp } from '../../lib/db/migrate.js';
|
||||||
|
|
||||||
|
const FAKE = fileURLToPath(new URL('../fixtures/fake-claude-security.js', import.meta.url));
|
||||||
|
let app;
|
||||||
|
beforeAll(async () => {
|
||||||
|
await resetDb(); await migrateUp();
|
||||||
|
process.env.OWNER_TOKEN = 'test-token';
|
||||||
|
app = createApp();
|
||||||
|
app.locals.claudeExe = FAKE;
|
||||||
|
});
|
||||||
|
const auth = (r) => r.set('Authorization', 'Bearer test-token');
|
||||||
|
|
||||||
|
describe('Yerin security API', () => {
|
||||||
|
it('GET creates the global conversation and returns Yerin + empty history', async () => {
|
||||||
|
const res = await auth(request(app).get('/api/security/yerin'));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.body.agent.slug).toBe('yerin');
|
||||||
|
expect(res.body.conversation_id).toBeTruthy();
|
||||||
|
expect(res.body.messages).toEqual([]);
|
||||||
|
});
|
||||||
|
it('POST /turn streams SSE and persists user+assistant; no draft event', async () => {
|
||||||
|
const res = await auth(request(app).post('/api/security/yerin/turn')).send({ text: 'any new threats?' });
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.headers['content-type']).toMatch(/text\/event-stream/);
|
||||||
|
expect(res.text).toMatch(/event: delta/);
|
||||||
|
expect(res.text).toMatch(/event: tool/);
|
||||||
|
expect(res.text).toMatch(/event: done/);
|
||||||
|
expect(res.text).not.toMatch(/event: draft/);
|
||||||
|
const { rows: msgs } = await pool.query(`SELECT role, body FROM messages ORDER BY created_at`);
|
||||||
|
expect(msgs.map(m => m.role)).toEqual(['user', 'assistant']);
|
||||||
|
expect(msgs[1].body).toBe('No new threats.');
|
||||||
|
});
|
||||||
|
});
|
||||||
16
tests/fixtures/fake-claude-security.js
vendored
Executable file
16
tests/fixtures/fake-claude-security.js
vendored
Executable file
@@ -0,0 +1,16 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Fake claude CLI for the Yerin security route test. Emits text deltas + one
|
||||||
|
// security tool call (mcp__void__audit_log) + a result. No propose_change/draft.
|
||||||
|
const TOOL_USE_ID = 'toolu_yerin_01';
|
||||||
|
const lines = [
|
||||||
|
{ type: 'system', subtype: 'init', session_id: 'fake-yerin', tools: [], cwd: '/tmp' },
|
||||||
|
{ type: 'stream_event', event: { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } } },
|
||||||
|
{ type: 'stream_event', event: { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'No new threats.' } } },
|
||||||
|
{ type: 'stream_event', event: { type: 'content_block_stop', index: 0 } },
|
||||||
|
{ type: 'stream_event', event: { type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: TOOL_USE_ID, name: 'mcp__void__audit_log', input: {} } } },
|
||||||
|
{ type: 'stream_event', event: { type: 'content_block_stop', index: 1 } },
|
||||||
|
{ type: 'tool_result', tool_use_id: TOOL_USE_ID, content: [{ type: 'text', text: JSON.stringify({ entries: [] }) }] },
|
||||||
|
{ type: 'result', subtype: 'success', is_error: false, result: 'No new threats.', stop_reason: 'end_turn', session_id: 'fake-yerin', total_cost_usd: 0.0001, usage: { input_tokens: 40, output_tokens: 4 } }
|
||||||
|
];
|
||||||
|
for (const l of lines) process.stdout.write(JSON.stringify(l) + '\n');
|
||||||
|
process.exit(0);
|
||||||
Reference in New Issue
Block a user