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-onlyapp/scripts/worker.mjs
1// Zoo Cloud Studio AI worker: durable, PostgreSQL-backed run executor (separate process from the web app).2// Claim with FOR UPDATE SKIP LOCKED -> lease/heartbeat -> stream -> checkpoint -> commit once. Chat-only: NO tool execution, no shell.3import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import crypto from "node:crypto";4import pg from "pg";5import { AsyncLocalStorage } from "node:async_hooks";6import { ADAPTERS, ProviderError, MAX_OUT } from "./ai-adapters.mjs";7import * as OC from "./opencode-engine.mjs";8const DATA_DIR = process.env.STUDIO_DATA_DIR || path.resolve("data");9pg.types.setTypeParser(20, v => Number(v)); pg.types.setTypeParser(1700, v => Number(v));1011const CFG = path.join(os.homedir(), ".config/zoo-cloud-studio");12const pw = fs.readFileSync(path.join(CFG, "pg-password"), "utf8").trim();13// Runtime role (studio_app): non-owner, no BYPASSRLS. The owner/migration credential is used only for the one-time idempotent DDL at startup.14const appPw = fs.readFileSync(path.join(CFG, "pg-app-password"), "utf8").trim();15const pool = new pg.Pool({ connectionString: process.env.STUDIO_APP_DATABASE_URL || `postgres://studio_app:${encodeURIComponent(appPw)}@127.0.0.1:5432/studio`, max: 6 });16const migrationUrl = process.env.STUDIO_MIGRATE_DATABASE_URL || process.env.STUDIO_DATABASE_URL || `postgres://studio:${encodeURIComponent(pw)}@127.0.0.1:5432/studio`;17// Tenant-scoped execution: every query runs in a transaction carrying app.org_id/app.mode; a run executes inside its OWN organization's scope.18const als = new AsyncLocalStorage();19async function withScope(s, fn) {20 const c = await pool.connect();21 try { await c.query("BEGIN"); if (s?.mode) await c.query("SELECT set_config('app.org_id',$1,true), set_config('app.mode',$2,true)", [s.org ?? "", s.mode]); const r = await fn(c); await c.query("COMMIT"); return r; }22 catch (e) { await c.query("ROLLBACK").catch(() => {}); throw e; } finally { c.release(); }23}24const asSystem = fn => als.run({ mode: "system" }, fn); // explicitly authorized: queue claim/reclaim, heartbeat, audit chain, org lookup25const WORKER = `w-${os.hostname()}-${process.pid}-${crypto.randomBytes(2).toString("hex")}`;26const LEASE_MS = Number(process.env.ZCS_LEASE_MS || 30_000), HEARTBEAT_MS = Math.max(500, LEASE_MS / 6), CONCURRENCY = 2;27const ALLOW_MOCK = process.env.ZCS_ALLOW_MOCK === "1";28const log = (...a) => console.log(new Date().toISOString(), WORKER, ...a);29const q = (t, p) => withScope(als.getStore(), c => c.query(t, p)); const scopedPool = { query: q }; const nowIso = () => new Date().toISOString();30const DEFAULT_PRICING = { "claude-sonnet-5-5": { in: 3, out: 15 }, "claude-opus-5-5": { in: 15, out: 75 }, "claude-haiku-5-5": { in: 1, out: 5 }, "gpt-4o": { in: 2.5, out: 10 }, "gpt-4o-mini": { in: 0.15, out: 0.6 }, "mock-1": { in: 0, out: 0 } };3132const decrypt = r => { const d = crypto.createDecipheriv("aes-256-gcm", Buffer.from(fs.readFileSync(path.join(CFG, "master.key"), "utf8").trim(), "hex"), Buffer.from(r.iv, "base64")); d.setAuthTag(Buffer.from(r.tag, "base64")); return Buffer.concat([d.update(Buffer.from(r.ciphertext, "base64")), d.final()]).toString("utf8"); };33async function setting(k, f) { const r = (await q("SELECT value FROM settings WHERE key=$1", [k])).rows[0]; return r ? r.value : f; }34async function checkpoint(runId, kind, detail = "") { await q("INSERT INTO ai_checkpoints(run_id,seq,kind,detail,created_at) VALUES($1,(SELECT COALESCE(MAX(seq),0)+1 FROM ai_checkpoints WHERE run_id=$1),$2,$3,$4)", [runId, kind, String(detail).slice(0, 500), nowIso()]); }35async function audit(action, resource, detail = {}) { return asSystem(() => auditInner(action, resource, detail)); }36async function auditInner(action, resource, detail = {}) {37 const c = await pool.connect();38 try { await c.query("BEGIN"); await c.query("SELECT set_config('app.mode','system',true)"); await c.query("SELECT pg_advisory_xact_lock(7001)");39 const last = (await c.query("SELECT hash FROM audit_log ORDER BY seq DESC LIMIT 1")).rows[0]; const prev = last?.hash ?? "GENESIS"; const ts = nowIso(); const det = JSON.stringify(detail).slice(0, 2000);40 const hash = crypto.createHash("sha256").update([prev, ts, "ai-worker", action, resource, det].join("|")).digest("hex");41 await c.query("INSERT INTO audit_log(ts,actor,action,resource,detail,prev_hash,hash,org_id) VALUES($1,$2,$3,$4,$5,$6,$7,$8)", [ts, "ai-worker", action, resource, det, prev, hash, detail?.org ?? null]); await c.query("COMMIT");42 } catch (e) { await c.query("ROLLBACK").catch(() => {}); log("audit failed", e.message); } finally { c.release(); }43}4445// ---------- provider adapters (streaming). Each yields {text} chunks and {usage:{in,out}} ----------46// ---------- budgets & pricing ----------47const costOf = (pr, tin, tout) => (tin * pr.in + tout * pr.out) / 1e6;48async function budgetGate(run, ses, pr, inputTokens) {49 const worst = costOf(pr, inputTokens, MAX_OUT);50 const mStart = new Date(Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), 1)).toISOString();51 const month = (await q("SELECT COALESCE(SUM(cost_usd),0) s FROM usage_ledger WHERE ts>=$1", [mStart])).rows[0].s;52 const mcap = Number(await setting("ai.monthly_cap_usd", "5")); if (month + worst > mcap) return `global monthly cap $${mcap} would be exceeded (spent $${month.toFixed(4)}, worst-case call $${worst.toFixed(4)})`;53 const org = (await q("SELECT ai_monthly_cap_usd cap FROM organizations WHERE id=$1", [ses.org_id])).rows[0];54 const om = (await q("SELECT COALESCE(SUM(cost_usd),0) s FROM usage_ledger WHERE ts>=$1 AND org_id=$2", [mStart, ses.org_id])).rows[0].s;55 if (org && om + worst > org.cap) return `organization monthly cap $${org.cap} would be exceeded (spent $${om.toFixed(4)})`;56 if (ses.project_id) { const ps = (await q("SELECT COALESCE(SUM(spent_usd),0) s FROM ai_sessions WHERE project_id=$1", [ses.project_id])).rows[0].s; const pcap = Number(await setting("ai.project_cap_usd", "2")); if (ps + worst > pcap) return `project cap $${pcap} would be exceeded (spent $${ps.toFixed(4)})`; }57 if (ses.spent_usd + worst > ses.budget_usd) return `session budget $${ses.budget_usd} would be exceeded (spent $${ses.spent_usd.toFixed(4)}, worst-case call $${worst.toFixed(4)})`;58 return null;59}6061// ---------- execution ----------62const owned = new Map(); // runId -> AbortController63async function finishRun(run, status, extra = {}) {64 await q("UPDATE ai_runs SET status=$2, locked_by=NULL, locked_at=NULL, updated_at=$3, error=COALESCE($4,error) WHERE id=$1 AND locked_by=$5", [run.id, status, nowIso(), extra.error ?? null, WORKER]);65}66async function execute(run) {67 const ac = new AbortController(); owned.set(run.id, ac);68 try {69 const ses = (await q("SELECT * FROM ai_sessions WHERE id=$1", [run.session_id])).rows[0];70 if (!ses) return finishRun(run, "failed", { error: "session missing" });71 if (ses.provider === "mock" && !ALLOW_MOCK) { await finishRun(run, "failed", { error: "mock provider disabled" }); return; }72 let ocMode = "chat";73 if (ses.provider === "opencode") {74 const why = !OC.installed() ? "OpenCode is not installed" : (await setting("engine.opencode.consent", "0")) !== "1" ? "OpenCode sends prompts and files to an external model service; owner consent has not been recorded (AI Engines page)" : !OC.FREE_MODEL(ses.model) ? "only documented free OpenCode models are enabled; paid models need provider credentials that are not configured" : null;75 if (why) { await checkpoint(run.id, "blocked", why); await finishRun(run, "failed", { error: why }); await q("UPDATE ai_sessions SET status='idle',updated_at=$2 WHERE id=$1", [ses.id, nowIso()]); return; }76 if (ses.project_id && (await setting(`exec.authorized.${ses.project_id}`, "0")) === "1") ocMode = "edit";77 }78 let key = null; if (ses.provider !== "mock" && ses.provider !== "opencode") { const c = (await q("SELECT * FROM credentials WHERE provider=$1 AND org_id=$2", [ses.provider, ses.org_id])).rows[0]; if (!c) { await checkpoint(run.id, "blocked", "awaiting credentials"); await finishRun(run, "failed", { error: `Awaiting credentials: no ${ses.provider} API key configured` }); await q("UPDATE ai_sessions SET status='idle',updated_at=$2 WHERE id=$1", [ses.id, nowIso()]); return; } key = decrypt(c); }79 const history = (await q("SELECT role,content FROM ai_messages WHERE session_id=$1 ORDER BY id", [ses.id])).rows.map(r => ({ role: r.role, content: r.content }));80 const resumed = run.partial.length > 0; const messages = resumed ? [...history, { role: "assistant", content: run.partial }, { role: "user", content: "Continue exactly where you left off. Do not repeat earlier text." }] : history;81 const pr = ses.provider === "opencode" ? { in: 0, out: 0 } : ({ ...DEFAULT_PRICING, ...JSON.parse(await setting("ai.pricing", "{}")) }[ses.model] ?? { in: 15, out: 75 });82 const inTok = Math.ceil(JSON.stringify(messages).length / 4);83 const over = await budgetGate(run, ses, pr, inTok); if (over) { await checkpoint(run.id, "budget_exceeded", over); await audit("ai.run.budget_block", run.id, { over }); await finishRun(run, "failed", { error: `Budget limit: ${over}` }); await q("UPDATE ai_sessions SET status='idle',updated_at=$2 WHERE id=$1", [ses.id, nowIso()]); return; }84 await checkpoint(run.id, resumed ? "resumed_from_partial" : "started", `attempt ${run.attempts}/${run.max_attempts}, ${ses.provider}/${ses.model}${ses.provider === "opencode" ? ` mode=${ocMode}` : ""}`);85 await q("UPDATE ai_sessions SET status='running',updated_at=$2 WHERE id=$1", [ses.id, nowIso()]);86 let text = run.partial, usage = null, lastFlush = 0, stop = null;87 const flush = async force => {88 if (!force && Date.now() - lastFlush < 400) return; lastFlush = Date.now();89 const r = (await q("UPDATE ai_runs SET partial=$2, updated_at=$3, locked_at=$4 WHERE id=$1 AND locked_by=$5 RETURNING cancel_requested", [run.id, text, nowIso(), Date.now(), WORKER])).rows[0];90 if (!r) { stop = "lease_lost"; ac.abort(); } else if (r.cancel_requested && !stop) { stop = r.cancel_requested === 2 ? "paused" : "cancelled"; ac.abort(); }91 };92 try {93 const gen = ses.provider === "opencode"94 ? OC.runOpenCode({ ses, run, pool: scopedPool, checkpoint, signal: ac.signal, mode: ocMode, workspaceRoot: ses.project_id ? path.join(DATA_DIR, "workspaces", ses.project_id) : null, dataDir: DATA_DIR,95 prompt: ocMode === "chat" && ses.engine_ref ? messages[messages.length - 1].content : messages.map(m => `${m.role.toUpperCase()}: ${m.content}`).join("\n\n") })96 : ADAPTERS[ses.provider]({ key, model: ses.model, messages, signal: ac.signal, attempt: run.attempts, baseUrl: process.env[`ZCS_${ses.provider.toUpperCase()}_BASE_URL`] });97 for await (const ev of gen) {98 if (ev.engineSession && ocMode === "chat" && ev.engineSession !== ses.engine_ref) { ses.engine_ref = ev.engineSession; await q("UPDATE ai_sessions SET engine_ref=$2 WHERE id=$1", [ses.id, ev.engineSession]); await checkpoint(run.id, "engine_session", ev.engineSession); }99 if (ev.note) await checkpoint(run.id, "engine_event", ev.note);100 if (ev.error) throw new ProviderError(ev.error, { retryable: false });101 if (ev.text) { text += ev.text; await flush(false); }102 if (ev.usage) usage = ev.partialUsage ? { in: (usage?.in ?? 0) + ev.usage.in, out: (usage?.out ?? 0) + ev.usage.out, cost: (usage?.cost ?? 0) + (ev.usage.cost ?? 0) } : ev.usage;103 if (stop) break;104 }105 } catch (e) { if (!stop) throw e; }106 await flush(true);107 const tin = usage?.in ?? inTok, tout = usage?.out ?? Math.ceil((text.length - run.partial.length) / 4), cost = ses.provider === "opencode" ? Number(usage?.cost ?? 0) : costOf(pr, tin, tout);108 const tx = async fn => withScope(als.getStore(), fn); const _txOld = async fn => { const c = await pool.connect(); try { await c.query("BEGIN"); const r = await fn(c); await c.query("COMMIT"); return r; } catch (e) { await c.query("ROLLBACK").catch(() => {}); throw e; } finally { c.release(); } };109 const commit = async (status, kind, saveMessage) => tx(async c => {110 // single guarded commit: only the lease holder may finalise, so a reclaimed run can never double-bill or double-write111 const g = await c.query("UPDATE ai_runs SET status=$2, partial=$3, tokens_in=tokens_in+$4, tokens_out=tokens_out+$5, cost_usd=cost_usd+$6, locked_by=NULL, locked_at=NULL, updated_at=$7 WHERE id=$1 AND locked_by=$8 AND status='running' RETURNING id", [run.id, status, text, tin, tout, cost, nowIso(), WORKER]);112 if (!g.rowCount) return false;113 await c.query("INSERT INTO usage_ledger(ts,session_id,run_id,provider,model,tokens_in,tokens_out,cost_usd,org_id) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)", [nowIso(), ses.id, run.id, ses.provider, ses.model, tin, tout, cost, ses.org_id]);114 if (saveMessage && text) await c.query("INSERT INTO ai_messages(session_id,role,content,run_id,created_at) VALUES($1,'assistant',$2,$3,$4)", [ses.id, text, run.id, nowIso()]);115 await c.query("UPDATE ai_sessions SET status=$2, spent_usd=spent_usd+$3, updated_at=$4 WHERE id=$1", [ses.id, status === "paused" ? "paused" : "idle", cost, nowIso()]);116 await c.query("INSERT INTO ai_checkpoints(run_id,seq,kind,detail,created_at) VALUES($1,(SELECT COALESCE(MAX(seq),0)+1 FROM ai_checkpoints WHERE run_id=$1),$2,$3,$4)", [run.id, kind, `tokens ${tin}/${tout} cost $${cost.toFixed(6)} (estimate)`, nowIso()]); return true;117 });118 if (stop === "lease_lost") { log("lease lost for", run.id); return; }119 if (stop === "paused") { if (await commit("paused", "paused", false)) { await audit("ai.run.paused", run.id); log("paused", run.id); } return; }120 if (stop === "cancelled") { if (await commit("cancelled", "cancelled", true)) { await audit("ai.run.cancelled", run.id); log("cancelled", run.id); } return; }121 if (await commit("succeeded", "completed", true)) { await audit("ai.run.completed", run.id, { tokens_in: tin, tokens_out: tout, cost_usd: cost }); log("completed", run.id, `$${cost.toFixed(6)}`); }122 } catch (e) {123 const retryable = e.retryable ?? true; const give = !e.waitOnly && (!retryable || run.attempts >= run.max_attempts);124 const wait = e.retryAfterMs ?? Math.min(60_000, 1000 * 2 ** run.attempts);125 const text0 = (await q("SELECT partial FROM ai_runs WHERE id=$1", [run.id])).rows[0]?.partial;126 if (give && !/Budget limit|consent|not installed|uncommitted|merge/.test(String(e.message)) && await tryHandoff(run, e)) return;127 if (give) { await checkpoint(run.id, "failed", e.message); await finishRun(run, "failed", { error: String(e.message).slice(0, 400) }); await q("UPDATE ai_sessions SET status='idle',updated_at=$2 WHERE id=$1", [run.session_id, nowIso()]); await audit("ai.run.failed", run.id, { error: String(e.message).slice(0, 200), attempts: run.attempts }); log("failed", run.id, e.message); }128 else { await q("UPDATE ai_runs SET attempts=attempts-$6, status='queued', locked_by=NULL, locked_at=NULL, run_after=$2, error=$3, updated_at=$4 WHERE id=$1 AND locked_by=$5", [run.id, Date.now() + wait, String(e.message).slice(0, 400), nowIso(), WORKER, e.waitOnly ? 1 : 0]); await checkpoint(run.id, "retry_scheduled", `attempt ${run.attempts}/${run.max_attempts}; retry in ${wait}ms; ${e.message}`.slice(0, 400)); log("retry", run.id, wait + "ms", `kept ${text0?.length ?? 0} chars`); }129 } finally { owned.delete(run.id); }130}131132// Authorized fallback: only when the owner enabled it. Completed work lives in ai_messages/checkpoints (engine-independent), so the next engine continues instead of restarting.133async function tryHandoff(run, e) {134 if ((await setting("ai.fallback_enabled", "0")) !== "1") return false;135 const ses = (await q("SELECT * FROM ai_sessions WHERE id=$1", [run.session_id])).rows[0]; if (!ses) return false;136 if ((await q("SELECT COUNT(*)::int n FROM ai_checkpoints WHERE run_id=$1 AND kind='handoff'", [run.id])).rows[0].n >= 1) return false;137 let order; try { order = JSON.parse(await setting("ai.fallback_order", '["opencode","anthropic","openai"]')); } catch { order = []; }138 const MODEL = { opencode: "opencode/big-pickle", anthropic: "claude-haiku-5-5", openai: "gpt-4o-mini", mock: "mock-1" };139 for (const eng of order) {140 if (eng === ses.provider || !MODEL[eng]) continue;141 const ok = eng === "opencode" ? OC.installed() && (await setting("engine.opencode.consent", "0")) === "1" : eng === "mock" ? ALLOW_MOCK : (await q("SELECT 1 FROM credentials WHERE provider=$1 AND org_id=$2", [eng, ses.org_id])).rowCount > 0;142 if (!ok) continue;143 const from = `${ses.provider}/${ses.model}`; await q("UPDATE ai_sessions SET provider=$2, model=$3, updated_at=$4 WHERE id=$1", [ses.id, eng, MODEL[eng], nowIso()]);144 await q("UPDATE ai_runs SET status='queued', attempts=0, locked_by=NULL, locked_at=NULL, run_after=0, error=$2, updated_at=$3 WHERE id=$1 AND locked_by=$4", [run.id, String(e.message).slice(0, 300), nowIso(), WORKER]);145 await checkpoint(run.id, "handoff", `${from} failed (${String(e.message).slice(0, 120)}); authorized fallback -> ${eng}/${MODEL[eng]}; session history and partial output carried over`);146 await audit("ai.run.handoff", run.id, { from, to: `${eng}/${MODEL[eng]}` }); log("handoff", run.id, from, "->", eng); return true;147 }148 return false;149}150async function claim() { return asSystem(claimInner); }151async function claimInner() {152 const r = await q(`UPDATE ai_runs SET status='running', locked_by=$1, locked_at=$2, attempts=attempts+1, updated_at=$3 WHERE id=(153 SELECT id FROM ai_runs WHERE status='queued' AND run_after<=$2 ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED) RETURNING *`, [WORKER, Date.now(), nowIso()]);154 return r.rows[0];155}156async function heartbeatAndReclaim() { return asSystem(hbInner); }157async function hbInner() {158 await q("INSERT INTO settings(key,value) VALUES('worker.heartbeat',$1) ON CONFLICT(key) DO UPDATE SET value=excluded.value", [String(Date.now())]).catch(() => {});159 if (owned.size) await q("UPDATE ai_runs SET locked_at=$2 WHERE locked_by=$1 AND status='running'", [WORKER, Date.now()]);160 // Crash recovery: a run whose lease expired belongs to a dead worker. Re-queue (bounded by max_attempts); the partial text is kept as the continuation point.161 const stale = (await q("SELECT id,attempts,max_attempts,session_id,locked_by FROM ai_runs WHERE status='running' AND locked_at < $1 FOR UPDATE SKIP LOCKED", [Date.now() - LEASE_MS])).rows;162 for (const s of stale) {163 if (s.locked_by === WORKER && owned.has(s.id)) continue;164 if (s.attempts >= s.max_attempts) { await q("UPDATE ai_runs SET status='failed', error='lease expired; attempts exhausted', locked_by=NULL, locked_at=NULL, updated_at=$2 WHERE id=$1 AND status='running'", [s.id, nowIso()]); await q("UPDATE ai_sessions SET status='idle' WHERE id=$1", [s.session_id]); await checkpoint(s.id, "failed", "lease expired; attempts exhausted"); }165 else { await q("UPDATE ai_runs SET status='queued', locked_by=NULL, locked_at=NULL, run_after=0, updated_at=$2 WHERE id=$1 AND status='running'", [s.id, nowIso()]); await checkpoint(s.id, "reclaimed", `lease expired (was ${s.locked_by}); re-queued`); await audit("ai.run.reclaimed", s.id, { from: s.locked_by }); log("reclaimed", s.id); }166 }167}168169let stopping = false; for (const sig of ["SIGTERM", "SIGINT"]) process.on(sig, () => { stopping = true; log("signal", sig); setTimeout(() => process.exit(0), 1500); });170{ const mp = new pg.Pool({ connectionString: migrationUrl, max: 1 }); await OC.ensureSchema(mp); await mp.end(); }171log("worker started", { lease_ms: LEASE_MS, mock: ALLOW_MOCK });172setInterval(() => heartbeatAndReclaim().catch(e => log("hb error", e.message)), HEARTBEAT_MS);173while (!stopping) {174 try { if (owned.size < CONCURRENCY) { const r = await claim(); if (r) { const org = (await asSystem(() => q("SELECT org_id FROM ai_sessions WHERE id=$1", [r.session_id]))).rows[0]?.org_id; if (!org) { await asSystem(() => q("UPDATE ai_runs SET status='failed', error='session missing', locked_by=NULL WHERE id=$1", [r.id])); continue; } void als.run({ mode: "tenant", org }, () => execute(r)); continue; } } } catch (e) { log("loop error", e.message); }175 await new Promise(r => setTimeout(r, 400));176}177
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.