export interface ImageConfig { enabled: boolean; every: number; size: number; zoom: number; } export type RunStatus = "queued" | "running" | "done" | "failed" | "cancelled"; export interface RunInfo { id: string; example: string; name: string | null; status: RunStatus; started_at: number; finished_at: number; last_step: number | null; log_lines: number; overrides: Record; image: ImageConfig; } export async function listExamples(): Promise { const r = await fetch("/api/examples"); if (!r.ok) throw new Error(`listExamples: ${r.status}`); return r.json(); } export interface SubmitPayload { example: string; overrides: Record; image: ImageConfig; } export async function submitRun(payload: SubmitPayload): Promise { const r = await fetch("/api/runs", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), }); if (!r.ok) throw new Error(`submitRun: ${r.status} ${await r.text()}`); return r.json(); } export interface ParamSpec { name: string; label: string; type: "int" | "float" | "bool"; group: string; /** Discovered default from the example's input file. */ default?: number; description?: string; min?: number; max?: number; step?: number; decimals?: number; } export interface ExampleSchema { /** Discovered + metadata-overlaid parameters for a specific example. */ params: ParamSpec[]; /** Default image-rendering config. */ image: ImageConfig; } export async function getExampleSchema(name: string): Promise { const r = await fetch(`/api/examples/${encodeURIComponent(name)}/schema`); if (!r.ok) throw new Error(`getExampleSchema: ${r.status}`); return r.json(); } // ── Legacy types/helpers kept so existing callers can migrate gradually ── export interface SchemaResponse { params: ParamSpec[]; image_defaults: ImageConfig; } /** @deprecated Use getExampleSchema(name) — global metadata is incomplete. */ export async function getSchema(): Promise { const r = await fetch("/api/schema"); if (!r.ok) throw new Error(`getSchema: ${r.status}`); return r.json(); } export interface ExampleDefaults { values: Record; image: ImageConfig; } /** @deprecated Use getExampleSchema(name) — that one returns full per-param info. */ export async function getExampleDefaults(name: string): Promise { const r = await fetch(`/api/examples/${encodeURIComponent(name)}/defaults`); if (!r.ok) throw new Error(`getExampleDefaults: ${r.status}`); return r.json(); } export async function getRun(id: string): Promise { const r = await fetch(`/api/runs/${id}`); if (!r.ok) throw new Error(`getRun: ${r.status}`); return r.json(); } export async function listRuns(): Promise { const r = await fetch("/api/runs"); if (!r.ok) throw new Error(`listRuns: ${r.status}`); return r.json(); } export async function renameRun(id: string, name: string | null): Promise { const r = await fetch(`/api/runs/${id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }), }); if (!r.ok) throw new Error(`renameRun: ${r.status} ${await r.text()}`); return r.json(); } export async function deleteRun(id: string): Promise { const r = await fetch(`/api/runs/${id}`, { method: "DELETE" }); if (!r.ok && r.status !== 204) { throw new Error(`deleteRun: ${r.status} ${await r.text()}`); } } export async function getLog(id: string): Promise { const r = await fetch(`/api/runs/${id}/log`); if (!r.ok) throw new Error(`getLog: ${r.status}`); return r.text(); } export interface Frame { step: number; filename: string; } export async function listFrames(id: string): Promise { const r = await fetch(`/api/runs/${id}/frames`); if (!r.ok) throw new Error(`listFrames: ${r.status}`); return r.json(); } export function frameUrl(runId: string, filename: string): string { return `/api/runs/${runId}/frames/${encodeURIComponent(filename)}`; } export async function stopRun(id: string): Promise { const r = await fetch(`/api/runs/${id}/stop`, { method: "POST" }); if (!r.ok) throw new Error(`stopRun: ${r.status} ${await r.text()}`); return r.json(); } export interface ThermoData { columns: string[]; rows: number[][]; } export async function getThermo(id: string): Promise { const r = await fetch(`/api/runs/${id}/thermo`); if (!r.ok) throw new Error(`getThermo: ${r.status}`); return r.json(); } export interface Preset { id: string; name: string; description: string; overrides: Record; image: ImageConfig; created_at: number; updated_at: number; } export async function listPresets(): Promise { const r = await fetch("/api/presets"); if (!r.ok) throw new Error(`listPresets: ${r.status}`); return r.json(); } export async function createPreset( name: string, overrides: Record, image: ImageConfig, description = "" ): Promise { const r = await fetch("/api/presets", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name, overrides, image, description }), }); if (!r.ok) throw new Error(`createPreset: ${r.status} ${await r.text()}`); return r.json(); } export async function deletePreset(pid: string): Promise { const r = await fetch(`/api/presets/${pid}`, { method: "DELETE" }); if (!r.ok && r.status !== 204) throw new Error(`deletePreset: ${r.status}`); } // ---- Optimization studies ---- export interface SearchSpaceEntry { type: "float" | "int" | "categorical"; low?: number; high?: number; choices?: (number | string)[]; log?: boolean; /** Discretization step. Optional; integer parameters default to 1 if omitted. */ step?: number; } export type Reducer = | "last" | "abs_last" | "mean" | "abs_mean" | "stability" | "mae" | "mape"; export type Direction = "minimize" | "maximize"; export type Sampler = "tpe" | "random" | "cmaes" | "nsga2" | "nsga3"; /** Reducers that require the user to supply a target value. */ export const TARGET_REDUCERS: Reducer[] = ["mae", "mape"]; export interface Objective { metric: string; reduce: Reducer; direction: Direction; /** Required for mae / mape; ignored otherwise. */ target?: number | null; } export interface TrialResult { number: number; run_id: string; overrides: Record; values: number[] | null; // one entry per objective; null if pruned/failed status: "running" | "done" | "failed" | "cancelled"; } export interface ParetoTrial { number: number; values: number[]; params: Record; } export interface StudyState { id: string; name: string; example: string; fixed: Record; space: Record; objectives: Objective[]; n_objectives: number; n_trials: number; sampler: Sampler; status: "queued" | "running" | "done" | "cancelled" | "failed"; started_at: number; finished_at: number; trials: TrialResult[]; pareto_trials: ParetoTrial[]; error: string | null; n_completed: number; } export interface StartStudyPayload { name: string; example: string; fixed: Record; space: Record; objectives: Objective[]; n_trials: number; sampler: Sampler; } export async function listStudies(): Promise { const r = await fetch("/api/studies"); if (!r.ok) throw new Error(`listStudies: ${r.status}`); return r.json(); } export async function startStudy(p: StartStudyPayload): Promise { const r = await fetch("/api/studies", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(p), }); if (!r.ok) throw new Error(`startStudy: ${r.status} ${await r.text()}`); return r.json(); } export async function getStudy(id: string): Promise { const r = await fetch(`/api/studies/${id}`); if (!r.ok) throw new Error(`getStudy: ${r.status}`); return r.json(); } export async function stopStudy(id: string): Promise { const r = await fetch(`/api/studies/${id}/stop`, { method: "POST" }); if (!r.ok) throw new Error(`stopStudy: ${r.status} ${await r.text()}`); return r.json(); } // ---- Study analysis report ---- export interface ImportanceScore { param: string; score: number; } export interface ImportanceObjective { objective: string; direction: Direction; scores: ImportanceScore[]; error?: string; } export interface HistoryPoint { trial: number; value: number; best: number; } export interface HistoryObjective { objective: string; direction: Direction; points: HistoryPoint[]; } export interface SlicePoint { x: number; y: number; trial: number; } export interface SliceObjective { objective: string; direction: Direction; points: SlicePoint[]; } export interface CorrelationEntry { objective: string; param: string; r: number; n: number; } export interface StudyReport { n_completed: number; importances: ImportanceObjective[]; history: HistoryObjective[]; correlations: CorrelationEntry[]; slices: Record; } export interface BuildVersion { build_time: string; git_commit: string; } export async function getVersion(): Promise { const r = await fetch("/api/version"); if (!r.ok) throw new Error(`getVersion: ${r.status}`); return r.json(); } export async function getStudyReport(id: string): Promise { const r = await fetch(`/api/studies/${id}/report`); if (!r.ok) throw new Error(`getStudyReport: ${r.status}`); return r.json(); } // ---- Agent (LLM) ---- export interface AgentInfo { providers: string[]; defaults: Record; default_provider: string; server_has_default_key: boolean; } export async function getAgentInfo(): Promise { const r = await fetch("/api/agent/info"); if (!r.ok) throw new Error(`getAgentInfo: ${r.status}`); return r.json(); } export async function getMemory(): Promise { const r = await fetch("/api/agent/memory"); if (!r.ok) throw new Error(`getMemory: ${r.status}`); return r.text(); } export async function putMemory(content: string): Promise { const r = await fetch("/api/agent/memory", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ content }), }); if (!r.ok) throw new Error(`putMemory: ${r.status} ${await r.text()}`); } export async function listAgentDocs(): Promise { const r = await fetch("/api/agent/docs"); if (!r.ok) throw new Error(`listAgentDocs: ${r.status}`); return (await r.json()).files; } export async function readAgentDoc(filename: string): Promise { const r = await fetch(`/api/agent/docs/${encodeURIComponent(filename)}`); if (!r.ok) throw new Error(`readAgentDoc: ${r.status}`); return r.text(); } export interface ChatMessage { role: "user" | "assistant" | "system"; content: string; } export type AgentEvent = | { type: "assistant"; content: string } | { type: "tool_call"; id: string; name: string; arguments: Record } | { type: "tool_result"; id: string; name: string; result: unknown } | { type: "tool_error"; id: string; name: string; error: string } | { type: "done" } | { type: "error"; message: string }; export interface ChatRequest { messages: ChatMessage[]; provider?: string; base_url?: string; model?: string; api_key?: string; } export function openAgentChat( payload: ChatRequest, onEvent: (e: AgentEvent) => void ): WebSocket { const proto = location.protocol === "https:" ? "wss" : "ws"; const ws = new WebSocket(`${proto}://${location.host}/api/agent/chat`); ws.onopen = () => ws.send(JSON.stringify(payload)); ws.onmessage = (m) => { try { onEvent(JSON.parse(m.data)); } catch { // ignore malformed } }; return ws; } export type LogEvent = | { type: "log"; line: string } | { type: "status"; status: RunInfo["status"]; last_step: number | null } | { type: "error"; message: string }; export function openLogStream( id: string, onEvent: (e: LogEvent) => void ): WebSocket { const proto = location.protocol === "https:" ? "wss" : "ws"; const ws = new WebSocket(`${proto}://${location.host}/api/ws/runs/${id}`); ws.onmessage = (m) => { try { onEvent(JSON.parse(m.data)); } catch { // ignore malformed frames } }; return ws; }