SPB Git

Repository Public MIT

research.ts 14.6 KB 271 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : VQuant8 * File             : server/next/research.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 API for the three clients (contract: docs/next/CONTRACT.md §9.6, §9.7).47 *48 *   GET    /api/v2/research/sessions                       the person's research workspaces, newest first49 *   POST   /api/v2/research/sessions                       { title?, projectId? } → a workspace and the sessionId to chat in50 *   GET    /api/v2/research/sessions/:id                   one workspace: files, experiments, runs, notes, environment, pending approvals51 *   GET    /api/v2/research/sessions/:id/files?path=       directory listing52 *   DELETE /api/v2/research/sessions/:id/files?path=       removes a file or a directory of the workspace (audited)53 *   GET    /api/v2/research/sessions/:id/file?path=&download=1   a file (text as JSON, or the raw bytes)54 *   POST   /api/v2/research/sessions/:id/upload            multipart `file`: a dataset (CSV/TSV/JSON/Parquet/Excel/Feather) → data/55 *   GET    /api/v2/research/sessions/:id/inspect?path=     schema, dtypes, missingness and head of a dataset56 *   GET    /api/v2/research/sessions/:id/experiments?kind= the ledger57 *   GET    /api/v2/research/sessions/:id/runs              script runs58 *   GET    /api/v2/research/runs/:runId                    one run with the end of its logs59 *   POST   /api/v2/research/runs/:runId/cancel60 *   GET    /api/v2/research/approvals?status=pending       authorization requests61 *   POST   /api/v2/research/approvals/:id                  { decision: "approve" | "deny" }62 *   GET    /api/v2/research/sandbox                        what isolates the code on this server, and its limits63 *64 * `:id` is a workspace id, or `session:<sessionId>` to address the workspace of a conversation. Everything is scoped65 * to the signed-in person; a workspace of someone else answers 404.66 */67import type { Express, Request, Response } from "express";68import fs from "node:fs";69import path from "node:path";70import multer from "multer";71import { randomUUID } from "node:crypto";72import { z } from "zod";73import { currentUser } from "../access";74import { logger } from "../utils/logger";75import { audit, requestDevice } from "./audit";76import { allowedHosts } from "../services/research/broker";77import { cancelRun, getRun, inspectDataset, listApprovals, listRuns, resolveApproval, tailLog } from "../services/research/runtime";78import { defaultLimits, sandboxStatus } from "../services/research/sandbox";79import { listTraces } from "./trace";80import {81  ResearchError, UPLOAD_MAX_BYTES, deleteFile, ensureWorkspace, listFigures, getWorkspace, listExperiments, listFiles, listLibrary, listNotes, listWorkspaces, readEnvironment, readTextFile, resolveInside, saveUpload, sessionsOfWorkspace, workspaceOfSession, type Workspace,82} from "../services/research/store";8384const summary = (w: Workspace) => ({ id: w.id, kind: w.kind, ref: w.ref, title: w.title, createdAt: w.createdAt, updatedAt: w.updatedAt, sessionIds: sessionsOfWorkspace(w.owner, w.id) });8586function fail(res: Response, e: unknown, what: string): void {87  if (e instanceof ResearchError) return void res.status(e.status).json({ error: e.message });88  logger.error(`[research] ${what}: ${(e as Error).message}`);89  res.status(500).json({ error: "The research workspace could not be read." });90}9192const MIME: Record<string, string> = { ".png": "image/png", ".svg": "image/svg+xml", ".pdf": "application/pdf", ".csv": "text/csv", ".json": "application/json", ".txt": "text/plain", ".py": "text/plain", ".md": "text/markdown", ".html": "text/html", ".parquet": "application/octet-stream", ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" };9394export function registerResearchRoutes(app: Express): void {95  const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: UPLOAD_MAX_BYTES, files: 1 } });96  const mine = (req: Request, res: Response): Workspace | null => {97    const owner = currentUser(req).id;98    const id = String(req.params.id ?? "");99    const ws = id.startsWith("session:") ? workspaceOfSession(owner, id.slice(8)) : getWorkspace(owner, id);100    if (!ws) res.status(404).json({ error: "Research workspace not found." });101    return ws;102  };103104  app.get("/api/v2/research/sessions", (req: Request, res: Response) => {105    try {106      res.set("Cache-Control", "private, no-store").json({ sessions: listWorkspaces(currentUser(req).id).map(summary) });107    } catch (e) {108      fail(res, e, "list");109    }110  });111112  app.post("/api/v2/research/sessions", (req: Request, res: Response) => {113    const parsed = z.object({ title: z.string().trim().max(200).optional(), projectId: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/).optional(), sessionId: z.string().regex(/^[A-Za-z0-9_-]{8,64}$/).optional() }).safeParse(req.body ?? {});114    if (!parsed.success) return res.status(400).json({ error: parsed.error.issues[0].message });115    try {116      const sessionId = parsed.data.sessionId ?? randomUUID();117      const ws = ensureWorkspace(currentUser(req).id, { sessionId, projectId: parsed.data.projectId, title: parsed.data.title });118      res.status(201).json({ session: summary(ws), sessionId });119    } catch (e) {120      fail(res, e, "create");121    }122  });123124  app.get("/api/v2/research/sessions/:id", (req: Request, res: Response) => {125    const ws = mine(req, res);126    if (!ws) return;127    try {128      const env = readEnvironment(ws);129      const generations = sessionsOfWorkspace(ws.owner, ws.id)130        .flatMap((sid) => listTraces(ws.owner, sid))131        .sort((a, b) => a.startedAt - b.startedAt);132      res.set("Cache-Control", "private, no-store").json({133        session: summary(ws),134        files: listFiles(ws, "", { recursive: true, max: 600 }),135        experiments: listExperiments(ws.owner, ws.id, { kind: "experiment", limit: 300 }),136        executions: listExperiments(ws.owner, ws.id, { kind: "execution", limit: 200 }),137        runs: listRuns(ws.owner, ws.id, 100),138        notes: listNotes(ws.owner, ws.id),139        library: listLibrary(ws.owner),140        environment: { hash: env.hash, packages: env.packages, overlay: env.overlay, lockfile: env.lockfile ? "environment.lock.txt" : null },141        approvals: listApprovals(ws.owner, { status: "pending", workspaceId: ws.id }),142        // What the live stream showed and a reload would otherwise lose: the analyses run in this workspace with143        // the final state of their plan and their budget, and every figure with its caption and linter verdict.144        generations,145        plan: [...generations].reverse().find((g) => g.plan.length > 0)?.plan ?? [],146        figures: listFigures(ws.owner, ws.id),147      });148    } catch (e) {149      fail(res, e, "detail");150    }151  });152153  app.get("/api/v2/research/sessions/:id/files", (req: Request, res: Response) => {154    const ws = mine(req, res);155    if (!ws) return;156    try {157      res.set("Cache-Control", "private, no-store").json({ path: String(req.query.path ?? ""), files: listFiles(ws, String(req.query.path ?? ""), { recursive: req.query.recursive === "1", max: 1000 }) });158    } catch (e) {159      fail(res, e, "files");160    }161  });162163  app.delete("/api/v2/research/sessions/:id/files", (req: Request, res: Response) => {164    const ws = mine(req, res);165    if (!ws) return;166    try {167      const rel = String(req.query.path ?? "");168      deleteFile(ws, rel);169      audit(req, "research.file.delete", `${ws.id}:${rel.slice(0, 300)}`);170      res.json({ ok: true, path: rel });171    } catch (e) {172      fail(res, e, "delete file");173    }174  });175176  app.get("/api/v2/research/sessions/:id/file", (req: Request, res: Response) => {177    const ws = mine(req, res);178    if (!ws) return;179    try {180      const rel = String(req.query.path ?? "");181      const target = resolveInside(ws.dir, rel, { userVisible: true });182      if (!fs.existsSync(target) || !fs.statSync(target).isFile() || fs.lstatSync(target).isSymbolicLink()) return res.status(404).json({ error: "No such file." });183      const ext = path.extname(target).toLowerCase();184      const textual = [".py", ".txt", ".md", ".csv", ".tsv", ".json", ".jsonl", ".log", ".toml", ".yaml", ".yml", ".tex", ".sql", ".r", ".ipynb"].includes(ext) || path.basename(target) === "environment.lock.txt";185      if (req.query.download !== "1" && textual) return res.set("Cache-Control", "private, no-store").json(readTextFile(ws, rel, { offset: Number(req.query.offset) || 1, limit: Number(req.query.limit) || 2000 }));186      // Raw bytes: never rendered as a page of this origin (a workspace file is untrusted content).187      res.set({ "Content-Type": ext === ".html" || ext === ".svg" ? (req.query.download === "1" ? "application/octet-stream" : MIME[ext]) : MIME[ext] ?? "application/octet-stream", "Content-Disposition": `${req.query.download === "1" || ext === ".html" ? "attachment" : "inline"}; filename="${path.basename(target).replace(/[^A-Za-z0-9._-]/g, "_")}"`, "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox", "Cache-Control": "private, no-store" });188      fs.createReadStream(target).pipe(res);189    } catch (e) {190      fail(res, e, "file");191    }192  });193194  app.post("/api/v2/research/sessions/:id/upload", (req: Request, res: Response) => {195    const ws = mine(req, res);196    if (!ws) return;197    upload.single("file")(req, res, (err: unknown) => {198      if (err) return res.status((err as { code?: string }).code === "LIMIT_FILE_SIZE" ? 413 : 400).json({ error: (err as { code?: string }).code === "LIMIT_FILE_SIZE" ? `The file is larger than ${UPLOAD_MAX_BYTES / 1024 / 1024} MB.` : "The upload could not be read." });199      const file = (req as Request & { file?: { originalname: string; buffer: Buffer } }).file;200      if (!file) return res.status(400).json({ error: "A file is required (multipart field `file`)." });201      try {202        const saved = saveUpload(ws, file.originalname, file.buffer);203        audit(req, "research.upload", `${ws.id}:${saved.path}`, { bytes: saved.bytes, sha256: saved.sha256.slice(0, 16) });204        res.status(201).json({ file: saved });205      } catch (e) {206        fail(res, e, "upload");207      }208    });209  });210211  app.get("/api/v2/research/sessions/:id/inspect", async (req: Request, res: Response) => {212    const ws = mine(req, res);213    if (!ws) return;214    try {215      res.set("Cache-Control", "private, no-store").json({ dataset: await inspectDataset(ws, String(req.query.path ?? "")) });216    } catch (e) {217      fail(res, e, "inspect");218    }219  });220221  app.get("/api/v2/research/sessions/:id/experiments", (req: Request, res: Response) => {222    const ws = mine(req, res);223    if (!ws) return;224    const kind = req.query.kind === "execution" ? "execution" : req.query.kind === "experiment" ? "experiment" : undefined;225    res.set("Cache-Control", "private, no-store").json({ experiments: listExperiments(ws.owner, ws.id, { kind, limit: 1000 }) });226  });227228  app.get("/api/v2/research/sessions/:id/runs", (req: Request, res: Response) => {229    const ws = mine(req, res);230    if (!ws) return;231    res.set("Cache-Control", "private, no-store").json({ runs: listRuns(ws.owner, ws.id, 200) });232  });233234  app.get("/api/v2/research/runs/:runId", (req: Request, res: Response) => {235    const owner = currentUser(req).id;236    const run = getRun(owner, req.params.runId);237    const ws = run ? getWorkspace(owner, run.workspaceId) : null;238    if (!run || !ws) return res.status(404).json({ error: "Run not found." });239    const tail = Math.min(200_000, Math.max(1000, Number(req.query.tail) || 20_000));240    res.set("Cache-Control", "private, no-store").json({ run, stdout: tailLog(ws, run.id, "stdout", tail), stderr: tailLog(ws, run.id, "stderr", Math.min(tail, 40_000)) });241  });242243  app.post("/api/v2/research/runs/:runId/cancel", (req: Request, res: Response) => {244    try {245      const run = cancelRun(currentUser(req).id, req.params.runId);246      audit(req, "research.run.cancel", run.id);247      res.json({ run });248    } catch (e) {249      fail(res, e, "cancel");250    }251  });252253  app.get("/api/v2/research/approvals", (req: Request, res: Response) => {254    const status = typeof req.query.status === "string" && ["pending", "approved", "denied", "expired"].includes(req.query.status) ? req.query.status : undefined;255    res.set("Cache-Control", "private, no-store").json({ approvals: listApprovals(currentUser(req).id, { status }) });256  });257258  app.post("/api/v2/research/approvals/:id", (req: Request, res: Response) => {259    const parsed = z.object({ decision: z.enum(["approve", "deny"]) }).safeParse(req.body);260    if (!parsed.success) return res.status(400).json({ error: 'decision must be "approve" or "deny"' });261    const a = resolveApproval(currentUser(req).id, req.params.id, parsed.data.decision, requestDevice(req));262    if (!a) return res.status(404).json({ error: "No pending request with this id." });263    audit(req, "research.approval.answer", `${a.action}:${a.id}`, { decision: parsed.data.decision });264    res.json({ approval: a });265  });266267  app.get("/api/v2/research/sandbox", (_req: Request, res: Response) => {268    res.set("Cache-Control", "private, no-store").json({ sandbox: sandboxStatus(), limits: defaultLimits(), network: { default: ["market data through the server (FMP, FinData)", ...allowedHosts()], open: "any public host, for one run, after an explicit authorization" }, uploadMaxBytes: UPLOAD_MAX_BYTES });269  });270}271
Files main
Menu

Theme