feat(dross): global (space-less) Dross conversation + SSE turn

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
root
2026-06-09 23:54:01 +10:00
parent 7a09b9f91c
commit 1df0a905a2
2 changed files with 110 additions and 0 deletions

View File

@@ -4,8 +4,14 @@ import { validate } from '../validate.js';
import { asyncWrap } from '../errors.js';
import { requireOwner } from '../cap.js';
import * as settings from '../../db/repos/app_settings.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 DEFAULT_SETTINGS = { avatar: 'soft-eye', accent: '#a86adf', persona: '', voiceMode: 'review' };
const COMPANION_SLUG = 'companion';
export const router = Router();
@@ -21,3 +27,87 @@ const settingsBody = z.object({
});
router.put('/settings', requireOwner, validate({ body: settingsBody }),
asyncWrap(async (req, res) => res.json(await settings.set('dross', req.body))));
async function resolve() {
const agent = await agents.getBySlug(COMPANION_SLUG);
const convo = await conversations.findOrCreateGlobal(agent.id, { kind: 'user', id: null });
return { agent, convo };
}
router.get('/', asyncWrap(async (_req, res) => {
const { agent, convo } = await resolve();
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),
view: z.object({ entityType: z.string(), entityId: z.string() }).partial().nullish()
});
router.post('/turn', requireOwner, validate({ body: turnSchema }), asyncWrap(async (req, res) => {
const { agent, convo } = await resolve();
const { text, view } = req.body;
const cfg = await getCfg();
const persona = (cfg.persona && cfg.persona.trim()) ? cfg.persona : personaFor(COMPANION_SLUG);
const priorTurns = (await messages.listByConversation(convo.id)).length;
const resume = priorTurns > 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';
const companionTools = ['mcp__void__search', 'mcp__void__read', 'mcp__void__context', 'mcp__void__propose_change'];
const draftIds = [];
let result;
try {
result = await runAgentTurn({
agent, persona, registryName: undefined, toolNames: companionTools,
spaceId: null, view, 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 === 'tool_result') {
let parsed = null;
const tryParse = (s) => { try { return JSON.parse(s); } catch { return null; } };
if (typeof e.result === 'string') {
parsed = tryParse(e.result);
} else if (e.result?.structuredContent?.pending_change_id) {
parsed = e.result.structuredContent;
} else if (Array.isArray(e.result)) {
for (const b of e.result) {
const c = b?.type === 'text' && b.text ? tryParse(b.text) : null;
if (c?.pending_change_id) { parsed = c; break; }
}
}
if (parsed?.pending_change_id) {
draftIds.push(parsed.pending_change_id);
send('draft', { type: 'draft', pending_change_id: parsed.pending_change_id, summary: parsed.summary || 'a change' });
}
} else if (e.type === 'error') {
send('error', { type: 'error', message: e.message });
}
}
});
} catch (e) {
send('error', { message: String(e?.message || e) });
res.end();
return;
}
const assistant = await messages.append(convo.id, {
role: 'assistant', body: result.text, agent_id: agent.id,
metadata: { tool_trace: result.toolTrace, draft_ids: draftIds, usage: result.usage }
});
send('done', { assistant_message_id: assistant.id, draft_ids: draftIds, usage: result.usage });
res.end();
}));

View File

@@ -12,6 +12,26 @@ beforeAll(async () => {
app = createApp();
});
describe('dross chat', () => {
it('GET /api/dross returns a global conversation + Dross agent', async () => {
const res = await request(app).get('/api/dross').set(owner);
expect(res.status).toBe(200);
expect(res.body.conversation_id).toBeTruthy();
expect(res.body.agent.slug).toBe('companion');
expect(Array.isArray(res.body.messages)).toBe(true);
});
it('POST /api/dross/turn rejects empty text (400)', async () => {
const res = await request(app).post('/api/dross/turn').set(owner).send({ text: '' });
expect(res.status).toBe(400);
});
it('GET /api/dross without token is 401', async () => {
const res = await request(app).get('/api/dross');
expect(res.status).toBe(401);
});
});
describe('dross settings', () => {
it('GET /api/dross/settings returns defaults', async () => {
const res = await request(app).get('/api/dross/settings').set(owner);