-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-client.js
More file actions
165 lines (142 loc) · 4.83 KB
/
Copy pathapi-client.js
File metadata and controls
165 lines (142 loc) · 4.83 KB
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
/* global oauthGetToken, oauthRefreshToken, oauthLogout, getConfig, chrome */
const API_BASE = '/api/ambient/v1';
const DEFAULT_TIMEOUT = 30000;
async function apiRequest(method, path, options = {}) {
const { body, params, stream, timeout = DEFAULT_TIMEOUT } = options;
const config = await getConfig();
if (!config.baseUrl) throw new Error('Not configured');
let url = `${config.baseUrl}${API_BASE}${path}`;
if (params) {
const qs = new URLSearchParams();
for (const [k, v] of Object.entries(params)) {
if (v != null) qs.set(k, v);
}
const str = qs.toString();
if (str) url += `?${str}`;
}
let token = await oauthGetToken();
if (!token) throw new Error('Not authenticated');
const buildHeaders = (tkn) => {
const h = {
'Authorization': `Bearer ${tkn}`,
'X-Ambient-Project': config.projectName || '',
'User-Agent': 'acp-browser-extension/0.2.0',
'Accept': stream ? 'text/event-stream' : 'application/json',
};
if (body !== undefined) h['Content-Type'] = 'application/json';
return h;
};
const buildFetchOpts = (tkn, signal) => {
const opts = { method, headers: buildHeaders(tkn), signal };
if (body !== undefined) opts.body = JSON.stringify(body);
return opts;
};
const doFetch = async (tkn) => {
const controller = new AbortController();
let timer;
if (!stream && timeout > 0) {
timer = setTimeout(() => controller.abort(), timeout);
}
try {
return await fetch(url, buildFetchOpts(tkn, controller.signal));
} finally {
if (timer) clearTimeout(timer);
}
};
let response = await doFetch(token);
if (response.status === 401) {
const refreshed = await oauthRefreshToken();
if (refreshed) {
response = await doFetch(refreshed);
}
if (!refreshed || response.status === 401) {
try { chrome.runtime.sendMessage({ type: 'AUTH_EXPIRED' }); } catch (_) {}
throw new Error('Authentication expired');
}
}
if (stream && response.ok) return response;
if (response.status === 204) return null;
let json;
try {
json = await response.json();
} catch (_) {
json = null;
}
if (!response.ok) {
const err = new Error(json?.reason || response.statusText);
err.status = response.status;
err.code = json?.code;
err.reason = json?.reason;
throw err;
}
return json;
}
function parseSSEStream(response, onEvent, onError, signal) {
const controller = new AbortController();
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let dataLines = [];
if (signal) {
signal.addEventListener('abort', () => {
controller.abort();
reader.cancel();
});
}
(async () => {
try {
while (true) {
if (controller.signal.aborted) break;
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) {
if (line.startsWith('data: ')) {
dataLines.push(line.slice(6));
} else if (line === '' && dataLines.length > 0) {
const raw = dataLines.join('\n');
dataLines = [];
try {
onEvent(JSON.parse(raw));
} catch (e) {
if (onError) onError(e);
}
}
}
}
} catch (e) {
if (e.name !== 'AbortError' && onError) onError(e);
}
})();
return controller;
}
const api = {
sessions: {
list: (params) => apiRequest('GET', '/sessions', { params }),
get: (id) => apiRequest('GET', `/sessions/${id}`),
create: (body) => apiRequest('POST', '/sessions', { body }),
start: (id) => apiRequest('POST', `/sessions/${id}/start`),
stop: (id) => apiRequest('POST', `/sessions/${id}/stop`),
delete: (id) => apiRequest('DELETE', `/sessions/${id}`),
listMessages: (id, afterSeq) =>
apiRequest('GET', `/sessions/${id}/messages`, { params: { after_seq: afterSeq || 0 }, timeout: 60000 }),
sendMessage: (id, payload) =>
apiRequest('POST', `/sessions/${id}/messages`, { body: { event_type: 'user', payload }, timeout: 60000 }),
streamMessages: (id, afterSeq) =>
apiRequest('GET', `/sessions/${id}/messages`, { params: { after_seq: afterSeq || 0 }, stream: true }),
streamEvents: (id) =>
apiRequest('GET', `/sessions/${id}/events`, { stream: true }),
},
projects: {
list: (params) => apiRequest('GET', '/projects', { params }),
get: (id) => apiRequest('GET', `/projects/${id}`),
create: (body) => apiRequest('POST', '/projects', { body }),
update: (id, body) => apiRequest('PATCH', `/projects/${id}`, { body }),
delete: (id) => apiRequest('DELETE', `/projects/${id}`),
},
agents: {},
credentials: {},
scheduledSessions: {},
};