feat(api): companion route drives claude CLI + MCP tools (subscription auth)
Replaces the runTurn/callModel/Anthropic-API-key path in POST /turn with runClaudeTurn (claude CLI) backed by a per-turn MCP config that spawns companion-stdio.js. Extracts pending_change_id from tool_result events defensively (structuredContent → text-JSON fallback). Rewrites companion test to inject fake-claude-draft.js via app.locals.claudeExe. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -1,13 +1,16 @@
|
||||
import { Router } from 'express';
|
||||
import { z } from 'zod';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { writeFile, unlink } from 'fs/promises';
|
||||
import { join } from 'path';
|
||||
import { tmpdir } from 'os';
|
||||
import { randomUUID } from 'crypto';
|
||||
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';
|
||||
import { runClaudeTurn } from '../../ai/claude_cli.js';
|
||||
|
||||
const COMPANION_SLUG = 'companion';
|
||||
|
||||
@@ -15,18 +18,17 @@ const SYSTEM = `You are the Void companion — a concise, helpful assistant embe
|
||||
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.`;
|
||||
|
||||
/** Absolute path to the companion MCP stdio server. */
|
||||
const COMPANION_STDIO_PATH = fileURLToPath(
|
||||
new URL('../../mcp/companion-stdio.js', import.meta.url)
|
||||
);
|
||||
|
||||
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) => {
|
||||
@@ -59,37 +61,132 @@ spacesScopedRouter.post('/turn',
|
||||
});
|
||||
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 });
|
||||
// Write a per-turn MCP config temp file declaring the companion stdio server.
|
||||
// DB connection env is inherited from the void-server process — no creds needed here.
|
||||
const mcpConfigPath = join(tmpdir(), `void-mcp-${randomUUID()}.json`);
|
||||
const agentActor = {
|
||||
kind: 'agent',
|
||||
id: agent.id,
|
||||
capabilities: agent.capabilities,
|
||||
scopes: agent.scopes
|
||||
};
|
||||
const mcpConfig = {
|
||||
mcpServers: {
|
||||
void: {
|
||||
command: 'node',
|
||||
args: [COMPANION_STDIO_PATH],
|
||||
env: {
|
||||
VOID_SPACE_ID: req.params.space_id,
|
||||
VOID_AGENT_JSON: JSON.stringify(agentActor),
|
||||
VOID_VIEW_JSON: view ? JSON.stringify(view) : ''
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
await writeFile(mcpConfigPath, JSON.stringify(mcpConfig));
|
||||
|
||||
const history = toAnthropicHistory(await messages.listByConversation(convo.id));
|
||||
const claudeExe = req.app.locals.claudeExe || process.env.CLAUDE_EXE || 'claude';
|
||||
const draftIds = [];
|
||||
|
||||
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)
|
||||
result = await runClaudeTurn({
|
||||
sessionId: convo.id,
|
||||
systemPrompt: SYSTEM,
|
||||
userText: text,
|
||||
mcpConfigPath,
|
||||
allowedTools: [
|
||||
'mcp__void__search',
|
||||
'mcp__void__read',
|
||||
'mcp__void__context',
|
||||
'mcp__void__propose_change'
|
||||
],
|
||||
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') {
|
||||
// Extract pending_change_id from the MCP tool result.
|
||||
//
|
||||
// companion-stdio.js returns:
|
||||
// { content: [{ type:'text', text: JSON.stringify(result) }], structuredContent: result }
|
||||
//
|
||||
// claude_cli.js surfaces this as:
|
||||
// { type:'tool_result', name, result: raw.content }
|
||||
// where result = the content array: [{ type:'text', text:'...' }]
|
||||
//
|
||||
// Defensive parsing: try structuredContent first (future-proof), then
|
||||
// scan content array text blocks and JSON.parse them.
|
||||
let parsed = null;
|
||||
try {
|
||||
// Shape A: structuredContent forwarded through (hypothetical future CLI)
|
||||
if (e.result?.structuredContent?.pending_change_id) {
|
||||
parsed = e.result.structuredContent;
|
||||
}
|
||||
// Shape B: array of content blocks (real current shape from companion-stdio.js)
|
||||
if (!parsed && Array.isArray(e.result)) {
|
||||
for (const block of e.result) {
|
||||
if (block?.type === 'text' && block.text) {
|
||||
try {
|
||||
const candidate = JSON.parse(block.text);
|
||||
if (candidate?.pending_change_id) {
|
||||
parsed = candidate;
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
// not JSON or not a change result — skip
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// parsing failed — no draft to surface
|
||||
}
|
||||
|
||||
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 });
|
||||
}
|
||||
// 'result' events are captured via the resolved return value; no SSE needed mid-stream.
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
send('error', { message: String(e?.message || e) });
|
||||
return res.end();
|
||||
res.end();
|
||||
// Clean up temp file even on error
|
||||
unlink(mcpConfigPath).catch(() => {});
|
||||
return;
|
||||
}
|
||||
|
||||
// Clean up the temp MCP config file
|
||||
unlink(mcpConfigPath).catch(() => {});
|
||||
|
||||
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 }
|
||||
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: result.draftIds, usage: result.usage });
|
||||
send('done', {
|
||||
assistant_message_id: assistant.id,
|
||||
draft_ids: draftIds,
|
||||
usage: result.usage
|
||||
});
|
||||
res.end();
|
||||
})
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user