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 { companionRegistry } from '../../ai/agent/tools/index.js'; import { runTurn } from '../../ai/agent/runtime.js'; import { makeCallModel, getAnthropicClient, DEFAULT_MODEL } from '../../ai/anthropic.js'; const COMPANION_SLUG = 'companion'; const SYSTEM = `You are the Void companion — a concise, helpful assistant embedded in a personal knowledge system. Ground answers in the Void's content: call the context tool to see what the owner is looking at, and search/read before answering factual questions. When the owner asks you to change something, use propose_change — it creates a draft they approve; you cannot apply changes directly. Be brief.`; async function resolveConversation(space_id) { const agent = await agents.getBySlug(COMPANION_SLUG); const convo = await conversations.findOrCreateForSpace(space_id, agent.id, { kind: 'user', id: null }); return { agent, convo }; } function toAnthropicHistory(rows) { return rows .filter(m => m.role === 'user' || m.role === 'assistant') .map(m => ({ role: m.role, content: m.body })); } export const spacesScopedRouter = Router({ mergeParams: true }); spacesScopedRouter.get('/', asyncWrap(async (req, res) => { const { agent, convo } = await resolveConversation(req.params.space_id); 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().optional() }); spacesScopedRouter.post('/turn', validate({ body: turnSchema }), asyncWrap(async (req, res) => { const { agent, convo } = await resolveConversation(req.params.space_id); const { text, view } = req.body; 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 callModel = req.app.locals.callModel || makeCallModel({ client: getAnthropicClient(), model: agent.model || DEFAULT_MODEL }); const history = toAnthropicHistory(await messages.listByConversation(convo.id)); let result; try { result = await runTurn({ callModel, registry: companionRegistry, system: SYSTEM, messages: history, ctx: { agent: { kind: 'agent', id: agent.id, capabilities: agent.capabilities, scopes: agent.scopes }, space_id: req.params.space_id, view: view ?? null, actor: req.actor }, onEvent: (e) => send(e.type, e) }); } 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, draft_ids: result.draftIds, usage: result.usage } }); send('done', { assistant_message_id: assistant.id, draft_ids: result.draftIds, usage: result.usage }); res.end(); }) );