File size: 6,179 Bytes
a5784e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
/**
 * API Client - Centralized HTTP client with error handling
 */

import type {
  ChatCompletionRequest,
  ChatCompletionResponse,
  ChatCompletionChunk,
  ModelsResponse,
  HealthStatus,
} from "@/types";

// Custom API Error
export class ApiError extends Error {
  status: number;
  userMessage: string;
  details?: unknown;

  constructor(status: number, userMessage: string, details?: unknown) {
    super(userMessage);
    this.name = "ApiError";
    this.status = status;
    this.userMessage = userMessage;
    this.details = details;
  }
}

// Base fetch wrapper with error handling
async function fetchApi<T>(url: string, options?: RequestInit): Promise<T> {
  try {
    const response = await fetch(url, {
      headers: {
        "Content-Type": "application/json",
        ...options?.headers,
      },
      ...options,
    });

    if (!response.ok) {
      const errorBody = await response.text();
      throw new ApiError(
        response.status,
        `Request failed: ${response.statusText}`,
        errorBody
      );
    }

    return response.json();
  } catch (error) {
    if (error instanceof ApiError) throw error;
    throw new ApiError(0, "Network error", error);
  }
}

// Models API
export async function fetchModels(): Promise<ModelsResponse> {
  return fetchApi<ModelsResponse>("/v1/models");
}

// Health API
export async function fetchHealth(): Promise<HealthStatus> {
  return fetchApi<HealthStatus>("/health");
}

// Chat API (non-streaming)
export async function sendChatCompletion(
  request: ChatCompletionRequest
): Promise<ChatCompletionResponse> {
  return fetchApi<ChatCompletionResponse>("/v1/chat/completions", {
    method: "POST",
    body: JSON.stringify({ ...request, stream: false }),
  });
}

// Chat API (streaming) - Returns async generator
export async function* streamChatCompletion(
  request: ChatCompletionRequest,
  signal?: AbortSignal
): AsyncGenerator<ChatCompletionChunk, void, unknown> {
  const response = await fetch("/v1/chat/completions", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ ...request, stream: true }),
    signal,
  });

  if (!response.ok) {
    throw new ApiError(response.status, `Request failed: ${response.statusText}`);
  }

  const reader = response.body?.getReader();
  if (!reader) throw new ApiError(0, "Cannot read response stream");

  const decoder = new TextDecoder();
  let buffer = "";

  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split("\n");
      buffer = lines.pop() || "";

      for (const line of lines) {
        const trimmed = line.trim();
        if (!trimmed || trimmed === "data: [DONE]") continue;
        if (!trimmed.startsWith("data: ")) continue;

        try {
          const json = JSON.parse(trimmed.slice(6));
          yield json as ChatCompletionChunk;
        } catch {
          // Skip malformed JSON
        }
      }
    }
  } finally {
    reader.releaseLock();
  }
}

// ============================================
// Proxy Configuration API
// ============================================

export interface ProxyConfig {
  enabled: boolean;
  address: string;
}

export interface ProxyTestResult {
  success: boolean;
  message: string;
  latency_ms?: number;
}

export async function fetchProxyConfig(): Promise<ProxyConfig> {
  return fetchApi<ProxyConfig>("/api/proxy/config");
}

export async function updateProxyConfig(
  config: ProxyConfig
): Promise<{ success: boolean; config: ProxyConfig }> {
  return fetchApi("/api/proxy/config", {
    method: "POST",
    body: JSON.stringify(config),
  });
}

export async function testProxyConnectivity(
  address: string,
  testUrl?: string
): Promise<ProxyTestResult> {
  return fetchApi<ProxyTestResult>("/api/proxy/test", {
    method: "POST",
    body: JSON.stringify({
      address,
      test_url: testUrl || "http://httpbin.org/get",
    }),
  });
}

// ============================================
// Auth Files API
// ============================================

interface AuthFileInfo {
  name: string;
  path: string;
  size_bytes: number;
  is_active: boolean;
}

interface AuthFilesResponse {
  saved_files: AuthFileInfo[];
  active_file: string | null;
}

export async function fetchAuthFiles(): Promise<AuthFilesResponse> {
  return fetchApi<AuthFilesResponse>("/api/auth/files");
}

export async function fetchActiveAuth(): Promise<{
  active_file: string | null;
}> {
  return fetchApi("/api/auth/active");
}

export async function activateAuthFile(
  filename: string
): Promise<{ success: boolean; message: string; active_file: string }> {
  return fetchApi("/api/auth/activate", {
    method: "POST",
    body: JSON.stringify({ filename }),
  });
}

export async function deactivateAuth(): Promise<{
  success: boolean;
  message: string;
}> {
  return fetchApi("/api/auth/deactivate", {
    method: "DELETE",
  });
}

// ============================================
// Ports Configuration API
// ============================================

export interface PortConfig {
  fastapi_port: number;
  camoufox_debug_port: number;
  stream_proxy_port: number;
  stream_proxy_enabled: boolean;
}

interface ProcessInfo {
  pid: number;
  name: string;
}

interface PortStatusInfo {
  port: number;
  port_type: string;
  in_use: boolean;
  processes: ProcessInfo[];
}

export async function fetchPortConfig(): Promise<PortConfig> {
  return fetchApi<PortConfig>("/api/ports/config");
}

export async function updatePortConfig(
  config: PortConfig
): Promise<{ success: boolean; message: string; config: PortConfig }> {
  return fetchApi("/api/ports/config", {
    method: "POST",
    body: JSON.stringify(config),
  });
}

export async function fetchPortStatus(): Promise<{ ports: PortStatusInfo[] }> {
  return fetchApi("/api/ports/status");
}

export async function killProcess(
  pid: number
): Promise<{ success: boolean; message: string; pid: number }> {
  return fetchApi("/api/ports/kill", {
    method: "POST",
    body: JSON.stringify({ pid, confirm: true }),
  });
}