Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : server/services/research/runtime.ts9 * Module : server10 * Repository : https://git.spboucher.ai/vquant11 * Project Website : https://vquant.spboucher.ai12 * Created : 2026-11-2013 * Last Modified : 2026-11-2014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier : MIT34 * License : MIT License35 * License File : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * Research runtime (contract: docs/next/CONTRACT.md §9.1, §9.5, §9.7): script runs, dataset inspection and approvals.47 *48 * A run is a Python program of the workspace executed in the sandbox by vq_sandbox_boot.py in "supervise" mode:49 * its output goes to runs/<id>/stdout.log and stderr.log and its exit to runs/<id>/status.json. The server only50 * watches those files, so a run does not depend on the request, the generation or even the server process that51 * started it: after a restart `adoptRuns()` finds every run again — finished (its status file is there), still52 * running (re-attached to the watchdog) or lost (marked `interrupted`, with its logs kept).53 *54 * Every run is written to the experiment ledger as an execution, with the hash of its code and of the environment,55 * whatever its outcome.56 */57import type Database from "better-sqlite3";58import { EventEmitter } from "node:events";59import { randomUUID } from "node:crypto";60import fs from "node:fs";61import path from "node:path";62import { isSqlite, pool } from "../../db";63import { logger } from "../../utils/logger";64import { pythonPath, redactSecrets } from "../python/lab";65import { brokerUrl, ensureBroker, issueToken, revokeToken } from "./broker";66import { adoptProcess, defaultLimits, pythonScriptsDir, releaseProcess, spawnSandboxed, type SandboxLimits, type Sandboxed } from "./sandbox";67import { ResearchError, addExperiment, appendExecutionLog, getWorkspace, libraryDir, resolveInside, sha256, touchWorkspace, updateExperiment, type Workspace } from "./store";6869type Db = Database.Database;70const db = (): Db => {71 if (!isSqlite) throw new Error("Research runs need the SQLite database");72 return pool as Db;73};7475/** What a sandboxed process of this workspace is started with (broker access and import roots). Revoke the token when it ends. */76export async function sandboxAccess(ws: Workspace, network: "default" | "open", label: string): Promise<{ brokerUrl: string; brokerPort: number; brokerToken: string; libraryDirs: string[] }> {77 const port = await ensureBroker();78 return { brokerUrl: brokerUrl(port), brokerPort: port, brokerToken: issueToken({ owner: ws.owner, workspace: ws.dir, network, label }), libraryDirs: [libraryDir(ws.owner)] };79}8081// ─── Runs ────────────────────────────────────────────────────────────────────82export type RunStatus = "running" | "done" | "failed" | "timeout" | "killed" | "cancelled" | "interrupted";83export interface Run {84 id: string;85 workspaceId: string;86 sessionId: string | null;87 generationId: string | null;88 label: string | null;89 codeRef: string;90 codeHash: string | null;91 args: string[];92 network: "default" | "open";93 status: RunStatus;94 pid: number | null;95 progress: number | null;96 exitCode: number | null;97 error: string | null;98 startedAt: number;99 finishedAt: number | null;100}101const toRun = (r: any): Run => ({102 id: r.id, workspaceId: r.workspace_id, sessionId: r.session_id, generationId: r.generation_id, label: r.label, codeRef: r.code_ref, codeHash: r.code_hash, args: r.args ? JSON.parse(r.args) : [],103 network: r.network, status: r.status, pid: r.pid, progress: r.progress, exitCode: r.exit_code, error: r.error, startedAt: r.started_at, finishedAt: r.finished_at,104});105106/** `run` events: { owner, run } each time a run changes state or reports progress. */107export const runEvents = new EventEmitter();108runEvents.setMaxListeners(200);109110const MAX_RUNNING_PER_OWNER = Number(process.env.VQ_RESEARCH_MAX_RUNS) > 0 ? Number(process.env.VQ_RESEARCH_MAX_RUNS) : 6;111const DEFAULT_WALL_S = 2 * 3600;112const MAX_WALL_S = Number(process.env.VQ_RESEARCH_MAX_WALL_SECONDS) > 0 ? Number(process.env.VQ_RESEARCH_MAX_WALL_SECONDS) : 12 * 3600;113114interface Live {115 run: Run;116 owner: string;117 ws: Workspace;118 token: string | null;119 kill: (reason?: string) => void;120 killedFor: string | null;121 cancelled: boolean;122 poll: NodeJS.Timeout;123 experimentId: string | null;124 done: Promise<Run>;125 resolve: (r: Run) => void;126 errOffset: number;127}128const live = new Map<string, Live>();129130export function getRun(owner: string, id: string): Run | null {131 const r = db().prepare("SELECT * FROM vq_research_runs WHERE id = ? AND owner = ?").get(id, owner);132 return r ? toRun(r) : null;133}134export function listRuns(owner: string, workspaceId: string, limit = 200): Run[] {135 return (db().prepare("SELECT * FROM vq_research_runs WHERE owner = ? AND workspace_id = ? ORDER BY started_at DESC LIMIT ?").all(owner, workspaceId, limit) as any[]).map(toRun);136}137export function runningRuns(owner: string): number {138 return (db().prepare("SELECT count(*) AS n FROM vq_research_runs WHERE owner = ? AND status = 'running'").get(owner) as { n: number }).n;139}140141const runDir = (ws: Workspace, id: string) => path.join(ws.dir, "runs", id);142143/** The last `maxBytes` of a run's log, with anything that looks like a secret masked. */144export function tailLog(ws: Workspace, runId: string, stream: "stdout" | "stderr", maxBytes = 12_000): string {145 if (!/^[a-f0-9-]{8,40}$/.test(runId)) throw new ResearchError("Invalid run id");146 const file = path.join(runDir(ws, runId), `${stream}.log`);147 try {148 const size = fs.statSync(file).size;149 const fd = fs.openSync(file, "r");150 const len = Math.min(size, maxBytes);151 const buf = Buffer.alloc(len);152 fs.readSync(fd, buf, 0, len, size - len);153 fs.closeSync(fd);154 const text = buf.toString("utf8");155 return redactSecrets(stream === "stderr" ? text.split("\n").filter((l) => !/^@@progress\s/.test(l)).join("\n") : text);156 } catch {157 return "";158 }159}160161function readStatus(ws: Workspace, runId: string): { exitCode: number | null; signal: number | null; finishedAt: number; error?: string } | null {162 try {163 return JSON.parse(fs.readFileSync(path.join(runDir(ws, runId), "status.json"), "utf8"));164 } catch {165 return null;166 }167}168169function readProgress(l: Live): void {170 try {171 const file = path.join(runDir(l.ws, l.run.id), "stderr.log");172 const size = fs.statSync(file).size;173 if (size <= l.errOffset) return;174 const fd = fs.openSync(file, "r");175 const buf = Buffer.alloc(Math.min(size - l.errOffset, 64 * 1024));176 fs.readSync(fd, buf, 0, buf.length, size - buf.length);177 fs.closeSync(fd);178 l.errOffset = size;179 const all = [...buf.toString("utf8").matchAll(/^@@progress\s+([0-9]*\.?[0-9]+)\s*$/gm)];180 if (all.length === 0) return;181 const f = Math.min(1, Math.max(0, Number(all[all.length - 1][1])));182 if (Number.isFinite(f) && f !== l.run.progress) {183 l.run.progress = f;184 db().prepare("UPDATE vq_research_runs SET progress = ? WHERE id = ?").run(f, l.run.id);185 runEvents.emit("run", { owner: l.owner, run: l.run });186 }187 } catch {188 /* no stderr yet */189 }190}191192function finalize(l: Live, st: { exitCode: number | null; signal: number | null; finishedAt?: number; error?: string } | null): void {193 if (!live.has(l.run.id)) return;194 live.delete(l.run.id);195 clearInterval(l.poll);196 revokeToken(l.token);197 if (l.run.pid) releaseProcess(l.run.pid);198 const exitCode = st?.exitCode ?? null;199 let status: RunStatus;200 let error: string | null = null;201 if (l.cancelled) (status = "cancelled"), (error = "Cancelled.");202 else if (l.killedFor) (status = /time limit/.test(l.killedFor) ? "timeout" : "killed"), (error = `Stopped by the sandbox: ${l.killedFor}.`);203 else if (!st) (status = "killed"), (error = "The process ended without reporting its exit (killed from outside the run).");204 else if (exitCode === 0) status = "done";205 else {206 status = "failed";207 // SIGXCPU = the CPU-time rlimit; SIGXFSZ = the file-size rlimit.208 error = st.signal === 24 ? "Stopped by the sandbox: CPU time limit." : st.signal === 25 ? "Stopped by the sandbox: file size limit." : st.signal ? `Killed by signal ${st.signal}.` : `Exit code ${exitCode}. ${tailLog(l.ws, l.run.id, "stderr", 1500).trim().split("\n").slice(-6).join("\n")}`;209 if (st.signal === 24) status = "timeout";210 }211 const finishedAt = Date.now();212 db().prepare("UPDATE vq_research_runs SET status = ?, exit_code = ?, error = ?, finished_at = ?, progress = CASE WHEN ? = 'done' THEN 1.0 ELSE progress END WHERE id = ?").run(status, exitCode, error ? redactSecrets(error).slice(0, 2000) : null, finishedAt, status, l.run.id);213 const run = getRunById(l.run.id)!;214 if (l.experimentId) {215 try {216 updateExperiment(l.owner, l.experimentId, { status: status === "done" ? "ok" : status === "timeout" ? "timeout" : status === "cancelled" ? "abandoned" : status === "killed" ? "killed" : "failed", error: run.error, finishedAt, durationMs: finishedAt - run.startedAt });217 } catch {218 /* the run row still tells the outcome */219 }220 }221 appendExecutionLog(l.ws, { type: "run", runId: run.id, code: run.codeRef, codeHash: run.codeHash, status, exitCode, durationMs: finishedAt - run.startedAt, error: run.error });222 touchWorkspace(l.owner, l.ws.id);223 logger.info(`[research] run ${run.id} ${status} after ${Math.round((finishedAt - run.startedAt) / 1000)} s`);224 runEvents.emit("run", { owner: l.owner, run });225 l.resolve(run);226}227228const getRunById = (id: string): Run | null => {229 const r = db().prepare("SELECT * FROM vq_research_runs WHERE id = ?").get(id);230 return r ? toRun(r) : null;231};232233function track(owner: string, ws: Workspace, run: Run, token: string | null, kill: (reason?: string) => void, experimentId: string | null, exited?: Promise<void>): Live {234 let resolve: (r: Run) => void = () => undefined;235 const done = new Promise<Run>((r) => (resolve = r));236 const l: Live = { run, owner, ws, token, kill, killedFor: null, cancelled: false, experimentId, done, resolve, errOffset: 0, poll: setInterval(() => check(l), 1000) };237 l.poll.unref();238 live.set(run.id, l);239 // When the server itself spawned the process, its exit is known at once; the status file follows within moments.240 void exited?.then(() => setTimeout(() => finalize(l, readStatus(ws, run.id)), 150));241 return l;242}243244function check(l: Live): void {245 readProgress(l);246 const st = readStatus(l.ws, l.run.id);247 if (st) return finalize(l, st);248 if (l.run.pid) {249 try {250 process.kill(l.run.pid, 0);251 } catch {252 finalize(l, null); // gone without a status file253 }254 }255}256257export interface StartRun {258 ws: Workspace;259 /** a Python file of the workspace… */260 path?: string;261 /** …or code to run (saved under code/_runs/ first, so every run has a file) */262 code?: string;263 args?: string[];264 label?: string;265 timeoutSeconds?: number;266 network?: "default" | "open";267 sessionId?: string | null;268 generationId?: string | null;269 limits?: Partial<SandboxLimits>;270}271272/** Starts a run and returns at once; `waitRun` waits for its end. */273export async function startRun(o: StartRun): Promise<Run> {274 const { ws } = o;275 if (runningRuns(ws.owner) >= MAX_RUNNING_PER_OWNER) throw new ResearchError(`${MAX_RUNNING_PER_OWNER} runs are already in progress: wait for one (research_runs wait) or cancel one.`, 429);276 const id = randomUUID();277 let rel = o.path?.trim();278 if (!rel) {279 if (!o.code?.trim()) throw new ResearchError("research_run needs `path` (a Python file of the workspace) or `code`.");280 rel = `code/_runs/${new Date().toISOString().slice(0, 19).replace(/[-:T]/g, "")}_${id.slice(0, 8)}.py`;281 const target = resolveInside(ws.dir, rel);282 fs.mkdirSync(path.dirname(target), { recursive: true });283 fs.writeFileSync(target, o.code);284 }285 const script = resolveInside(ws.dir, rel, { userVisible: true });286 if (!fs.existsSync(script) || !fs.statSync(script).isFile()) throw new ResearchError(`No such file in the workspace: ${rel}`, 404);287 if (!/\.py$/i.test(script)) throw new ResearchError("Only Python programs (.py) can be run.");288 const args = (o.args ?? []).map((a) => String(a)).slice(0, 64);289 if (args.some((a) => a.length > 4000)) throw new ResearchError("An argument is too long.");290 const wall = Math.min(MAX_WALL_S, Math.max(5, Math.floor(o.timeoutSeconds ?? DEFAULT_WALL_S)));291 const limits: SandboxLimits = { ...defaultLimits(), ...(o.limits ?? {}), wallMs: wall * 1000 };292 const network = o.network === "open" ? "open" : "default";293 const codeHash = sha256(fs.readFileSync(script)).slice(0, 16);294 const dir = runDir(ws, id);295 fs.mkdirSync(dir, { recursive: true });296 fs.writeFileSync(path.join(dir, "run.json"), JSON.stringify({ id, code: rel, codeHash, args, network, limits, startedAt: Date.now(), label: o.label ?? null }, null, 2));297298 const access = await sandboxAccess(ws, network, `run:${id.slice(0, 8)}`);299 let sandboxed: Sandboxed;300 try {301 sandboxed = await spawnSandboxed({ argv: [pythonPath(), "-u", script, ...args], workspace: ws.dir, ...access, limits, mode: "supervise", runDir: dir, stdio: "ignore", env: { VQ_RUN_ID: id, VQ_RUN_DIR: dir } });302 } catch (e) {303 revokeToken(access.brokerToken);304 throw e;305 }306 // The run must be able to outlive this server process.307 sandboxed.child.unref();308 const startedAt = Date.now();309 db().prepare("INSERT INTO vq_research_runs (id, owner, workspace_id, session_id, generation_id, label, code_ref, code_hash, args, network, status, pid, limits, started_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', ?, ?, ?)")310 .run(id, ws.owner, ws.id, o.sessionId ?? null, o.generationId ?? null, o.label?.slice(0, 160) ?? null, rel, codeHash, JSON.stringify(args), network, sandboxed.child.pid ?? null, JSON.stringify(limits), startedAt);311 const experiment = addExperiment(ws, { kind: "execution", sessionId: o.sessionId, generationId: o.generationId, title: o.label ?? rel, codeRef: rel, codeHash, runId: id, status: "running", startedAt });312 const run = getRunById(id)!;313 const exited = new Promise<void>((r) => sandboxed.child.once("exit", () => r()));314 const l = track(ws.owner, ws, run, access.brokerToken, (why) => sandboxed.kill(why), experiment.id, exited);315 void exited.then(() => {316 const why = sandboxed.killedFor();317 if (why) l.killedFor = why;318 });319 // The watchdog reports why it killed through the sandbox handle.320 const reasonPoll = setInterval(() => {321 const why = sandboxed.killedFor();322 if (why) l.killedFor = why;323 if (!live.has(id)) clearInterval(reasonPoll);324 }, 500);325 reasonPoll.unref();326 logger.info(`[research] run ${id} started owner=${ws.owner} workspace=${ws.id} code=${rel} network=${network}`);327 // The start is announced by whoever started the run (it holds the stream); progress and the end come from here.328 return run;329}330331/** Waits until the run has ended or `timeoutMs` has passed; returns its current state either way. */332export async function waitRun(owner: string, id: string, timeoutMs: number, signal?: AbortSignal): Promise<Run> {333 const l = live.get(id);334 if (!l || l.owner !== owner) {335 const r = getRun(owner, id);336 if (!r) throw new ResearchError(`No run ${id}.`, 404);337 return r;338 }339 await Promise.race([l.done, new Promise((r) => setTimeout(r, Math.max(0, timeoutMs))), new Promise((r) => signal?.addEventListener("abort", r, { once: true }))]);340 return getRun(owner, id)!;341}342343export function cancelRun(owner: string, id: string): Run {344 const l = live.get(id);345 const r = getRun(owner, id);346 if (!r) throw new ResearchError(`No run ${id}.`, 404);347 if (!l || l.owner !== owner || r.status !== "running") return r;348 l.cancelled = true;349 l.kill();350 setTimeout(() => finalize(l, readStatus(l.ws, id)), 400);351 return { ...r, status: "cancelled" };352}353354/**355 * After a restart: every run recorded as running is looked up again. Finished meanwhile → its outcome is recorded;356 * still alive → watched again (limits included); gone → `interrupted` (the files it wrote and its logs remain, and357 * the agent can start it again).358 */359export function adoptRuns(): { adopted: number; finished: number; interrupted: number } {360 const out = { adopted: 0, finished: 0, interrupted: 0 };361 const rows = db().prepare("SELECT * FROM vq_research_runs WHERE status = 'running'").all() as any[];362 for (const row of rows) {363 const run = toRun(row);364 if (live.has(run.id)) continue;365 const ws = getWorkspace(row.owner, run.workspaceId);366 if (!ws) continue;367 const experiment = db().prepare("SELECT id FROM vq_experiments WHERE run_id = ? AND owner = ?").get(run.id, row.owner) as { id: string } | undefined;368 const st = readStatus(ws, run.id);369 let alive = false;370 if (!st && run.pid) {371 try {372 process.kill(run.pid, 0);373 alive = true;374 } catch {375 alive = false;376 }377 }378 if (st) {379 const l = track(row.owner, ws, run, null, () => undefined, experiment?.id ?? null);380 finalize(l, st);381 out.finished++;382 } else if (alive && run.pid) {383 const limits: SandboxLimits = { ...defaultLimits(), ...(row.limits ? JSON.parse(row.limits) : {}) };384 const l = track(row.owner, ws, run, null, () => undefined, experiment?.id ?? null);385 const handle = adoptProcess(run.pid, ws.dir, limits, run.startedAt, (why) => (l.killedFor = why));386 l.kill = (why) => handle.kill(why);387 out.adopted++;388 } else {389 db().prepare("UPDATE vq_research_runs SET status = 'interrupted', finished_at = ?, error = 'The server restarted and this run was no longer running afterwards. Its files and logs are kept; start it again to resume.' WHERE id = ?").run(Date.now(), run.id);390 if (experiment) {391 try {392 updateExperiment(row.owner, experiment.id, { status: "interrupted", error: "Interrupted by a server restart." });393 } catch {394 /* best effort */395 }396 }397 out.interrupted++;398 }399 }400 if (rows.length) logger.info(`[research] runs after restart: ${out.adopted} re-attached, ${out.finished} finished meanwhile, ${out.interrupted} interrupted`);401 return out;402}403404// ─── One-shot sandboxed helper (dataset inspection) ──────────────────────────405/** Runs a helper script of the app in the sandbox of a workspace and returns its stdout. */406export async function runHelper(ws: Workspace, script: string, args: string[], timeoutMs = 120_000): Promise<{ stdout: string; stderr: string; exitCode: number | null; killedFor: string | null }> {407 const access = await sandboxAccess(ws, "default", `helper:${script}`);408 try {409 const s = await spawnSandboxed({ argv: [pythonPath(), "-u", path.join(pythonScriptsDir(), script), ...args], workspace: ws.dir, ...access, limits: { wallMs: timeoutMs, memoryMb: 4096 }, stdio: ["ignore", "pipe", "pipe"] });410 const out: Buffer[] = [];411 const err: Buffer[] = [];412 let size = 0;413 s.child.stdout!.on("data", (c: Buffer) => ((size += c.length) < 16 * 1024 * 1024 ? out.push(c) : s.kill("output too large")));414 s.child.stderr!.on("data", (c: Buffer) => err.length < 200 && err.push(c));415 const exitCode = await new Promise<number | null>((r) => s.child.once("exit", (code) => r(code)));416 return { stdout: Buffer.concat(out).toString("utf8"), stderr: redactSecrets(Buffer.concat(err).toString("utf8").slice(-3000)), exitCode, killedFor: s.killedFor() };417 } finally {418 revokeToken(access.brokerToken);419 }420}421422/** Schema, dtypes, missingness and head of a dataset of the workspace. */423export async function inspectDataset(ws: Workspace, rel: string): Promise<Record<string, unknown>> {424 const target = resolveInside(ws.dir, rel, { userVisible: true });425 if (!fs.existsSync(target) || !fs.statSync(target).isFile()) throw new ResearchError(`No such file in the workspace: ${rel}`, 404);426 const r = await runHelper(ws, "vq_inspect.py", [target]);427 const line = r.stdout.trim().split("\n").pop() ?? "";428 try {429 const parsed = JSON.parse(line);430 if (parsed.error) throw new ResearchError(`The dataset could not be read: ${parsed.error}`);431 return { ...parsed, path: rel };432 } catch (e) {433 if (e instanceof ResearchError) throw e;434 throw new ResearchError(`The dataset could not be inspected${r.killedFor ? ` (${r.killedFor})` : ""}: ${r.stderr.slice(-600) || "no output"}`);435 }436}437438// ─── Approvals ───────────────────────────────────────────────────────────────439export const APPROVAL_ACTIONS = ["open_network", "send_data", "raise_budget", "other"] as const;440export type ApprovalAction = (typeof APPROVAL_ACTIONS)[number];441export interface Approval {442 id: string;443 workspaceId: string | null;444 sessionId: string | null;445 generationId: string | null;446 action: ApprovalAction;447 reason: string | null;448 detail: Record<string, unknown> | null;449 status: "pending" | "approved" | "denied" | "expired";450 createdAt: number;451 resolvedAt: number | null;452}453const toApproval = (r: any): Approval => ({ id: r.id, workspaceId: r.workspace_id, sessionId: r.session_id, generationId: r.generation_id, action: r.action, reason: r.reason, detail: r.detail ? JSON.parse(r.detail) : null, status: r.status, createdAt: r.created_at, resolvedAt: r.resolved_at });454const waiters = new Map<string, (a: Approval) => void>();455export const approvalEvents = new EventEmitter();456approvalEvents.setMaxListeners(200);457const APPROVAL_WAIT_MS = Number(process.env.VQ_RESEARCH_APPROVAL_WAIT_SECONDS) > 0 ? Number(process.env.VQ_RESEARCH_APPROVAL_WAIT_SECONDS) * 1000 : 15 * 60_000;458459export function listApprovals(owner: string, opts: { status?: string; workspaceId?: string } = {}): Approval[] {460 const where = ["owner = ?"];461 const args: unknown[] = [owner];462 if (opts.status) (where.push("status = ?"), args.push(opts.status));463 if (opts.workspaceId) (where.push("workspace_id = ?"), args.push(opts.workspaceId));464 return (db().prepare(`SELECT * FROM vq_research_approvals WHERE ${where.join(" AND ")} ORDER BY created_at DESC LIMIT 100`).all(...args) as any[]).map(toApproval);465}466467/**468 * Asks the person for an explicit authorization and waits for the answer (POST /api/v2/research/approvals/:id).469 * No answer within the waiting time counts as a refusal. `onCreated` receives the pending request (to emit the event).470 */471export async function requestApproval(owner: string, o: { workspaceId?: string | null; sessionId?: string | null; generationId?: string | null; action: ApprovalAction; reason: string; detail?: Record<string, unknown>; waitMs?: number; signal?: AbortSignal }, onCreated?: (a: Approval) => void): Promise<Approval> {472 const id = randomUUID();473 db().prepare("INSERT INTO vq_research_approvals (id, owner, workspace_id, session_id, generation_id, action, reason, detail, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?)")474 .run(id, owner, o.workspaceId ?? null, o.sessionId ?? null, o.generationId ?? null, o.action, String(o.reason ?? "").slice(0, 1000), o.detail ? JSON.stringify(o.detail).slice(0, 4000) : null, Date.now());475 const pending = toApproval(db().prepare("SELECT * FROM vq_research_approvals WHERE id = ?").get(id));476 onCreated?.(pending);477 approvalEvents.emit("approval", { owner, approval: pending });478 const answered = await new Promise<Approval | null>((resolve) => {479 const timer = setTimeout(() => resolve(null), o.waitMs ?? APPROVAL_WAIT_MS);480 timer.unref();481 waiters.set(id, (a) => {482 clearTimeout(timer);483 resolve(a);484 });485 o.signal?.addEventListener("abort", () => resolve(null), { once: true });486 });487 waiters.delete(id);488 if (answered) return answered;489 db().prepare("UPDATE vq_research_approvals SET status = 'expired', resolved_at = ? WHERE id = ? AND status = 'pending'").run(Date.now(), id);490 const final = toApproval(db().prepare("SELECT * FROM vq_research_approvals WHERE id = ?").get(id));491 approvalEvents.emit("approval", { owner, approval: final });492 return final;493}494495/** The person's answer. Returns null when the request is not theirs or is no longer pending. */496export function resolveApproval(owner: string, id: string, decision: "approve" | "deny", device: string | null): Approval | null {497 const done = db().prepare("UPDATE vq_research_approvals SET status = ?, resolved_at = ?, device = ? WHERE id = ? AND owner = ? AND status = 'pending'").run(decision === "approve" ? "approved" : "denied", Date.now(), device, id, owner);498 if (done.changes !== 1) return null;499 const a = toApproval(db().prepare("SELECT * FROM vq_research_approvals WHERE id = ?").get(id));500 waiters.get(id)?.(a);501 approvalEvents.emit("approval", { owner, approval: a });502 return a;503}504505/** Requests left pending by a server that stopped can no longer be answered to anyone. */506export function expireStaleApprovals(): number {507 return db().prepare("UPDATE vq_research_approvals SET status = 'expired', resolved_at = ? WHERE status = 'pending'").run(Date.now()).changes;508}509