import { Router } from 'express'; import { z } from 'zod'; 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(); async function getCfg() { return { ...DEFAULT_SETTINGS, ...(await settings.get('dross', {})) }; } router.get('/settings', asyncWrap(async (_req, res) => res.json(await getCfg()))); const settingsBody = z.object({ avatar: z.enum(['soft-eye', 'wisp', 'motes']), accent: z.string().regex(/^#[0-9a-fA-F]{6}$/), persona: z.string().max(8000), voiceMode: z.enum(['review', 'handsfree', 'action']) }); 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') { try { 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' }); } } catch { /* parsing failed — no draft to surface */ } } 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(); }));