| 1 | import fs from "node:fs"; |
| 2 | |
| 3 | import { ModelRole } from "@continuedev/config-yaml"; |
| 4 | import { |
| 5 | OAuthClientInformationFull, |
| 6 | OAuthTokens, |
| 7 | } from "@modelcontextprotocol/sdk/shared/auth.js"; |
| 8 | |
| 9 | import { SiteIndexingConfig } from ".."; |
| 10 | import { |
| 11 | salvageSharedConfig, |
| 12 | sharedConfigSchema, |
| 13 | SharedConfigSchema, |
| 14 | } from "../config/sharedConfig"; |
| 15 | |
| 16 | import { getGlobalContextFilePath } from "./paths"; |
| 17 | |
| 18 | export type GlobalContextModelSelections = Partial< |
| 19 | Record<ModelRole, string | null> |
| 20 | >; |
| 21 | |
| 22 | export type GlobalContextType = { |
| 23 | indexingPaused: boolean; |
| 24 | lastSelectedProfileForWorkspace: { |
| 25 | [workspaceIdentifier: string]: string | null; |
| 26 | }; |
| 27 | lastSelectedOrgIdForWorkspace: { |
| 28 | [workspaceIdentifier: string]: string | null; |
| 29 | }; |
| 30 | selectedModelsByProfileId: { |
| 31 | [profileId: string]: GlobalContextModelSelections; |
| 32 | }; |
| 33 | |
| 34 | /** |
| 35 | * This is needed to handle the case where a JetBrains user has created |
| 36 | * docs embeddings using one provider, and then updates to a new provider. |
| 37 | * |
| 38 | * For VS Code users, it is unnecessary since we use transformers.js by default. |
| 39 | */ |
| 40 | hasDismissedConfigTsNoticeJetBrains: boolean; |
| 41 | hasAlreadyCreatedAPromptFile: boolean; |
| 42 | hasShownUnsupportedPlatformWarning: boolean; |
| 43 | showConfigUpdateToast: boolean; |
| 44 | isSupportedLanceDbCpuTargetForLinux: boolean; |
| 45 | sharedConfig: SharedConfigSchema; |
| 46 | failedDocs: SiteIndexingConfig[]; |
| 47 | shownDeprecatedProviderWarnings: { [providerTitle: string]: boolean }; |
| 48 | autoUpdateCli: boolean; |
| 49 | mcpOauthStorage: { |
| 50 | [serverUrl: string]: { |
| 51 | clientInformation?: OAuthClientInformationFull; |
| 52 | tokens?: OAuthTokens; |
| 53 | codeVerifier?: string; |
| 54 | }; |
| 55 | }; |
| 56 | }; |
| 57 | |
| 58 | /** |
| 59 | * A way to persist global state |
| 60 | */ |
| 61 | export class GlobalContext { |
| 62 | update<T extends keyof GlobalContextType>( |
| 63 | key: T, |
| 64 | value: GlobalContextType[T], |
| 65 | ) { |
| 66 | const filepath = getGlobalContextFilePath(); |
| 67 | if (!fs.existsSync(filepath)) { |
| 68 | fs.writeFileSync(filepath, JSON.stringify({ [key]: value }, null, 2)); |
| 69 | } else { |
| 70 | const data = fs.readFileSync(filepath, "utf-8"); |
| 71 | |
| 72 | let parsed; |
| 73 | try { |
| 74 | parsed = JSON.parse(data); |
| 75 | } catch (e: any) { |
| 76 | console.warn( |
| 77 | `Error updating global context, attempting to salvage security-sensitive values: ${e}`, |
| 78 | ); |
| 79 | |
| 80 | // Attempt to salvage security-sensitive values before deleting |
| 81 | let salvaged: Partial<GlobalContextType> = {}; |
| 82 | try { |
| 83 | // Try to partially parse the corrupted data to extract sharedConfig |
| 84 | const match = data.match(/"sharedConfig"\s*:\s*({[^}]*})/); |
| 85 | if (match) { |
| 86 | const sharedConfigObj = JSON.parse(match[1]); |
| 87 | const salvagedSharedConfig = salvageSharedConfig(sharedConfigObj); |
| 88 | if (Object.keys(salvagedSharedConfig).length > 0) { |
| 89 | salvaged.sharedConfig = salvagedSharedConfig; |
| 90 | } |
| 91 | } |
| 92 | } catch { |
| 93 | // If salvage fails, continue with empty salvaged object |
| 94 | } |
| 95 | |
| 96 | // Delete the corrupted file and recreate it fresh |
| 97 | try { |
| 98 | fs.unlinkSync(filepath); |
| 99 | } catch (deleteError) { |
| 100 | console.warn( |
| 101 | `Error deleting corrupted global context file: ${deleteError}`, |
| 102 | ); |
| 103 | } |
| 104 | |
| 105 | // Recreate the file with salvaged values plus the new value |
| 106 | const newData = { ...salvaged, [key]: value }; |
| 107 | |
| 108 | fs.writeFileSync(filepath, JSON.stringify(newData, null, 2)); |
| 109 | return; |
| 110 | } |
| 111 | |
| 112 | parsed[key] = value; |
| 113 | fs.writeFileSync(filepath, JSON.stringify(parsed, null, 2)); |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | get<T extends keyof GlobalContextType>( |
| 118 | key: T, |
| 119 | ): GlobalContextType[T] | undefined { |
| 120 | const filepath = getGlobalContextFilePath(); |
| 121 | if (!fs.existsSync(filepath)) { |
| 122 | return undefined; |
| 123 | } |
| 124 | |
| 125 | const data = fs.readFileSync(filepath, "utf-8"); |
| 126 | try { |
| 127 | const parsed = JSON.parse(data); |
| 128 | return parsed[key]; |
| 129 | } catch (e: any) { |
| 130 | console.warn( |
| 131 | `Error parsing global context, deleting corrupted file: ${e}`, |
| 132 | ); |
| 133 | // Delete the corrupted file so it can be recreated fresh |
| 134 | try { |
| 135 | fs.unlinkSync(filepath); |
| 136 | } catch (deleteError) { |
| 137 | console.warn( |
| 138 | `Error deleting corrupted global context file: ${deleteError}`, |
| 139 | ); |
| 140 | } |
| 141 | return undefined; |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | getSharedConfig(): SharedConfigSchema { |
| 146 | const sharedConfig = this.get("sharedConfig") ?? {}; |
| 147 | const result = sharedConfigSchema.safeParse(sharedConfig); |
| 148 | if (result.success) { |
| 149 | return result.data; |
| 150 | } else { |
| 151 | // in case of damaged shared config, repair it |
| 152 | // Attempt to salvage any values that are security concerns |
| 153 | console.error("Failed to load shared config, salvaging...", result.error); |
| 154 | const salvagedConfig = salvageSharedConfig(sharedConfig); |
| 155 | this.update("sharedConfig", salvagedConfig); |
| 156 | return salvagedConfig; |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | updateSharedConfig( |
| 161 | newValues: Partial<SharedConfigSchema>, |
| 162 | ): SharedConfigSchema { |
| 163 | const currentSharedConfig = this.getSharedConfig(); |
| 164 | const updatedSharedConfig = { ...currentSharedConfig, ...newValues }; |
| 165 | this.update("sharedConfig", updatedSharedConfig); |
| 166 | return updatedSharedConfig; |
| 167 | } |
| 168 | |
| 169 | updateSelectedModel( |
| 170 | profileId: string, |
| 171 | role: ModelRole, |
| 172 | title: string | null, |
| 173 | ): GlobalContextModelSelections { |
| 174 | const currentSelections = this.get("selectedModelsByProfileId") ?? {}; |
| 175 | const forProfile = currentSelections[profileId] ?? {}; |
| 176 | const newSelections = { ...forProfile, [role]: title }; |
| 177 | |
| 178 | this.update("selectedModelsByProfileId", { |
| 179 | ...currentSelections, |
| 180 | [profileId]: newSelections, |
| 181 | }); |
| 182 | return newSelections; |
| 183 | } |
| 184 | } |