okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-qafix into f-0213-int64b48c0d0

main
4.4 KiB125 linesraw
1import { userError } from './format';
2/** Thin HTTP client for the Strata host. Zero deps, works in browser and Electron renderer. */
3
4const BASE = (globalThis as { __STRATA_HOST__?: string }).__STRATA_HOST__ ?? '';
5
6export class ApiError extends Error {
7  constructor(
8    message: string,
9    readonly status: number,
10    readonly body?: unknown,
11  ) {
12    super(userError(message));
13    this.name = 'ApiError';
14  }
15}
16
17async function request<T>(method: string, path: string, body?: unknown, signal?: AbortSignal): Promise<T> {
18  const res = await fetch(`${BASE}${path}`, {
19    method,
20    signal,
21    headers: body === undefined ? undefined : { 'content-type': 'application/json' },
22    body: body === undefined ? undefined : JSON.stringify(body),
23  });
24  const text = await res.text();
25  const data = text ? (JSON.parse(text) as unknown) : undefined;
26  if (!res.ok) {
27    const message =
28      (data as { error?: string } | undefined)?.error ?? `Request failed (${res.status} ${res.statusText})`;
29    throw new ApiError(message, res.status, data);
30  }
31  return data as T;
32}
33
34export const api = {
35  get: <T>(path: string, signal?: AbortSignal) => request<T>('GET', path, undefined, signal),
36  post: <T>(path: string, body?: unknown) => request<T>('POST', path, body),
37  patch: <T>(path: string, body?: unknown) => request<T>('PATCH', path, body),
38  put: <T>(path: string, body?: unknown) => request<T>('PUT', path, body),
39  del: <T>(path: string) => request<T>('DELETE', path),
40};
41
42export interface StreamEvent {
43  event: string;
44  data: Record<string, unknown>;
45}
46
47/** Subscribe to the host event stream. Returns an unsubscribe function. */
48export function onEvent(handler: (e: StreamEvent) => void, onStatus?: (s: 'live' | 'offline') => void) {
49  let source: EventSource;
50  let seenAt = Date.now();
51  const names = ['engine', 'monitor', 'models', 'native', 'image-models', 'runtime', 'providers', 'serving', 'download', 'log', 'setup', 'skills', 'task', 'goal', 'timeskip', 'plan', 'queue', 'chats'];
52  const connect = () => {
53    source?.close();
54    seenAt = Date.now();
55    source = new EventSource(`${BASE}/api/events`);
56    for (const name of names) {
57      source.addEventListener(name, ((ev: MessageEvent) => {
58        seenAt = Date.now();
59        try { handler({ event: name, data: JSON.parse(ev.data) as Record<string, unknown> }); }
60        catch { /* Ignore malformed frames without losing valid state. */ }
61      }) as EventListener);
62    }
63    source.addEventListener('open', () => { seenAt = Date.now(); onStatus?.('live'); });
64    source.addEventListener('error', () => onStatus?.('offline'));
65    source.addEventListener('message', ev => {
66      seenAt = Date.now();
67      try { handler({ event: 'message', data: JSON.parse((ev as MessageEvent).data) as Record<string, unknown> }); }
68      catch { /* Ignore malformed frames. */ }
69    });
70  };
71  connect();
72  // The host sends monitor frames each second. Some proxies leave a dead SSE
73  // socket open, so silence must also invalidate readings and retry the stream.
74  const watchdog = setInterval(() => {
75    if (Date.now() - seenAt <= 10000) return;
76    onStatus?.('offline');
77    connect();
78  }, 5000);
79  return () => { clearInterval(watchdog); source.close(); };
80}
81
82/** POST a JSON body and consume an NDJSON/SSE-ish stream of JSON frames. */
83export async function streamPost(
84  path: string,
85  body: unknown,
86  onFrame: (frame: Record<string, unknown>) => void,
87  signal?: AbortSignal,
88): Promise<void> {
89  const res = await fetch(`${BASE}${path}`, {
90    method: 'POST',
91    headers: { 'content-type': 'application/json' },
92    body: JSON.stringify(body),
93    signal,
94  });
95  if (!res.ok || !res.body) {
96    const text = await res.text().catch(() => '');
97    throw new ApiError(text || `Stream failed (${res.status})`, res.status);
98  }
99  const reader = res.body.getReader();
100  const decoder = new TextDecoder();
101  let buffer = '';
102  for (;;) {
103    const { done, value } = await reader.read();
104    if (done) break;
105    buffer += decoder.decode(value, { stream: true });
106    let idx: number;
107    while ((idx = buffer.indexOf('\n')) >= 0) {
108      const line = buffer.slice(0, idx).trim();
109      buffer = buffer.slice(idx + 1);
110      if (!line) continue;
111      try {
112        onFrame(JSON.parse(line) as Record<string, unknown>);
113      } catch {
114        /* ignore partial frame */
115      }
116    }
117  }
118  if (buffer.trim()) {
119    try {
120      onFrame(JSON.parse(buffer.trim()) as Record<string, unknown>);
121    } catch {
122      /* ignore */
123    }
124  }
125}