import { randomUUID } from "node:crypto"; export function createOpencodeBackend(env) { const OC_URL = (env.OC_URL ?? "http://127.0.0.1:4097").replace(/\/$/, ""); const TITLE = env.OC_SESSION_TITLE ?? "pi-collab"; const PROVIDER = env.OC_PROVIDER ?? "opencode-go"; let model = env.OC_MODEL ?? "deepseek-v4-flash"; const PASSWORD = env.OC_PASSWORD ?? ""; const USER = env.OC_USER ?? "opencode"; const auth = PASSWORD ? { Authorization: "Basic " + Buffer.from(`${USER}:${PASSWORD}`).toString("base64") } : {}; const listeners = new Set(); const emit = (ev) => { for (const fn of listeners) { try { fn(ev); } catch { /* listener errors are isolated */ } } }; let sessionID = null; const partsByMessage = new Map(); const userMsgIds = new Set(); const finalized = new Set(); const pendingAgent = new Map(); const reasoningSet = new Set(); const toolState = new Map(); async function oc(path, opts = {}) { const res = await fetch(OC_URL + path, { ...opts, headers: { ...auth, "Content-Type": "application/json", ...(opts.headers ?? {}) }, }); if (!res.ok) { throw new Error( `opencode ${opts.method ?? "GET"} ${path} -> ${res.status} ${(await res.text().catch(() => "")).slice(0, 200)}`, ); } return res; } async function ensureSession() { const res = await oc("/session"); const sessions = await res.json(); const matching = (sessions ?? []) .filter((s) => s.title === TITLE) .sort((a, b) => (b.time?.created ?? 0) - (a.time?.created ?? 0)); const existing = matching[0]; if (existing) { sessionID = existing.id; console.log(`opencode: reusing session ${sessionID}`); return; } const created = await oc("/session", { method: "POST", body: JSON.stringify({ title: TITLE, model: { id: model, providerID: PROVIDER } }), }); sessionID = (await created.json()).id; console.log(`opencode: created session ${sessionID}`); } function getMsgParts(id) { let m = partsByMessage.get(id); if (!m) { m = new Map(); partsByMessage.set(id, m); } return m; } function joinedText(id) { return [...getMsgParts(id).values()] .filter((p) => p.type !== "reasoning") .map((p) => p.text) .join("\n"); } function markThinking(id, active) { if (active) { if (!reasoningSet.has(id)) { reasoningSet.add(id); emit({ type: "thinking", active: true }); } } else if (reasoningSet.delete(id) && reasoningSet.size === 0) { emit({ type: "thinking", active: false }); } } async function finalizeAgent(id, text) { if (userMsgIds.has(id) || finalized.has(id)) return; finalized.add(id); let t = text; if (t == null) { try { const res = await oc(`/session/${sessionID}/message/${id}`); const { parts } = await res.json(); t = (parts ?? []).filter((p) => p.type === "text").map((p) => p.text).join("\n"); } catch { t = ""; } } partsByMessage.delete(id); pendingAgent.delete(id); markThinking(id, false); if (!t.trim()) return; emit({ type: "final", messageID: id, text: t }); } function toolDetail(part) { const tool = part.tool ?? "tool"; const input = part.state?.input ?? {}; if (tool === "bash") return input.command ?? ""; if (typeof input.filePath === "string") return input.filePath; if (typeof input.description === "string") return input.description; if (typeof input.prompt === "string") return input.prompt; if (typeof input.pattern === "string") return input.pattern; if (typeof input.content === "string") return `(${input.content.length} chars)`; const keys = Object.keys(input).filter((k) => k !== "content"); return keys.join(", "); } function emitTool(part) { const state = part.state ?? {}; const status = state.status ?? "pending"; if (!["running", "completed", "error"].includes(status)) return; const prev = toolState.get(part.id); const detail = toolDetail(part); const tool = part.tool ?? prev?.tool ?? "tool"; const id = part.callID ?? part.id; if (!prev) { toolState.set(part.id, { tool, detail, status }); emit({ type: "tool", id, tool, detail, status }); return; } if (detail && !prev.detail) { prev.detail = detail; emit({ type: "tool", id, tool, detail, status }); } if (prev.status !== status) { prev.status = status; if (detail) prev.detail = detail; emit({ type: "tool", id, tool: prev.tool, detail: prev.detail, status }); } } function handleEvent(ev) { const { type, properties: p } = ev ?? {}; if (!p || (p.sessionID && p.sessionID !== sessionID)) return; switch (type) { case "message.part.delta": { if (p.field !== "text") break; const id = p.messageID; if (!id || userMsgIds.has(id)) break; const parts = getMsgParts(id); const entry = parts.get(p.partID) ?? { type: "unknown", text: "" }; entry.text += p.delta ?? ""; parts.set(p.partID, entry); if (entry.type === "reasoning") break; if (p.delta) markThinking(id, false); emit({ type: "text", messageID: id, text: joinedText(id) }); break; } case "message.part.updated": { const part = p.part; if (!part || userMsgIds.has(part.messageID)) break; if (part.type === "step-finish") { finalizeAgent(part.messageID, joinedText(part.messageID)); } else if (part.type === "tool") { emitTool(part); } else { const parts = getMsgParts(part.messageID); const entry = parts.get(part.id) ?? { type: "unknown", text: "" }; entry.type = part.type; if (part.type === "text" && part.text && part.text.length >= entry.text.length) { entry.text = part.text; } parts.set(part.id, entry); if (part.type === "step-start") { markThinking(part.messageID, true); } else if (part.type === "text") { if (part.text) markThinking(part.messageID, false); emit({ type: "text", messageID: part.messageID, text: joinedText(part.messageID) }); } } break; } case "message.updated": { const info = p.info; if (!info) break; if (info.role === "user") { userMsgIds.add(info.id); } else if (info.role === "assistant" && (info.finish || info.error)) { finalizeAgent(info.id, joinedText(info.id)); } break; } case "session.idle": { for (const id of [...partsByMessage.keys()]) finalizeAgent(id, joinedText(id)); break; } } } function handleSseChunk(chunk) { for (const line of chunk.split("\n")) { if (!line.startsWith("data:")) continue; const data = line.slice(5).trim(); if (!data || data === "[DONE]") continue; let ev; try { ev = JSON.parse(data); } catch { continue; } handleEvent(ev); } } function subscribeEvents() { async function run() { try { const res = await fetch(OC_URL + "/event", { headers: { ...auth, Accept: "text/event-stream" }, }); const reader = res.body.getReader(); const decoder = new TextDecoder(); let buf = ""; for (;;) { const { done, value } = await reader.read(); if (done) break; buf += decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n"); let idx; while ((idx = buf.indexOf("\n\n")) !== -1) { const chunk = buf.slice(0, idx); buf = buf.slice(idx + 2); handleSseChunk(chunk); } } } catch (err) { console.error("opencode SSE stream ended:", err.message); } setTimeout(run, 1000); } run(); } return { name: "opencode", async connect() { await ensureSession(); subscribeEvents(); }, getModel() { return model; }, prompt({ messageID, did, user, text }) { userMsgIds.add(messageID); // Include the human-facing name (nick or resolved handle) with the DID. const who = user && user !== did ? `${did} (${user})` : did; oc(`/session/${sessionID}/prompt_async`, { method: "POST", body: JSON.stringify({ messageID, parts: [{ type: "text", text: `[${who}] ${text}` }], model: { providerID: PROVIDER, modelID: model }, }), }).catch((err) => { emit({ type: "error", text: err.message }); }); }, async newSession() { const created = await oc("/session", { method: "POST", body: JSON.stringify({ title: TITLE, model: { id: model, providerID: PROVIDER } }), }); sessionID = (await created.json()).id; partsByMessage.clear(); userMsgIds.clear(); finalized.clear(); pendingAgent.clear(); reasoningSet.clear(); toolState.clear(); console.log(`opencode: new session ${sessionID}`); return "fresh opencode session started"; }, async compact() { await oc(`/api/session/${sessionID}/compact`, { method: "POST" }); return "session context compacted"; }, async setModel(id) { model = id; return `Model set to \`${id}\``; }, onEvent(fn) { listeners.add(fn); return () => listeners.delete(fn); }, dispose() { listeners.clear(); }, }; }