Elffuss BraidHub

kikocis/continue public

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