Elffuss BraidHub

kikocis/continue public

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