Spaces:
Runtime error
Runtime error
File size: 10,068 Bytes
3c8d218 e2728d4 1e24842 3c8d218 1e24842 098f3ea 1e24842 3c8d218 1e24842 3c8d218 1e24842 098f3ea 1e24842 098f3ea ef865f2 098f3ea 1e24842 098f3ea ef865f2 098f3ea ad279fb 098f3ea 1e24842 098f3ea 1e24842 098f3ea 1e24842 098f3ea 1e24842 098f3ea 3c8d218 6270070 3c8d218 1e24842 3c8d218 1e24842 3c8d218 481e01c 3c8d218 481e01c 3c8d218 481e01c 3c8d218 481e01c 3c8d218 481e01c 3c8d218 481e01c 3c8d218 ef865f2 3c8d218 6270070 1e24842 6270070 | 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 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | import axios from 'axios';
const BACKEND_URL = (import.meta.env.VITE_BACKEND_URL || 'http://localhost:8001').replace(/\/+$/, '');
const API_BASE = `${BACKEND_URL}/api/v1`;
const SESSION_KEY = '_jwt';
// Token lives in module memory AND sessionStorage (survives refresh, clears on tab close)
let _token = null;
function _restoreToken() {
if (!_token) _token = sessionStorage.getItem(SESSION_KEY);
return _token;
}
export const api = axios.create({
baseURL: API_BASE,
timeout: 60000,
});
// Attach Bearer token to every request; restore from sessionStorage on first use after refresh
api.interceptors.request.use((config) => {
const tok = _restoreToken();
if (tok) config.headers.Authorization = `Bearer ${tok}`;
return config;
});
// Normalize error shape; broadcast logout on 401
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
_token = null;
sessionStorage.removeItem(SESSION_KEY);
window.dispatchEvent(new Event('auth:logout'));
}
const msg =
error.response?.data?.error ||
error.response?.data?.detail ||
error.message ||
'An unexpected error occurred.';
return Promise.reject(new Error(typeof msg === 'string' ? msg : JSON.stringify(msg)));
}
);
export const AuthService = {
register: async (username, password) => {
const response = await axios.post(`${API_BASE}/auth/register`, { username, password });
_token = response.data.access_token;
sessionStorage.setItem(SESSION_KEY, _token);
return response.data;
},
login: async (username, password) => {
// Uses plain axios (no token needed, no 401 redirect loop)
const response = await axios.post(`${API_BASE}/auth/login`, { username, password });
_token = response.data.access_token;
sessionStorage.setItem(SESSION_KEY, _token);
return response.data;
},
logout: () => {
_token = null;
sessionStorage.removeItem(SESSION_KEY);
},
isAuthenticated: () => !!_restoreToken(),
};
export const SpecService = {
getAllSpecs: async () => {
const response = await api.get('/specs');
return response.data;
},
getSpec: async (id) => {
const response = await api.get(`/specs/${id}`);
return response.data;
},
deleteSpec: async (id) => {
const response = await api.delete(`/specs/${id}`);
return response.data;
},
uploadSpec: async (file) => {
const formData = new FormData();
formData.append('file', file);
const response = await api.post('/upload-spec', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
return response.data;
},
updateBaseUrl: async (id, baseUrl) => {
const response = await api.patch(`/specs/${id}`, { base_url: baseUrl });
return response.data;
}
};
export const SessionService = {
createSession: async () => {
const response = await api.post('/session');
return response.data;
},
clearSession: async (id) => {
const response = await api.delete(`/session/${id}`);
return response.data;
},
getContext: async (id) => {
const response = await api.get(`/context/${id}`);
return response.data;
},
updateContext: async (id, key, value) => {
const response = await api.post(`/context/${id}`, { session_id: id, key, value });
return response.data;
}
};
export const PlanService = {
generatePlan: async (payload) => {
const response = await api.post('/plan', payload);
return response.data;
},
/**
* Streaming version of generatePlan.
* Calls the SSE endpoint and fires callbacks for each event.
* onStatus(message) — progress messages while the AI is thinking
* onStep(step) — called once per step as it arrives
* onComplete(data) — { suggested_credentials, token_usage } when done
* onError(message) — on server-side error
*/
streamPlan: async (payload, { onStatus, onStep, onComplete, onError }) => {
const tok = _restoreToken();
const response = await fetch(`${API_BASE}/plan/stream`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(tok ? { Authorization: `Bearer ${tok}` } : {}),
},
body: JSON.stringify(payload),
});
if (!response.ok) {
const text = await response.text();
throw new Error(text || `Plan stream failed: ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
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(); // keep incomplete last line
for (const line of lines) {
if (!line.startsWith('data: ')) continue;
try {
const event = JSON.parse(line.slice(6));
if (event.type === 'status') onStatus?.(event.message);
else if (event.type === 'step') onStep?.(event.step);
else if (event.type === 'complete') onComplete?.(event);
else if (event.type === 'error') onError?.(event.message);
} catch { /* ignore malformed SSE line */ }
}
}
},
executeStep: async (payload) => {
const response = await api.post('/execute-step', payload);
return response.data;
},
analyzeResponse: async (payload) => {
const response = await api.post('/analyze-response', payload);
return response.data;
},
};
export const CredentialService = {
getCredentials: async (specId) => {
const response = await api.get(`/specs/${specId}/credentials`);
return response.data;
},
saveCredentials: async (specId, payload) => {
const response = await api.post(`/specs/${specId}/credentials`, payload);
return response.data;
}
}
export const AssetService = {
uploadAsset: async (specId, collectionId, file, description = '', tags = []) => {
const formData = new FormData();
if (specId) formData.append('spec_id', specId);
if (collectionId) formData.append('collection_id', collectionId);
formData.append('file', file);
formData.append('description', description);
formData.append('tags', JSON.stringify(tags));
const response = await api.post('/assets', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
return response.data;
},
getAllAssets: async (specId = null, category = null) => {
const params = {};
if (specId) params.spec_id = specId;
if (category) params.category = category;
const response = await api.get('/assets', { params });
return response.data;
},
deleteAsset: async (id) => {
const response = await api.delete(`/assets/${id}`);
return response.data;
},
// Collections
getCollections: async (specId = null) => {
const params = {};
if (specId) params.spec_id = specId;
const response = await api.get('/collections', { params });
return response.data;
},
createCollection: async (name, specId = null, description = '') => {
const formData = new FormData();
formData.append('name', name);
if (specId) formData.append('spec_id', specId);
formData.append('description', description);
const response = await api.post('/collections', formData);
return response.data;
},
addToCollection: async (collectionId, asset_id) => {
const response = await api.post(`/collections/${collectionId}/assets/${asset_id}`);
return response.data;
},
deleteCollection: async (id) => {
const response = await api.delete(`/collections/${id}`);
return response.data;
}
};
export const HistoryService = {
getHistory: async () => {
const response = await api.get('/history');
return response.data;
},
async deleteHistorySession(sessionId) {
const response = await api.delete(`/history/${sessionId}`);
return response.data;
},
async clearAllHistory() {
const response = await api.delete('/history');
return response.data;
},
async exportSession(sessionId) {
const response = await api.get(`/history/${sessionId}/export`, { responseType: 'blob' });
const url = URL.createObjectURL(response.data);
const a = document.createElement('a');
a.href = url;
a.download = `session_${sessionId.slice(0, 8)}.json`;
a.click();
URL.revokeObjectURL(url);
},
};
export const UsageService = {
getUsage: async (params = {}) => {
const response = await api.get('/usage', { params });
return response.data;
},
};
export const LLMSettingsService = {
get: async () => {
const response = await api.get('/settings/llm');
return response.data;
},
saveProviderKey: async (providerId, apiKey) => {
const response = await api.put(`/settings/llm/providers/${providerId}`, { api_key: apiKey });
return response.data;
},
deleteProviderKey: async (providerId) => {
const response = await api.delete(`/settings/llm/providers/${providerId}/key`);
return response.data;
},
saveTaskConfig: async (taskName, config) => {
const response = await api.put(`/settings/llm/tasks/${taskName}`, config);
return response.data;
},
};
export const ChatService = {
sendMessage: async (payload) => {
const response = await api.post('/chat', payload);
return response.data;
},
getSessions: async (specId = null) => {
const params = {};
if (specId) params.spec_id = specId;
const response = await api.get('/chat-sessions', { params });
return response.data;
},
getSession: async (id) => {
const response = await api.get(`/chat-sessions/${id}`);
return response.data;
},
renameSession: async (id, name) => {
const response = await api.patch(`/chat-sessions/${id}`, { name });
return response.data;
},
deleteSession: async (id) => {
const response = await api.delete(`/chat-sessions/${id}`);
return response.data;
},
clearAll: async () => {
const response = await api.delete('/chat-sessions');
return response.data;
},
};
|