|
@@ -0,0 +1,177 @@
|
|
|
|
|
+import { json } from '@sveltejs/kit';
|
|
|
|
|
+
|
|
|
|
|
+import { type ChatCompletionRequest, type ChatMessage, SESSION_ID_HEADER } from '$lib/api/agents';
|
|
|
|
|
+import { NotFoundError, server } from '$lib/server';
|
|
|
|
|
+
|
|
|
|
|
+import type { RequestHandler } from './$types';
|
|
|
|
|
+
|
|
|
|
|
+const SSE_HEADERS = {
|
|
|
|
|
+ 'Content-Type': 'text/event-stream',
|
|
|
|
|
+ 'Cache-Control': 'no-cache',
|
|
|
|
|
+ 'X-Accel-Buffering': 'no',
|
|
|
|
|
+} as const;
|
|
|
|
|
+
|
|
|
|
|
+/** Runtime template name used by agents that run the OpenCode headless server. */
|
|
|
|
|
+const OPENCODE_RUNTIME = 'opencode';
|
|
|
|
|
+
|
|
|
|
|
+/** Wrap a plain string as a single OpenAI-style SSE chat completion stream. */
|
|
|
|
|
+const toChatCompletionStream = (text: string): string => {
|
|
|
|
|
+ const chunk = { choices: [{ delta: { content: text }, index: 0 }] };
|
|
|
|
|
+ return `data: ${JSON.stringify(chunk)}\n\ndata: [DONE]\n\n`;
|
|
|
|
|
+};
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * Talk to an agent that exposes an OpenAI-compatible `/v1/chat/completions`
|
|
|
|
|
+ * endpoint (the default `loco-agent` runtime). The upstream stream is proxied
|
|
|
|
|
+ * back to the browser untouched.
|
|
|
|
|
+ */
|
|
|
|
|
+const proxyOpenAIChat = async (
|
|
|
|
|
+ endpoint: string,
|
|
|
|
|
+ messages: ChatMessage[],
|
|
|
|
|
+ signal: AbortSignal,
|
|
|
|
|
+): Promise<Response> => {
|
|
|
|
|
+ const resp = await fetch(new URL('/v1/chat/completions', endpoint), {
|
|
|
|
|
+ method: 'POST',
|
|
|
|
|
+ headers: { 'Content-Type': 'application/json' },
|
|
|
|
|
+ body: JSON.stringify({ messages, stream: true }),
|
|
|
|
|
+ signal,
|
|
|
|
|
+ });
|
|
|
|
|
+
|
|
|
|
|
+ if (!resp.ok) {
|
|
|
|
|
+ return new Response(await resp.text(), {
|
|
|
|
|
+ status: resp.status,
|
|
|
|
|
+ headers: { 'Content-Type': 'application/json' },
|
|
|
|
|
+ });
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return new Response(resp.body, { headers: SSE_HEADERS });
|
|
|
|
|
+};
|
|
|
|
|
+
|
|
|
|
|
+type OpenCodeSession = { id: string };
|
|
|
|
|
+type OpenCodePart = { type: string; text?: string };
|
|
|
|
|
+type OpenCodeMessageReply = { parts?: OpenCodePart[] };
|
|
|
|
|
+
|
|
|
|
|
+const openCodeUrl = (endpoint: string, path: string): URL => new URL(path, endpoint);
|
|
|
|
|
+
|
|
|
|
|
+const createOpenCodeSession = async (endpoint: string, signal: AbortSignal): Promise<string> => {
|
|
|
|
|
+ const resp = await fetch(openCodeUrl(endpoint, '/session'), {
|
|
|
|
|
+ method: 'POST',
|
|
|
|
|
+ headers: { 'Content-Type': 'application/json' },
|
|
|
|
|
+ body: JSON.stringify({ title: 'loco-admin agent test' }),
|
|
|
|
|
+ signal,
|
|
|
|
|
+ });
|
|
|
|
|
+ if (!resp.ok) {
|
|
|
|
|
+ throw new Error(`Failed to create OpenCode session (${resp.status}): ${await resp.text()}`);
|
|
|
|
|
+ }
|
|
|
|
|
+ const session = (await resp.json()) as OpenCodeSession;
|
|
|
|
|
+ if (!session.id) throw new Error('OpenCode session response did not include an id');
|
|
|
|
|
+ return session.id;
|
|
|
|
|
+};
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * Talk to an agent running the OpenCode headless server.
|
|
|
|
|
+ *
|
|
|
|
|
+ * OpenCode keeps conversation state server-side per session, so we only forward
|
|
|
|
|
+ * the latest user turn and let it own the history. The `POST /session/:id/message`
|
|
|
|
|
+ * call is synchronous — it resolves once the assistant turn is complete — so the
|
|
|
|
|
+ * reply is handed back as a single SSE chunk rather than token-by-token.
|
|
|
|
|
+ */
|
|
|
|
|
+const runOpenCodeChat = async (
|
|
|
|
|
+ endpoint: string,
|
|
|
|
|
+ messages: ChatMessage[],
|
|
|
|
|
+ sessionId: string | undefined,
|
|
|
|
|
+ signal: AbortSignal,
|
|
|
|
|
+): Promise<Response> => {
|
|
|
|
|
+ const latestUser = [...messages].reverse().find((m) => m.role === 'user');
|
|
|
|
|
+ if (!latestUser) {
|
|
|
|
|
+ return json({ code: 'BAD_REQUEST', message: 'No user message to send' }, { status: 400 });
|
|
|
|
|
+ }
|
|
|
|
|
+ const system = messages
|
|
|
|
|
+ .filter((m) => m.role === 'system')
|
|
|
|
|
+ .map((m) => m.content.trim())
|
|
|
|
|
+ .filter(Boolean)
|
|
|
|
|
+ .join('\n\n');
|
|
|
|
|
+
|
|
|
|
|
+ let session = sessionId;
|
|
|
|
|
+ try {
|
|
|
|
|
+ if (!session) session = await createOpenCodeSession(endpoint, signal);
|
|
|
|
|
+
|
|
|
|
|
+ const resp = await fetch(
|
|
|
|
|
+ openCodeUrl(endpoint, `/session/${encodeURIComponent(session)}/message`),
|
|
|
|
|
+ {
|
|
|
|
|
+ method: 'POST',
|
|
|
|
|
+ headers: { 'Content-Type': 'application/json' },
|
|
|
|
|
+ body: JSON.stringify({
|
|
|
|
|
+ parts: [{ type: 'text', text: latestUser.content }],
|
|
|
|
|
+ ...(system ? { system } : {}),
|
|
|
|
|
+ }),
|
|
|
|
|
+ signal,
|
|
|
|
|
+ },
|
|
|
|
|
+ );
|
|
|
|
|
+
|
|
|
|
|
+ if (!resp.ok) {
|
|
|
|
|
+ return new Response(
|
|
|
|
|
+ JSON.stringify({
|
|
|
|
|
+ code: 'OPENCODE_ERROR',
|
|
|
|
|
+ message: `OpenCode server returned ${resp.status}: ${await resp.text()}`,
|
|
|
|
|
+ }),
|
|
|
|
|
+ {
|
|
|
|
|
+ status: resp.status === 404 ? 502 : resp.status,
|
|
|
|
|
+ headers: { 'Content-Type': 'application/json' },
|
|
|
|
|
+ },
|
|
|
|
|
+ );
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const reply = (await resp.json()) as OpenCodeMessageReply;
|
|
|
|
|
+ const text = (reply.parts ?? [])
|
|
|
|
|
+ .filter((p) => p.type === 'text' && p.text)
|
|
|
|
|
+ .map((p) => p.text)
|
|
|
|
|
+ .join('');
|
|
|
|
|
+
|
|
|
|
|
+ return new Response(toChatCompletionStream(text), {
|
|
|
|
|
+ headers: { ...SSE_HEADERS, [SESSION_ID_HEADER]: session },
|
|
|
|
|
+ });
|
|
|
|
|
+ } catch (err) {
|
|
|
|
|
+ if (err instanceof Error && err.name === 'AbortError') {
|
|
|
|
|
+ return new Response(null, { status: 499 });
|
|
|
|
|
+ }
|
|
|
|
|
+ return json(
|
|
|
|
|
+ {
|
|
|
|
|
+ code: 'OPENCODE_ERROR',
|
|
|
|
|
+ message: err instanceof Error ? err.message : 'Failed to reach the OpenCode server',
|
|
|
|
|
+ },
|
|
|
|
|
+ { status: 502 },
|
|
|
|
|
+ );
|
|
|
|
|
+ }
|
|
|
|
|
+};
|
|
|
|
|
+
|
|
|
|
|
+const POST: RequestHandler = async ({ locals, params, request }) => {
|
|
|
|
|
+ const workspaceId = locals.workspaceId || '';
|
|
|
|
|
+ const agents = await server.catalog.getWorkspaceCatalog(workspaceId)?.agents.list();
|
|
|
|
|
+ const agent = agents?.find((m) => m.id === params.id);
|
|
|
|
|
+ if (!agent) {
|
|
|
|
|
+ throw new NotFoundError('Agent not found');
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const status = await server.resources
|
|
|
|
|
+ .getWorkspaceResources(workspaceId)
|
|
|
|
|
+ .agents.getAgentStatus(params.id);
|
|
|
|
|
+
|
|
|
|
|
+ const endpoint = status?.endpoint;
|
|
|
|
|
+ if (!endpoint) {
|
|
|
|
|
+ return json(
|
|
|
|
|
+ { code: 'ENDPOINT_UNAVAILABLE', message: 'Agent endpoint is not yet available' },
|
|
|
|
|
+ { status: 503 },
|
|
|
|
|
+ );
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const { messages, sessionId }: ChatCompletionRequest = await request.json();
|
|
|
|
|
+
|
|
|
|
|
+ if (agent.runtime.name === OPENCODE_RUNTIME) {
|
|
|
|
|
+ return runOpenCodeChat(endpoint, messages, sessionId, request.signal);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return proxyOpenAIChat(endpoint, messages, request.signal);
|
|
|
|
|
+};
|
|
|
|
|
+
|
|
|
|
|
+export { POST };
|