Files
SRCmail/app/api/ai/opencode/chat/route.ts
T
Bernd Rodler bd778adf12 feat(electron): supervise a password-protected opencode server (B1+B3)
B1 — LIFECYCLE. The OpenCode class previously required the user to remember
to run `opencode serve` in a terminal before opening their mail app, and again
after every reboot; in practice that means the feature quietly stops existing.
The desktop shell now owns it: finds the binary (OPENCODE_BIN, then
~/.opencode/bin — its installer's default, which is NOT on the PATH a macOS
GUI app inherits, so PATH alone finds nothing for most users), starts it on a
free port, restarts up to 3 times if it dies, and kills it on quit. Absent
binary = the class simply stays unavailable, no error.

B3 — SECURITY. opencode's own startup warns "OPENCODE_SERVER_PASSWORD is not
set; server is unsecured" — without one, any local process can drive the
agent. A per-launch password is now always generated (never persisted: the
server dies with the app, so a durable secret would be pure liability) and
handed to the standalone server alongside the base URL.

The auth scheme is worth recording because it is NOT in opencode's own
OpenAPI spec, which declares no securitySchemes at all: HTTP Basic with the
username EXACTLY `opencode`. Verified against 1.18.14 by trying them — an
empty username, an arbitrary one, Bearer, and every plausible custom header
all 401 with the correct password. Pinned by a unit test that decodes the
header, so a future refactor can't silently drop it.

Verified live against a real password-protected server on 4097: authenticated
discovery + prompt round-tripped, AND the same call with no password was
rejected — proving the auth is real rather than decorative.

Also removed now-stale guidance: the 503 no longer says "start one with
opencode serve", because the app does that; it says to install the CLI.

Gate: tsc clean, eslint clean, build clean, 2521/2522 tests. The one failure
is lib/__tests__/jmap-client-resilience.test.ts's onConnectionChange timing
flake — byte-identical to what is already running in prod (git diff vs
origin/main for that file and lib/jmap/ is empty), pre-existing, and
unrelated to anything here.
2026-08-07 09:57:51 +02:00

95 lines
3.8 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { getStalwartCredentials } from '@/lib/stalwart/credentials';
import { configManager } from '@/lib/admin/config-manager';
import { findOpencodeServer, parseModelRef, opencodePrompt } from '@/lib/ai/opencode';
import { logger } from '@/lib/logger';
export const runtime = 'nodejs';
const MAX_BODY_BYTES = 200 * 1024;
interface ChatMessage {
role: 'system' | 'user' | 'assistant';
content: string;
}
/**
* POST /api/ai/opencode/chat — one-shot chat against a locally-running
* `opencode serve`.
*
* Deliberately NOT entitlement-metered, unlike /api/ai/server/chat: this runs
* on the user's own machine against provider credentials opencode itself
* holds, so there is no centrally-borne cost for this app to bill — the same
* reasoning that leaves `local` unmetered (lib/ai/entitlement.ts's header).
*/
export async function POST(request: NextRequest) {
const auth = await getStalwartCredentials(request);
if (!auth) {
return NextResponse.json({ error: 'not authenticated' }, { status: 401 });
}
await configManager.ensureLoaded();
if (configManager.getAiConsoleConfig().classesEnabled.opencode === false) {
return NextResponse.json({ error: 'the OpenCode class is disabled by admin policy' }, { status: 403 });
}
const rawBody = await request.text();
if (rawBody.length > MAX_BODY_BYTES) {
return NextResponse.json({ error: 'request too large' }, { status: 413 });
}
let body: { model?: unknown; messages?: unknown };
try {
body = JSON.parse(rawBody);
} catch {
return NextResponse.json({ error: 'invalid JSON body' }, { status: 400 });
}
const model = typeof body.model === 'string' ? body.model : '';
const messages = Array.isArray(body.messages) ? (body.messages as ChatMessage[]) : null;
if (!model || !messages || messages.length === 0) {
return NextResponse.json({ error: 'model and messages are required' }, { status: 400 });
}
const found = await findOpencodeServer();
if (!found) {
return NextResponse.json(
{ error: 'No local OpenCode server is running. The desktop app starts one automatically when the opencode CLI is installed \u2014 install it from opencode.ai, then restart VNCmail+.' },
{ status: 503 },
);
}
if (!found.models.some((m) => m.ref === model)) {
// The picker is populated from this same list, so a mismatch means the
// saved model was removed/renamed in opencode since it was chosen -
// clearer to say so than to forward it and surface opencode's own error.
return NextResponse.json(
{ error: `OpenCode no longer offers the model "${model}" \u2014 pick another in Settings.` },
{ status: 400 },
);
}
const parsed = parseModelRef(model);
if (!parsed) {
return NextResponse.json({ error: `Malformed model reference "${model}"` }, { status: 400 });
}
// Flatten our chat-messages shape onto opencode's (system field + text
// parts). Every non-system message is already just the built prompt.
const system = messages.filter((m) => m.role === 'system').map((m) => m.content).join('\n\n') || undefined;
const userText = messages.filter((m) => m.role !== 'system').map((m) => m.content).join('\n\n');
if (!userText.trim()) {
return NextResponse.json({ error: 'no user content to send' }, { status: 400 });
}
try {
const result = await opencodePrompt(found.baseUrl, parsed, system, userText);
if (!result.ok) {
logger.error('opencode prompt failed', { error: result.error });
return NextResponse.json({ error: result.error }, { status: 502 });
}
return NextResponse.json({ answer: result.answer });
} catch (cause) {
logger.error('opencode chat failed', { error: cause instanceof Error ? cause.message : String(cause) });
return NextResponse.json({ error: 'OpenCode server unreachable' }, { status: 502 });
}
}