AI Engineering Workspace
PartialChat, files, terminal and preview in one place. Chat sessions run on a durable Postgres-backed queue (chat only: no tools or shell). Live models need an API key; the terminal is unavailable.
Project files
read-only- ..
- apple-touch-icon.png
- brand-guidelines-v2.md
- brand-manifest-v2.json
- favicon-16.png
- favicon-32.png
- favicon-48.png
- favicon.ico
- icon-192.png
- icon-512.png
- maskable-192.png
- maskable-512.png
- source-brand-board.png
- source-crop-icon-fullcolor.png
- source-crop-lockup-dark.png
- source-crop-wordmark-light.png
- zloud-app-icon-1024.png
- zloud-app-icon.svg
- zloud-favicon.svg
- zloud-mark-1024.png
- zloud-mark-512.png
- zloud-mark-mono-512.png
- zloud-mark-mono.svg
- zloud-mark-reversed.svg
- zloud-mark-white-512.png
- zloud-mark-white.svg
- zloud-mark.svg
- zloud-maskable.svg
- zloud-wordmark-dark.svg
- zloud-wordmark-light.svg
- zloud-wordmark-mono.svg
app/scripts/opencode-engine.mjs
1// OpenCode execution engine adapter. OpenCode is an execution ENGINE, not a sandbox: every run is constrained by2// - an isolated HOME/XDG tree (no access to our credentials/config),3// - a deny-by-default permission file that WE write (outside any workspace the agent can touch),4// - a throw-away scratch dir (chat mode) or a per-run git worktree guarded by a per-project lock (edit mode),5// - no network tools (webfetch/websearch denied), no shell tool, no external_directory access.6// It talks to OpenCode only through the CLI (`opencode run --standalone --format json`): no server port is ever opened.7import { spawn, execFile } from "node:child_process";8import fs from "node:fs"; import os from "node:os"; import path from "node:path";910export const OC_HOME = process.env.ZCS_OPENCODE_HOME || path.join(os.homedir(), ".local/opencode/home");11export const OC_BIN = process.env.ZCS_OPENCODE_BIN || path.join(os.homedir(), ".local/opencode/node_modules/.bin/opencode");12export const FREE_MODEL = m => /^opencode\/[\w.-]+$/.test(m) && (/-free$/.test(m) || m === "opencode/big-pickle");1314export function ocEnv() {15 return { PATH: process.env.PATH, HOME: OC_HOME, XDG_CONFIG_HOME: `${OC_HOME}/c`, XDG_DATA_HOME: `${OC_HOME}/d`, XDG_STATE_HOME: `${OC_HOME}/s`, XDG_CACHE_HOME: `${OC_HOME}/k`, NO_COLOR: "1" };16}17/** Permission policy written fresh before every run. "chat": nothing allowed. "edit": read + edit inside the worktree only. */18export function writePolicy(mode) {19 const rules = [{ action: "*", resource: "*", effect: "deny" }];20 if (mode === "edit") rules.push({ action: "read", resource: "*", effect: "allow" }, { action: "read", resource: "*.env*", effect: "deny" }, { action: "read", resource: "*.pem", effect: "deny" }, { action: "edit", resource: "*", effect: "allow" });21 const dir = path.join(OC_HOME, "c", "opencode"); fs.mkdirSync(dir, { recursive: true, mode: 0o700 });22 fs.writeFileSync(path.join(dir, "opencode.jsonc"), JSON.stringify({ $schema: "https://opencode.ai/config.json", permissions: rules }, null, 2), { mode: 0o600 });23 return rules;24}25export const installed = () => { try { fs.accessSync(OC_BIN, fs.constants.X_OK); return true; } catch { return false; } };26export function version() {27 return new Promise(res => execFile(OC_BIN, ["--version"], { env: ocEnv(), timeout: 15_000 }, (e, out) => res(e ? null : String(out).trim())));28}29export function listModels() {30 return new Promise(res => execFile(OC_BIN, ["models"], { env: ocEnv(), timeout: 30_000, maxBuffer: 1_000_000 }, (e, out) => res(e ? [] : String(out).split("\n").map(s => s.trim()).filter(l => /^[\w.-]+\/[\w.:-]+$/.test(l)))));31}3233const git = (cwd, args) => new Promise((res, rej) => execFile("git", ["-c", "core.hooksPath=/dev/null", "-c", "user.name=Zoo Cloud Studio", "-c", "user.email=studio@localhost", ...args], { cwd, timeout: 30_000, maxBuffer: 2_000_000, env: { PATH: process.env.PATH, HOME: cwd, GIT_CONFIG_NOSYSTEM: "1" } }, (e, o, er) => e ? rej(new Error(String(er || e.message).slice(0, 300))) : res(String(o))));34export const gitx = git;3536/** Pure parser for one JSON event line of `opencode run --format json` -> normalized events. */37export function parseEvent(line) {38 let j; try { j = JSON.parse(line); } catch { return []; }39 const p = j.part ?? {}; const out = [];40 if (j.sessionID) out.push({ engineSession: j.sessionID });41 if (j.type === "text" && p.text) out.push({ text: p.text });42 else if (j.type === "tool_use") out.push({ note: `tool ${p.tool}: ${p.state?.status}${p.state?.error ? " — " + String(p.state.error).slice(0, 120) : ""}`, tool: p.tool, status: p.state?.status });43 else if (j.type === "step_finish" && p.tokens) out.push({ usage: { in: p.tokens.input ?? 0, out: (p.tokens.output ?? 0) + (p.tokens.reasoning ?? 0), cost: typeof p.cost === "number" ? p.cost : undefined }, partialUsage: true });44 else if (j.type === "error") out.push({ error: String(j.error?.message ?? j.message ?? "engine error").slice(0, 300) });45 return out;46}4748/** Spawns the CLI in `cwd`; yields normalized events. Honors AbortSignal by killing the whole process group. */49export async function* runCli({ prompt, model, cwd, engineRef, signal }) {50 const args = ["run", "--standalone", "--format", "json", "--model", model, ...(engineRef ? ["--session", engineRef] : []), "--", prompt];51 const child = spawn(OC_BIN, args, { cwd, env: ocEnv(), detached: true, stdio: ["ignore", "pipe", "pipe"] });52 const kill = () => { try { process.kill(-child.pid, "SIGTERM"); } catch {} setTimeout(() => { try { process.kill(-child.pid, "SIGKILL"); } catch {} }, 3000).unref(); };53 signal?.addEventListener("abort", kill); let err = ""; child.stderr.on("data", d => { err = (err + d).slice(-800); });54 const exit = new Promise(r => child.on("close", (code, sig) => r({ code, sig }))); const spawnErr = new Promise(r => child.on("error", e => r(e)));55 let buf = ""; const dec = new TextDecoder();56 try {57 for await (const chunk of child.stdout) { buf += dec.decode(chunk, { stream: true }); let i; while ((i = buf.indexOf("\n")) >= 0) { const l = buf.slice(0, i); buf = buf.slice(i + 1); if (l.trim()) for (const ev of parseEvent(l)) yield ev; } }58 if (buf.trim()) for (const ev of parseEvent(buf)) yield ev;59 const r = await Promise.race([exit, spawnErr]); if (r instanceof Error) throw r;60 if (signal?.aborted) return; if (r.code !== 0) { const e = new Error(`opencode exited ${r.code ?? r.sig}: ${err.replace(/\s+/g, " ").slice(0, 300)}`); e.retryable = true; throw e; }61 } finally { signal?.removeEventListener("abort", kill); if (child.exitCode === null) kill(); }62}6364/**65 * Full engine run for the worker. ctx = { ses, run, pool, checkpoint, prompt, heartbeat }.66 * mode "chat": scratch dir, no tools. mode "edit": per-project lock + git worktree + guarded merge (only for projects the admin explicitly authorized).67 */68export async function* runOpenCode({ ses, run, pool, checkpoint, prompt, signal, mode, workspaceRoot, dataDir }) {69 writePolicy(mode);70 if (mode !== "edit") {71 // stable per-session EMPTY scratch dir: OpenCode ties a session to its directory, so session recovery needs the same cwd72 const scratch = path.join(dataDir, "scratch", ses.id); fs.mkdirSync(scratch, { recursive: true, mode: 0o700 });73 yield* runCli({ prompt, model: ses.model, cwd: scratch, engineRef: ses.engine_ref, signal }); return;74 }75 // ---- edit mode ----76 const pid = ses.project_id; const nowMs = Date.now(); const STALE = 120_000;77 const got = await pool.query(`INSERT INTO workspace_locks(project_id,run_id,locked_at) VALUES($1,$2,$3)78 ON CONFLICT(project_id) DO UPDATE SET run_id=EXCLUDED.run_id, locked_at=EXCLUDED.locked_at WHERE workspace_locks.run_id=EXCLUDED.run_id OR workspace_locks.locked_at < $4 RETURNING run_id`, [pid, run.id, nowMs, nowMs - STALE]);79 if (!got.rowCount) { const e = new Error("workspace busy: another agent holds the project lock"); e.retryable = true; e.retryAfterMs = 4000; e.waitOnly = true; throw e; }80 const beat = setInterval(() => pool.query("UPDATE workspace_locks SET locked_at=$2 WHERE project_id=$1 AND run_id=$3", [pid, Date.now(), run.id]).catch(() => {}), 15_000);81 const branch = `agent/${run.id}`; const wt = path.join(dataDir, "worktrees", run.id); let merged = false;82 try {83 if ((await pool.query("SELECT 1 FROM ai_checkpoints WHERE run_id=$1 AND kind='merged'", [run.id])).rowCount) { yield { note: "already merged by an earlier attempt; skipping re-execution" }; return; }84 fs.mkdirSync(workspaceRoot, { recursive: true, mode: 0o700 });85 if (!fs.existsSync(path.join(workspaceRoot, ".git"))) { await git(workspaceRoot, ["init", "-q", "-b", "main"]); }86 if (!(await git(workspaceRoot, ["rev-parse", "--verify", "-q", "HEAD"]).catch(() => ""))) await git(workspaceRoot, ["commit", "-q", "--allow-empty", "-m", "workspace baseline"]);87 if ((await git(workspaceRoot, ["status", "--porcelain"])).trim()) throw Object.assign(new Error("workspace has uncommitted changes; commit them in the editor first (agents only work from committed state)"), { retryable: false });88 await git(workspaceRoot, ["worktree", "prune"]); if (fs.existsSync(wt)) await git(workspaceRoot, ["worktree", "remove", "--force", wt]).catch(() => fs.rmSync(wt, { recursive: true, force: true }));89 await git(workspaceRoot, ["branch", "-D", branch]).catch(() => {}); fs.mkdirSync(path.dirname(wt), { recursive: true });90 await git(workspaceRoot, ["worktree", "add", "-q", "-b", branch, wt]); await checkpoint(run.id, "worktree", `${branch} @ ${wt.split("/").slice(-2).join("/")}`);91 yield* runCli({ prompt, model: ses.model, cwd: wt, engineRef: null, signal }); // new worktree per run => fresh engine session; context comes from the transcript92 if (signal?.aborted) { await checkpoint(run.id, "worktree_discarded", "run cancelled/paused before merge; branch kept for review"); return; }93 await git(wt, ["add", "-A"]); const dirty = (await git(wt, ["status", "--porcelain"])).trim();94 if (!dirty) { yield { note: "agent made no file changes" }; return; }95 await git(wt, ["commit", "-q", "-m", `agent run ${run.id}`]);96 if ((await git(workspaceRoot, ["status", "--porcelain"])).trim()) throw Object.assign(new Error("workspace changed during the run; merge refused (branch kept: " + branch + ")"), { retryable: false });97 try { await git(workspaceRoot, ["merge", "--no-ff", "-q", "-m", `Merge agent run ${run.id}`, branch]); }98 catch (e) { await git(workspaceRoot, ["merge", "--abort"]).catch(() => {}); throw Object.assign(new Error("merge conflict; branch kept for review: " + branch), { retryable: false }); }99 merged = true; await checkpoint(run.id, "merged", `merged ${branch}`); yield { note: `merged ${branch}` };100 } finally {101 clearInterval(beat);102 if (merged) { await git(workspaceRoot, ["worktree", "remove", "--force", wt]).catch(() => {}); await git(workspaceRoot, ["branch", "-D", branch]).catch(() => {}); }103 else if (fs.existsSync(wt)) await git(workspaceRoot, ["worktree", "remove", "--force", wt]).catch(() => {});104 await pool.query("DELETE FROM workspace_locks WHERE project_id=$1 AND run_id=$2", [pid, run.id]).catch(() => {});105 }106}107108/** Idempotent DDL this engine needs (also in src/lib/db.ts SCHEMA); lets the worker start before the web app has migrated. */109export async function ensureSchema(pool) {110 await pool.query("ALTER TABLE ai_sessions ADD COLUMN IF NOT EXISTS engine_ref TEXT; CREATE TABLE IF NOT EXISTS workspace_locks(project_id TEXT PRIMARY KEY, run_id TEXT NOT NULL, locked_at BIGINT NOT NULL)");111}112
Conversation
PartialSign in to start AI sessions.
Task checklist
- Application shell deployed
- Persistent projects
- Agent runtime
- Sandboxed terminal
Execution activity
No agent sessions. Git HEAD 1c27633 on master.
Approval requests
None pending.