Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : client/src/lib/research/api.ts9 * Module : lib10 * 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/** Research REST (CONTRACT §9.6) as fetchers and TanStack Query hooks. Everything is scoped to the signed-in person by the server. */46import { useMemo } from "react";47import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";48import { reloadIfLocked } from "@/lib/queryClient";49import { fileUrl } from "./files";50import { stateFromSnapshot } from "./snapshot";51import type { DatasetInspection, ResearchState, RestApproval, RestRun, RestSession, SandboxStatus, SessionDetail, StoredMessage } from "./types";5253export class ResearchApiError extends Error {54 constructor(public status: number, message: string) { super(message); }55}5657async function request<T>(url: string, init?: RequestInit): Promise<T> {58 const res = await fetch(url, { credentials: "include", ...init });59 reloadIfLocked(res);60 if (!res.ok) {61 const body = await res.json().catch(() => null) as { error?: string } | null;62 throw new ResearchApiError(res.status, body?.error || `Erreur ${res.status}`);63 }64 return res.json() as Promise<T>;65}66const post = <T,>(url: string, body?: unknown) => request<T>(url, { method: "POST", headers: body === undefined ? undefined : { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });6768const base = "/api/v2/research";69/** Address of a workspace in the routes: its id, or `session:<sessionId>` for the workspace of a conversation. */70export const workspaceRef = (o: { workspaceId?: string | null; sessionId?: string | null }): string | null => o.workspaceId || (o.sessionId ? `session:${o.sessionId}` : null);7172export const researchKeys = {73 sessions: ["research", "sessions"] as const,74 detail: (ref: string) => ["research", "detail", ref] as const,75 file: (ref: string, path: string, limit: number) => ["research", "file", ref, path, limit] as const,76 inspect: (ref: string, path: string) => ["research", "inspect", ref, path] as const,77 run: (runId: string) => ["research", "run", runId] as const,78 approvals: ["research", "approvals", "pending"] as const,79 sandbox: ["research", "sandbox"] as const,80};8182export const createResearchSession = (body: { title?: string; projectId?: string | null; sessionId?: string | null }) =>83 post<{ session: RestSession; sessionId: string }>(`${base}/sessions`, { title: body.title, projectId: body.projectId ?? undefined, sessionId: body.sessionId ?? undefined });84export const fetchInspection = (ref: string, path: string) => request<{ dataset: DatasetInspection }>(`${base}/sessions/${encodeURIComponent(ref)}/inspect?path=${encodeURIComponent(path)}`).then((r) => r.dataset);85export const answerApproval = (id: string, decision: "approve" | "deny") => post<{ approval: RestApproval }>(`${base}/approvals/${encodeURIComponent(id)}`, { decision }).then((r) => r.approval);86export const deleteWorkspaceFile = (ref: string, path: string) => request<{ ok: boolean; path: string }>(`${base}/sessions/${encodeURIComponent(ref)}/files?path=${encodeURIComponent(path)}`, { method: "DELETE" });87export const cancelRun = (runId: string) => post<{ run: RestRun }>(`${base}/runs/${encodeURIComponent(runId)}/cancel`).then((r) => r.run);8889export interface TextFile { path: string; bytes: number; totalLines: number; from: number; to: number; text: string; truncated: boolean }90export const fetchTextFile = (ref: string, path: string, limit = 2000) => request<TextFile>(`${fileUrl(ref, path)}&limit=${limit}`);9192export function useResearchSessions(enabled = true) {93 return useQuery({ queryKey: researchKeys.sessions, queryFn: () => request<{ sessions: RestSession[] }>(`${base}/sessions`).then((r) => r.sessions), enabled, staleTime: 15_000, retry: 1 });94}9596/**97 * One workspace with its ledger, runs, notes, files and environment. A conversation that never used its workspace98 * answers 404: that is "no research here", not an error (data = null).99 */100export function useSessionDetail(ref: string | null, opts: { poll?: boolean } = {}) {101 return useQuery<SessionDetail | null>({102 queryKey: researchKeys.detail(ref ?? ""),103 queryFn: async () => {104 try { return await request<SessionDetail>(`${base}/sessions/${encodeURIComponent(ref!)}`); }105 catch (e) { if (e instanceof ResearchApiError && e.status === 404) return null; throw e; }106 },107 enabled: !!ref,108 // The stream says when the workspace changes (the study hook invalidates this query then). Polling is only for109 // what no event reports: a background run that outlives its generation.110 refetchInterval: opts.poll ? 8000 : false,111 staleTime: 20_000,112 retry: 1,113 });114}115116/** The view model of a workspace at rest, from the REST detail and the stored conversation. */117export function useSnapshotState(detail: SessionDetail | null | undefined, stored?: StoredMessage[]): ResearchState | null {118 return useMemo(() => (detail ? stateFromSnapshot(detail, stored ?? []) : null), [detail, stored]);119}120121export function useTextFile(ref: string | null, path: string | null, opts: { enabled?: boolean; limit?: number; immutable?: boolean } = {}) {122 const limit = opts.limit ?? 2000;123 return useQuery({ queryKey: researchKeys.file(ref ?? "", path ?? "", limit), queryFn: () => fetchTextFile(ref!, path!, limit), enabled: !!ref && !!path && opts.enabled !== false, staleTime: opts.immutable ? Infinity : 10_000, retry: false });124}125126export function useInspection(ref: string | null, path: string | null, enabled = true) {127 return useQuery({ queryKey: researchKeys.inspect(ref ?? "", path ?? ""), queryFn: () => fetchInspection(ref!, path!), enabled: !!ref && !!path && enabled, staleTime: 5 * 60_000, retry: false });128}129130export function useRunLogs(runId: string | null, opts: { enabled?: boolean; live?: boolean } = {}) {131 return useQuery({ queryKey: researchKeys.run(runId ?? ""), queryFn: () => request<{ run: RestRun; stdout: string; stderr: string }>(`${base}/runs/${encodeURIComponent(runId!)}?tail=12000`), enabled: !!runId && opts.enabled !== false, refetchInterval: opts.live ? 2500 : false, staleTime: opts.live ? 0 : 30_000, retry: false });132}133134export function useSandboxStatus(enabled = true) {135 return useQuery({ queryKey: researchKeys.sandbox, queryFn: () => request<SandboxStatus>(`${base}/sandbox`), enabled, staleTime: 10 * 60_000, retry: 1 });136}137138/** Requests waiting for the person, whatever the study: a request made while this device was away is found again. */139export function usePendingApprovals(enabled = true) {140 return useQuery({ queryKey: researchKeys.approvals, queryFn: () => request<{ approvals: RestApproval[] }>(`${base}/approvals?status=pending`).then((r) => r.approvals), enabled, refetchInterval: enabled ? 15_000 : false, staleTime: 0, retry: false });141}142143export function invalidateWorkspace(client: QueryClient, ref: string | null): void {144 if (ref) void client.invalidateQueries({ queryKey: researchKeys.detail(ref) });145 void client.invalidateQueries({ queryKey: researchKeys.sessions });146}147148export function useInvalidateWorkspace() {149 const client = useQueryClient();150 return (ref: string | null) => invalidateWorkspace(client, ref);151}152