Elffuss BraidHub

kikocis/continue public

dfc814e4318e · 8.0 KiBRawPermalink
1import { ConfigJson } from "@continuedev/config-types";
2import {
3 AssistantUnrolled,
4 ConfigResult,
5 FQSN,
6 FullSlug,
7 Policy,
8 SecretResult,
9 SecretType,
10} from "@continuedev/config-yaml";
11import fetch, { RequestInit, Response } from "node-fetch";
12
13import { OrganizationDescription } from "../config/ProfileLifecycleManager.js";
14import { IDE, ModelDescription } from "../index.js";
15import { Logger } from "../util/Logger.js";
16
17import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js";
18import { getControlPlaneEnv } from "./env.js";
19
20export interface PolicyResponse {
21 orgSlug?: string;
22 policy?: Policy;
23}
24
25export interface ControlPlaneWorkspace {
26 id: string;
27 name: string;
28 settings: ConfigJson;
29}
30
31export interface ControlPlaneModelDescription extends ModelDescription {}
32
33export interface FreeTrialStatus {
34 optedInToFreeTrial: boolean;
35 chatCount?: number;
36 autocompleteCount?: number;
37 chatLimit: number;
38 autocompleteLimit: number;
39}
40
41export const TRIAL_PROXY_URL =
42 "https://proxy-server-blue-l6vsfbzhba-uw.a.run.app";
43
44export class ControlPlaneClient {
45 constructor(
46 readonly sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
47 private readonly ide: IDE,
48 ) {}
49
50 async resolveFQSNs(
51 fqsns: FQSN[],
52 orgScopeId: string | null,
53 ): Promise<(SecretResult | undefined)[]> {
54 if (!(await this.isSignedIn())) {
55 return fqsns.map((fqsn) => ({
56 found: false,
57 fqsn,
58 secretLocation: {
59 secretName: fqsn.secretName,
60 secretType: SecretType.NotFound,
61 },
62 }));
63 }
64
65 const resp = await this.requestAndHandleError("ide/sync-secrets", {
66 method: "POST",
67 body: JSON.stringify({ fqsns, orgScopeId }),
68 });
69 return (await resp.json()) as any;
70 }
71
72 async isSignedIn(): Promise<boolean> {
73 const sessionInfo = await this.sessionInfoPromise;
74 return !!sessionInfo;
75 }
76
77 async getAccessToken(): Promise<string | undefined> {
78 const sessionInfo = await this.sessionInfoPromise;
79 return isOnPremSession(sessionInfo) ? undefined : sessionInfo?.accessToken;
80 }
81
82 private async request(path: string, init: RequestInit): Promise<Response> {
83 const sessionInfo = await this.sessionInfoPromise;
84 const onPremSession = isOnPremSession(sessionInfo);
85 const accessToken = await this.getAccessToken();
86
87 // Bearer token not necessary for on-prem auth type
88 if (!accessToken && !onPremSession) {
89 throw new Error("No access token");
90 }
91
92 const env = await getControlPlaneEnv(this.ide.getIdeSettings());
93 const url = new URL(path, env.CONTROL_PLANE_URL).toString();
94 const ideInfo = await this.ide.getIdeInfo();
95
96 const resp = await fetch(url, {
97 ...init,
98 headers: {
99 ...init.headers,
100 Authorization: `Bearer ${accessToken}`,
101 ...{
102 "x-extension-version": ideInfo.extensionVersion,
103 "x-is-prerelease": String(ideInfo.isPrerelease),
104 },
105 },
106 });
107
108 return resp;
109 }
110
111 private async requestAndHandleError(
112 path: string,
113 init: RequestInit,
114 ): Promise<Response> {
115 const resp = await this.request(path, init);
116
117 if (!resp.ok) {
118 throw new Error(
119 `Control plane request failed: ${resp.status} ${await resp.text()}`,
120 );
121 }
122
123 return resp;
124 }
125
126 public async listAssistants(organizationId: string | null): Promise<
127 {
128 configResult: ConfigResult<AssistantUnrolled>;
129 ownerSlug: string;
130 packageSlug: string;
131 iconUrl: string;
132 rawYaml: string;
133 }[]
134 > {
135 if (!(await this.isSignedIn())) {
136 return [];
137 }
138
139 try {
140 const url = organizationId
141 ? `ide/list-assistants?organizationId=${organizationId}`
142 : "ide/list-assistants";
143
144 const resp = await this.requestAndHandleError(url, {
145 method: "GET",
146 });
147 return (await resp.json()) as any;
148 } catch (e) {
149 // Capture control plane API failures to Sentry
150 Logger.error(e, {
151 context: "control_plane_list_assistants",
152 organizationId,
153 });
154 return [];
155 }
156 }
157
158 public async listOrganizations(): Promise<Array<OrganizationDescription>> {
159 if (!(await this.isSignedIn())) {
160 return [];
161 }
162
163 // We try again here because when users sign up with an email domain that is
164 // captured by an org, we need to wait for the user account creation webhook to
165 // take effect. Otherwise the organization(s) won't show up.
166 // This error manifests as a 404 (user not found)
167 let retries = 0;
168 const maxRetries = 10;
169 const maxWaitTime = 20000; // 20 seconds in milliseconds
170
171 while (retries < maxRetries) {
172 const resp = await this.request("ide/list-organizations", {
173 method: "GET",
174 });
175
176 if (resp.status === 404) {
177 retries++;
178 if (retries >= maxRetries) {
179 console.warn(
180 `Failed to list organizations after ${maxRetries} retries: user not found`,
181 );
182 return [];
183 }
184 const waitTime = Math.min(
185 Math.pow(2, retries) * 100,
186 maxWaitTime / maxRetries,
187 );
188 await new Promise((resolve) => setTimeout(resolve, waitTime));
189 continue;
190 } else if (!resp.ok) {
191 console.warn(
192 `Failed to list organizations (${resp.status}): ${await resp.text()}`,
193 );
194 return [];
195 }
196 const { organizations } = (await resp.json()) as any;
197 return organizations;
198 }
199
200 // This should never be reached due to the while condition, but adding for safety
201 console.warn(
202 `Failed to list organizations after ${maxRetries} retries: maximum attempts exceeded`,
203 );
204 return [];
205 }
206
207 public async listAssistantFullSlugs(
208 organizationId: string | null,
209 ): Promise<FullSlug[] | null> {
210 if (!(await this.isSignedIn())) {
211 return null;
212 }
213
214 const url = organizationId
215 ? `ide/list-assistant-full-slugs?organizationId=${organizationId}`
216 : "ide/list-assistant-full-slugs";
217
218 try {
219 const resp = await this.requestAndHandleError(url, {
220 method: "GET",
221 });
222 const { fullSlugs } = (await resp.json()) as any;
223 return fullSlugs;
224 } catch (e) {
225 // Capture control plane API failures to Sentry
226 Logger.error(e, {
227 context: "control_plane_list_assistant_slugs",
228 organizationId,
229 });
230 return null;
231 }
232 }
233
234 public async getPolicy(): Promise<PolicyResponse | null> {
235 if (!(await this.isSignedIn())) {
236 return null;
237 }
238
239 try {
240 const resp = await this.request(`ide/policy`, {
241 method: "GET",
242 });
243 return (await resp.json()) as PolicyResponse;
244 } catch (e) {
245 return null;
246 }
247 }
248
249 public async getFreeTrialStatus(): Promise<FreeTrialStatus | null> {
250 if (!(await this.isSignedIn())) {
251 return null;
252 }
253
254 try {
255 const resp = await this.requestAndHandleError("ide/free-trial-status", {
256 method: "GET",
257 });
258 return (await resp.json()) as FreeTrialStatus;
259 } catch (e) {
260 // Capture control plane API failures to Sentry
261 Logger.error(e, {
262 context: "control_plane_free_trial_status",
263 });
264 return null;
265 }
266 }
267
268 /**
269 * JetBrains does not support deep links, so we only check for `vsCodeUriScheme`
270 * @param vsCodeUriScheme
271 * @returns
272 */
273 public async getModelsAddOnCheckoutUrl(
274 vsCodeUriScheme?: string,
275 ): Promise<{ url: string } | null> {
276 if (!(await this.isSignedIn())) {
277 return null;
278 }
279
280 try {
281 const params = new URLSearchParams({
282 // LocalProfileLoader ID
283 profile_id: "local",
284 });
285
286 if (vsCodeUriScheme) {
287 params.set("vscode_uri_scheme", vsCodeUriScheme);
288 }
289
290 const resp = await this.requestAndHandleError(
291 `ide/get-models-add-on-checkout-url?${params.toString()}`,
292 {
293 method: "GET",
294 },
295 );
296 return (await resp.json()) as { url: string };
297 } catch (e) {
298 // Capture control plane API failures to Sentry
299 Logger.error(e, {
300 context: "control_plane_models_checkout_url",
301 vsCodeUriScheme,
302 });
303 return null;
304 }
305 }
306}