Elffuss BraidHub

kikocis/continue public

80ffc97db92a · 7.5 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";
15
16import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js";
17import { getControlPlaneEnv } from "./env.js";
18
19export interface PolicyResponse {
20 orgSlug?: string;
21 policy?: Policy;
22}
23
24export interface ControlPlaneWorkspace {
25 id: string;
26 name: string;
27 settings: ConfigJson;
28}
29
30export interface ControlPlaneModelDescription extends ModelDescription {}
31
32export interface FreeTrialStatus {
33 optedInToFreeTrial: boolean;
34 chatCount?: number;
35 autocompleteCount?: number;
36 chatLimit: number;
37 autocompleteLimit: number;
38}
39
40export const TRIAL_PROXY_URL =
41 "https://proxy-server-blue-l6vsfbzhba-uw.a.run.app";
42
43export class ControlPlaneClient {
44 constructor(
45 readonly sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
46 private readonly ideSettingsPromise: Promise<IdeSettings>,
47 private readonly ideInfoPromise: Promise<IdeInfo>,
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.ideSettingsPromise);
93 const url = new URL(path, env.CONTROL_PLANE_URL).toString();
94 const ideInfo = await this.ideInfoPromise;
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 return [];
150 }
151 }
152
153 public async listOrganizations(): Promise<Array<OrganizationDescription>> {
154 if (!(await this.isSignedIn())) {
155 return [];
156 }
157
158 // We try again here because when users sign up with an email domain that is
159 // captured by an org, we need to wait for the user account creation webhook to
160 // take effect. Otherwise the organization(s) won't show up.
161 // This error manifests as a 404 (user not found)
162 let retries = 0;
163 const maxRetries = 10;
164 const maxWaitTime = 20000; // 20 seconds in milliseconds
165
166 while (retries < maxRetries) {
167 const resp = await this.request("ide/list-organizations", {
168 method: "GET",
169 });
170
171 if (resp.status === 404) {
172 retries++;
173 if (retries >= maxRetries) {
174 console.warn(
175 `Failed to list organizations after ${maxRetries} retries: user not found`,
176 );
177 return [];
178 }
179 const waitTime = Math.min(
180 Math.pow(2, retries) * 100,
181 maxWaitTime / maxRetries,
182 );
183 await new Promise((resolve) => setTimeout(resolve, waitTime));
184 continue;
185 } else if (!resp.ok) {
186 console.warn(
187 `Failed to list organizations (${resp.status}): ${await resp.text()}`,
188 );
189 return [];
190 }
191 const { organizations } = (await resp.json()) as any;
192 return organizations;
193 }
194
195 // This should never be reached due to the while condition, but adding for safety
196 console.warn(
197 `Failed to list organizations after ${maxRetries} retries: maximum attempts exceeded`,
198 );
199 return [];
200 }
201
202 public async listAssistantFullSlugs(
203 organizationId: string | null,
204 ): Promise<FullSlug[] | null> {
205 if (!(await this.isSignedIn())) {
206 return null;
207 }
208
209 const url = organizationId
210 ? `ide/list-assistant-full-slugs?organizationId=${organizationId}`
211 : "ide/list-assistant-full-slugs";
212
213 try {
214 const resp = await this.requestAndHandleError(url, {
215 method: "GET",
216 });
217 const { fullSlugs } = (await resp.json()) as any;
218 return fullSlugs;
219 } catch (e) {
220 return null;
221 }
222 }
223
224 public async getPolicy(): Promise<PolicyResponse | null> {
225 if (!(await this.isSignedIn())) {
226 return null;
227 }
228
229 try {
230 const resp = await this.request(`ide/policy`, {
231 method: "GET",
232 });
233 return (await resp.json()) as PolicyResponse;
234 } catch (e) {
235 return null;
236 }
237 }
238
239 public async getFreeTrialStatus(): Promise<FreeTrialStatus | null> {
240 if (!(await this.isSignedIn())) {
241 return null;
242 }
243
244 try {
245 const resp = await this.requestAndHandleError("ide/free-trial-status", {
246 method: "GET",
247 });
248 return (await resp.json()) as FreeTrialStatus;
249 } catch (e) {
250 return null;
251 }
252 }
253
254 /**
255 * JetBrains does not support deep links, so we only check for `vsCodeUriScheme`
256 * @param vsCodeUriScheme
257 * @returns
258 */
259 public async getModelsAddOnCheckoutUrl(
260 vsCodeUriScheme?: string,
261 ): Promise<{ url: string } | null> {
262 if (!(await this.isSignedIn())) {
263 return null;
264 }
265
266 try {
267 const params = new URLSearchParams({
268 // LocalProfileLoader ID
269 profile_id: "local",
270 });
271
272 if (vsCodeUriScheme) {
273 params.set("vscode_uri_scheme", vsCodeUriScheme);
274 }
275
276 const resp = await this.requestAndHandleError(
277 `ide/get-models-add-on-checkout-url?${params.toString()}`,
278 {
279 method: "GET",
280 },
281 );
282 return (await resp.json()) as { url: string };
283 } catch (e) {
284 return null;
285 }
286 }
287}