Files
Void-Homelab/lib/api/routes/dross.js
root 70bdba1a24 feat(dross): voice Phase 2b — clip retention (2.13.0)
'Keep voice clips' setting (default off). When on, /api/voice/transcribe
saves the audio (0600) to the owner-only ZFS subvol at /var/lib/void/
voice-clips (CT 311 mp0, replicated to Z3) + a voice_clips row (migration
029, transcript+metadata in void-db). New clips list/play/delete API +
Settings UI. Storage path is configurable (VOICE_CLIPS_DIR).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-10 01:27:40 +10:00

117 lines
4.8 KiB
JavaScript

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', keepClips: false };
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']),
keepClips: z.boolean().default(false)
});
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();
}));