From df0328641570dc6c0fbee4bfb46ecaf1ab400860 Mon Sep 17 00:00:00 2001 From: root Date: Mon, 1 Jun 2026 19:14:44 +1000 Subject: [PATCH] feat(api): companion SSE turn endpoint + per-Space history Co-Authored-By: Claude Opus 4.8 --- lib/api/index.js | 2 + lib/api/routes/companion.js | 95 +++++++++++++++++++++++++++++++++++++ tests/api/companion.test.js | 57 ++++++++++++++++++++++ 3 files changed, 154 insertions(+) create mode 100644 lib/api/routes/companion.js create mode 100644 tests/api/companion.test.js diff --git a/lib/api/index.js b/lib/api/index.js index ccf809f..9135232 100644 --- a/lib/api/index.js +++ b/lib/api/index.js @@ -22,6 +22,7 @@ import { router as auditRouter } from './routes/audit.js'; import { router as searchRouter } from './routes/search.js'; import { router as jobsRouter } from './routes/jobs.js'; import { router as captureRouter } from './routes/capture.js'; +import { spacesScopedRouter as companionRouter } from './routes/companion.js'; export function mountApi(app) { const api = Router(); @@ -32,6 +33,7 @@ export function mountApi(app) { api.use('/spaces/:space_id/tasks', tasksBySpaceRouter); api.use('/spaces/:space_id/pages', pagesBySpaceRouter); api.use('/spaces/:space_id/resources', resourcesBySpaceRouter); + api.use('/spaces/:space_id/companion', companionRouter); api.use('/projects', projectsRouter); api.use('/projects/:project_id/tasks', tasksByProjectRouter); api.use('/tasks', tasksRouter); diff --git a/lib/api/routes/companion.js b/lib/api/routes/companion.js new file mode 100644 index 0000000..ab2c0b3 --- /dev/null +++ b/lib/api/routes/companion.js @@ -0,0 +1,95 @@ +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(); + }) +); diff --git a/tests/api/companion.test.js b/tests/api/companion.test.js new file mode 100644 index 0000000..2141669 --- /dev/null +++ b/tests/api/companion.test.js @@ -0,0 +1,57 @@ +import { describe, it, expect, beforeAll } from 'vitest'; +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'; + +let app, spaceId; +beforeAll(async () => { + await resetDb(); await migrateUp(); + process.env.OWNER_TOKEN = 'test-token'; + ({ rows: [{ id: spaceId }] } = await pool.query( + `INSERT INTO spaces(slug,name) VALUES('s','S') RETURNING id`)); + app = createApp(); + let step = 0; + app.locals.callModel = async ({ onTextDelta }) => { + if (step++ === 0) return { text: '', toolUses: [{ id: 't1', name: 'propose_change', + input: { entity_type: 'task', action: 'create', payload: { space_id: spaceId, title: 'Validate CSV' } } }], stopReason: 'tool_use', usage: {} }; + for (const ch of 'Drafted a task.') onTextDelta?.(ch); + return { text: 'Drafted a task.', toolUses: [], stopReason: 'end_turn', usage: { output_tokens: 3 } }; + }; +}); + +const auth = (r) => r.set('Authorization', 'Bearer test-token'); + +describe('companion API', () => { + it('GET creates the conversation and returns empty history', async () => { + const res = await auth(request(app).get(`/api/spaces/${spaceId}/companion`)); + expect(res.status).toBe(200); + expect(res.body.conversation_id).toBeTruthy(); + expect(res.body.messages).toEqual([]); + }); + + it('POST /turn streams SSE events and persists messages + draft', async () => { + const res = await auth(request(app).post(`/api/spaces/${spaceId}/companion/turn`)) + .send({ text: 'make a task to validate the CSV' }); + expect(res.status).toBe(200); + expect(res.headers['content-type']).toMatch(/text\/event-stream/); + expect(res.text).toMatch(/event: tool/); + expect(res.text).toMatch(/event: draft/); + expect(res.text).toMatch(/event: delta/); + expect(res.text).toMatch(/event: done/); + + const { rows: msgs } = await pool.query( + `SELECT role, body, metadata FROM messages ORDER BY created_at`); + expect(msgs.map(m => m.role)).toEqual(['user', 'assistant']); + expect(msgs[1].body).toBe('Drafted a task.'); + expect(msgs[1].metadata.draft_ids).toHaveLength(1); + + const { rows: pc } = await pool.query(`SELECT * FROM pending_changes`); + expect(pc).toHaveLength(1); + expect(pc[0].status).toBe('pending'); + + const { rows: tasks } = await pool.query(`SELECT * FROM tasks WHERE title='Validate CSV'`); + expect(tasks).toHaveLength(0); // draft only, not applied + }); +});