| 1 | import { ConfigJson } from "@continuedev/config-types"; |
| 2 | import { |
| 3 | AssistantUnrolled, |
| 4 | ConfigResult, |
| 5 | FQSN, |
| 6 | FullSlug, |
| 7 | Policy, |
| 8 | SecretResult, |
| 9 | SecretType, |
| 10 | } from "@continuedev/config-yaml"; |
| 11 | import fetch, { RequestInit, Response } from "node-fetch"; |
| 12 | |
| 13 | import { OrganizationDescription } from "../config/ProfileLifecycleManager.js"; |
| 14 | import { |
| 15 | IDE, |
| 16 | ModelDescription, |
| 17 | Session, |
| 18 | BaseSessionMetadata, |
| 19 | } from "../index.js"; |
| 20 | import { Logger } from "../util/Logger.js"; |
| 21 | |
| 22 | import { |
| 23 | ControlPlaneSessionInfo, |
| 24 | HubSessionInfo, |
| 25 | isOnPremSession, |
| 26 | } from "./AuthTypes.js"; |
| 27 | import { getControlPlaneEnv } from "./env.js"; |
| 28 | |
| 29 | export interface PolicyResponse { |
| 30 | orgSlug?: string; |
| 31 | policy?: Policy; |
| 32 | } |
| 33 | |
| 34 | export interface ControlPlaneWorkspace { |
| 35 | id: string; |
| 36 | name: string; |
| 37 | settings: ConfigJson; |
| 38 | } |
| 39 | |
| 40 | export interface ControlPlaneModelDescription extends ModelDescription {} |
| 41 | |
| 42 | export interface FreeTrialStatus { |
| 43 | optedInToFreeTrial: boolean; |
| 44 | chatCount?: number; |
| 45 | autocompleteCount?: number; |
| 46 | chatLimit: number; |
| 47 | autocompleteLimit: number; |
| 48 | } |
| 49 | |
| 50 | export const TRIAL_PROXY_URL = |
| 51 | "https://proxy-server-blue-l6vsfbzhba-uw.a.run.app"; |
| 52 | |
| 53 | export interface RemoteSessionMetadata extends BaseSessionMetadata { |
| 54 | isRemote: true; |
| 55 | remoteId: string; |
| 56 | } |
| 57 | |
| 58 | export class ControlPlaneClient { |
| 59 | constructor( |
| 60 | readonly sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>, |
| 61 | private readonly ide: IDE, |
| 62 | ) {} |
| 63 | |
| 64 | async resolveFQSNs( |
| 65 | fqsns: FQSN[], |
| 66 | orgScopeId: string | null, |
| 67 | ): Promise<(SecretResult | undefined)[]> { |
| 68 | if (!(await this.isSignedIn())) { |
| 69 | return fqsns.map((fqsn) => ({ |
| 70 | found: false, |
| 71 | fqsn, |
| 72 | secretLocation: { |
| 73 | secretName: fqsn.secretName, |
| 74 | secretType: SecretType.NotFound, |
| 75 | }, |
| 76 | })); |
| 77 | } |
| 78 | |
| 79 | const resp = await this.requestAndHandleError("ide/sync-secrets", { |
| 80 | method: "POST", |
| 81 | body: JSON.stringify({ fqsns, orgScopeId }), |
| 82 | }); |
| 83 | return (await resp.json()) as any; |
| 84 | } |
| 85 | |
| 86 | async isSignedIn(): Promise<boolean> { |
| 87 | const sessionInfo = await this.sessionInfoPromise; |
| 88 | return !!sessionInfo; |
| 89 | } |
| 90 | |
| 91 | async getAccessToken(): Promise<string | undefined> { |
| 92 | const sessionInfo = await this.sessionInfoPromise; |
| 93 | return isOnPremSession(sessionInfo) ? undefined : sessionInfo?.accessToken; |
| 94 | } |
| 95 | |
| 96 | private async request(path: string, init: RequestInit): Promise<Response> { |
| 97 | const sessionInfo = await this.sessionInfoPromise; |
| 98 | const onPremSession = isOnPremSession(sessionInfo); |
| 99 | const accessToken = await this.getAccessToken(); |
| 100 | |
| 101 | // Bearer token not necessary for on-prem auth type |
| 102 | if (!accessToken && !onPremSession) { |
| 103 | throw new Error("No access token"); |
| 104 | } |
| 105 | |
| 106 | const env = await getControlPlaneEnv(this.ide.getIdeSettings()); |
| 107 | const url = new URL(path, env.CONTROL_PLANE_URL).toString(); |
| 108 | const ideInfo = await this.ide.getIdeInfo(); |
| 109 | |
| 110 | const resp = await fetch(url, { |
| 111 | ...init, |
| 112 | headers: { |
| 113 | ...init.headers, |
| 114 | Authorization: `Bearer ${accessToken}`, |
| 115 | ...{ |
| 116 | "x-extension-version": ideInfo.extensionVersion, |
| 117 | "x-is-prerelease": String(ideInfo.isPrerelease), |
| 118 | }, |
| 119 | }, |
| 120 | }); |
| 121 | |
| 122 | return resp; |
| 123 | } |
| 124 | |
| 125 | private async requestAndHandleError( |
| 126 | path: string, |
| 127 | init: RequestInit, |
| 128 | ): Promise<Response> { |
| 129 | const resp = await this.request(path, init); |
| 130 | |
| 131 | if (!resp.ok) { |
| 132 | throw new Error( |
| 133 | `Control plane request failed: ${resp.status} ${await resp.text()}`, |
| 134 | ); |
| 135 | } |
| 136 | |
| 137 | return resp; |
| 138 | } |
| 139 | |
| 140 | public async listAssistants(organizationId: string | null): Promise< |
| 141 | { |
| 142 | configResult: ConfigResult<AssistantUnrolled>; |
| 143 | ownerSlug: string; |
| 144 | packageSlug: string; |
| 145 | iconUrl: string; |
| 146 | rawYaml: string; |
| 147 | }[] |
| 148 | > { |
| 149 | if (!(await this.isSignedIn())) { |
| 150 | return []; |
| 151 | } |
| 152 | |
| 153 | try { |
| 154 | const url = organizationId |
| 155 | ? `ide/list-assistants?organizationId=${organizationId}` |
| 156 | : "ide/list-assistants"; |
| 157 | |
| 158 | const resp = await this.requestAndHandleError(url, { |
| 159 | method: "GET", |
| 160 | }); |
| 161 | return (await resp.json()) as any; |
| 162 | } catch (e) { |
| 163 | // Capture control plane API failures to Sentry |
| 164 | Logger.error(e, { |
| 165 | context: "control_plane_list_assistants", |
| 166 | organizationId, |
| 167 | }); |
| 168 | return []; |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | public async listOrganizations(): Promise<Array<OrganizationDescription>> { |
| 173 | if (!(await this.isSignedIn())) { |
| 174 | return []; |
| 175 | } |
| 176 | |
| 177 | // We try again here because when users sign up with an email domain that is |
| 178 | // captured by an org, we need to wait for the user account creation webhook to |
| 179 | // take effect. Otherwise the organization(s) won't show up. |
| 180 | // This error manifests as a 404 (user not found) |
| 181 | let retries = 0; |
| 182 | const maxRetries = 10; |
| 183 | const maxWaitTime = 20000; // 20 seconds in milliseconds |
| 184 | |
| 185 | while (retries < maxRetries) { |
| 186 | const resp = await this.request("ide/list-organizations", { |
| 187 | method: "GET", |
| 188 | }); |
| 189 | |
| 190 | if (resp.status === 404) { |
| 191 | retries++; |
| 192 | if (retries >= maxRetries) { |
| 193 | console.warn( |
| 194 | `Failed to list organizations after ${maxRetries} retries: user not found`, |
| 195 | ); |
| 196 | return []; |
| 197 | } |
| 198 | const waitTime = Math.min( |
| 199 | Math.pow(2, retries) * 100, |
| 200 | maxWaitTime / maxRetries, |
| 201 | ); |
| 202 | await new Promise((resolve) => setTimeout(resolve, waitTime)); |
| 203 | continue; |
| 204 | } else if (!resp.ok) { |
| 205 | console.warn( |
| 206 | `Failed to list organizations (${resp.status}): ${await resp.text()}`, |
| 207 | ); |
| 208 | return []; |
| 209 | } |
| 210 | const { organizations } = (await resp.json()) as any; |
| 211 | return organizations; |
| 212 | } |
| 213 | |
| 214 | // This should never be reached due to the while condition, but adding for safety |
| 215 | console.warn( |
| 216 | `Failed to list organizations after ${maxRetries} retries: maximum attempts exceeded`, |
| 217 | ); |
| 218 | return []; |
| 219 | } |
| 220 | |
| 221 | public async listAssistantFullSlugs( |
| 222 | organizationId: string | null, |
| 223 | ): Promise<FullSlug[] | null> { |
| 224 | if (!(await this.isSignedIn())) { |
| 225 | return null; |
| 226 | } |
| 227 | |
| 228 | const url = organizationId |
| 229 | ? `ide/list-assistant-full-slugs?organizationId=${organizationId}` |
| 230 | : "ide/list-assistant-full-slugs"; |
| 231 | |
| 232 | try { |
| 233 | const resp = await this.requestAndHandleError(url, { |
| 234 | method: "GET", |
| 235 | }); |
| 236 | const { fullSlugs } = (await resp.json()) as any; |
| 237 | return fullSlugs; |
| 238 | } catch (e) { |
| 239 | // Capture control plane API failures to Sentry |
| 240 | Logger.error(e, { |
| 241 | context: "control_plane_list_assistant_slugs", |
| 242 | organizationId, |
| 243 | }); |
| 244 | return null; |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | public async getPolicy(): Promise<PolicyResponse | null> { |
| 249 | if (!(await this.isSignedIn())) { |
| 250 | return null; |
| 251 | } |
| 252 | |
| 253 | try { |
| 254 | const resp = await this.request(`ide/policy`, { |
| 255 | method: "GET", |
| 256 | }); |
| 257 | return (await resp.json()) as PolicyResponse; |
| 258 | } catch (e) { |
| 259 | return null; |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | public async getFreeTrialStatus(): Promise<FreeTrialStatus | null> { |
| 264 | if (!(await this.isSignedIn())) { |
| 265 | return null; |
| 266 | } |
| 267 | |
| 268 | try { |
| 269 | const resp = await this.requestAndHandleError("ide/free-trial-status", { |
| 270 | method: "GET", |
| 271 | }); |
| 272 | return (await resp.json()) as FreeTrialStatus; |
| 273 | } catch (e) { |
| 274 | // Capture control plane API failures to Sentry |
| 275 | Logger.error(e, { |
| 276 | context: "control_plane_free_trial_status", |
| 277 | }); |
| 278 | return null; |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | /** |
| 283 | * JetBrains does not support deep links, so we only check for `vsCodeUriScheme` |
| 284 | * @param vsCodeUriScheme |
| 285 | * @returns |
| 286 | */ |
| 287 | public async getModelsAddOnCheckoutUrl( |
| 288 | vsCodeUriScheme?: string, |
| 289 | ): Promise<{ url: string } | null> { |
| 290 | if (!(await this.isSignedIn())) { |
| 291 | return null; |
| 292 | } |
| 293 | |
| 294 | try { |
| 295 | const params = new URLSearchParams({ |
| 296 | // LocalProfileLoader ID |
| 297 | profile_id: "local", |
| 298 | }); |
| 299 | |
| 300 | if (vsCodeUriScheme) { |
| 301 | params.set("vscode_uri_scheme", vsCodeUriScheme); |
| 302 | } |
| 303 | |
| 304 | const resp = await this.requestAndHandleError( |
| 305 | `ide/get-models-add-on-checkout-url?${params.toString()}`, |
| 306 | { |
| 307 | method: "GET", |
| 308 | }, |
| 309 | ); |
| 310 | return (await resp.json()) as { url: string }; |
| 311 | } catch (e) { |
| 312 | // Capture control plane API failures to Sentry |
| 313 | Logger.error(e, { |
| 314 | context: "control_plane_models_checkout_url", |
| 315 | vsCodeUriScheme, |
| 316 | }); |
| 317 | return null; |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | /** |
| 322 | * Check if remote sessions should be enabled based on feature flags |
| 323 | * Requires: PostHog feature flag AND @continue.dev email |
| 324 | */ |
| 325 | public async shouldEnableRemoteSessions(): Promise<boolean> { |
| 326 | // Check if user is signed in |
| 327 | if (!(await this.isSignedIn())) { |
| 328 | return false; |
| 329 | } |
| 330 | |
| 331 | // Check if user has @continue.dev email |
| 332 | try { |
| 333 | const sessionInfo = await this.sessionInfoPromise; |
| 334 | if (isOnPremSession(sessionInfo) || !sessionInfo) { |
| 335 | return false; |
| 336 | } |
| 337 | |
| 338 | const hubSession = sessionInfo as HubSessionInfo; |
| 339 | const email = hubSession.account?.id; |
| 340 | |
| 341 | return email ? email.includes("@continue.dev") : false; |
| 342 | } catch (e) { |
| 343 | Logger.error(e, { |
| 344 | context: "control_plane_check_remote_sessions_enabled", |
| 345 | }); |
| 346 | return false; |
| 347 | } |
| 348 | } |
| 349 | |
| 350 | /** |
| 351 | * Get current user's session info |
| 352 | */ |
| 353 | public async getSessionInfo(): Promise<ControlPlaneSessionInfo | undefined> { |
| 354 | return await this.sessionInfoPromise; |
| 355 | } |
| 356 | |
| 357 | /** |
| 358 | * Fetch remote agents/sessions from the control plane |
| 359 | * Currently restricted to @continue.dev emails for internal use |
| 360 | */ |
| 361 | public async listRemoteSessions(): Promise<RemoteSessionMetadata[]> { |
| 362 | if (!(await this.isSignedIn())) { |
| 363 | return []; |
| 364 | } |
| 365 | |
| 366 | try { |
| 367 | // Note: This endpoint is currently restricted to internal @continue.dev users |
| 368 | // In the future, this may be expanded to support broader remote session access |
| 369 | const resp = await this.requestAndHandleError("agents/devboxes", { |
| 370 | method: "GET", |
| 371 | }); |
| 372 | |
| 373 | const agents = (await resp.json()) as any[]; |
| 374 | |
| 375 | return agents.map( |
| 376 | (agent: any): RemoteSessionMetadata => ({ |
| 377 | sessionId: `remote-${agent.id}`, |
| 378 | title: agent.name || "Remote Agent", |
| 379 | dateCreated: new Date(agent.create_time_ms).toISOString(), |
| 380 | workspaceDirectory: "", |
| 381 | isRemote: true, |
| 382 | remoteId: agent.id, |
| 383 | }), |
| 384 | ); |
| 385 | } catch (e) { |
| 386 | // Log error but don't throw - remote sessions are optional |
| 387 | Logger.error(e, { |
| 388 | context: "control_plane_list_remote_sessions", |
| 389 | }); |
| 390 | return []; |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | public async loadRemoteSession(remoteId: string): Promise<Session> { |
| 395 | if (!(await this.isSignedIn())) { |
| 396 | throw new Error("Not signed in to load remote session"); |
| 397 | } |
| 398 | |
| 399 | try { |
| 400 | // First get the tunnel URL for the remote agent |
| 401 | const tunnelResp = await this.requestAndHandleError( |
| 402 | `agents/devboxes/${remoteId}/tunnel`, |
| 403 | { |
| 404 | method: "POST", |
| 405 | }, |
| 406 | ); |
| 407 | |
| 408 | const tunnelData = (await tunnelResp.json()) as { url?: string }; |
| 409 | const tunnelUrl = tunnelData.url; |
| 410 | |
| 411 | if (!tunnelUrl) { |
| 412 | throw new Error(`Failed to get tunnel URL for agent ${remoteId}`); |
| 413 | } |
| 414 | |
| 415 | // Now fetch the session state from the remote agent's /state endpoint |
| 416 | const stateResponse = await fetch(`${tunnelUrl}/state`); |
| 417 | if (!stateResponse.ok) { |
| 418 | throw new Error( |
| 419 | `Failed to fetch state from remote agent: ${stateResponse.statusText}`, |
| 420 | ); |
| 421 | } |
| 422 | |
| 423 | const remoteState = (await stateResponse.json()) as { session?: Session }; |
| 424 | |
| 425 | // The remote state contains a session property with the full session data |
| 426 | if (!remoteState.session) { |
| 427 | throw new Error( |
| 428 | "Remote agent returned invalid state - no session found", |
| 429 | ); |
| 430 | } |
| 431 | |
| 432 | return remoteState.session; |
| 433 | } catch (e) { |
| 434 | Logger.error(e, { |
| 435 | context: "control_plane_load_remote_session", |
| 436 | remoteId, |
| 437 | }); |
| 438 | throw new Error( |
| 439 | `Failed to load remote session: ${e instanceof Error ? e.message : "Unknown error"}`, |
| 440 | ); |
| 441 | } |
| 442 | } |
| 443 | } |