Elffuss BraidHub

kikocis/continue public

9c134d8c1202 · 5.7 KiBRawPermalink
1import fs from "node:fs";
2
3import { ModelRole } from "@continuedev/config-yaml";
4import {
5 OAuthClientInformationFull,
6 OAuthTokens,
7} from "@modelcontextprotocol/sdk/shared/auth.js";
8
9import { SiteIndexingConfig } from "..";
10import {
11 salvageSharedConfig,
12 sharedConfigSchema,
13 SharedConfigSchema,
14} from "../config/sharedConfig";
15
16import { getGlobalContextFilePath } from "./paths";
17
18export type GlobalContextModelSelections = Partial<
19 Record<ModelRole, string | null>
20>;
21
22export 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: {
48 [providerTitle: string]: boolean;
49 };
50 mcpOauthStorage: {
51 [serverUrl: string]: {
52 clientInformation?: OAuthClientInformationFull;
53 tokens?: OAuthTokens;
54 codeVerifier?: string;
55 };
56 };
57};
58
59/**
60 * A way to persist global state
61 */
62export class GlobalContext {
63 update<T extends keyof GlobalContextType>(
64 key: T,
65 value: GlobalContextType[T],
66 ) {
67 const filepath = getGlobalContextFilePath();
68 if (!fs.existsSync(filepath)) {
69 fs.writeFileSync(
70 filepath,
71 JSON.stringify(
72 {
73 [key]: value,
74 },
75 null,
76 2,
77 ),
78 );
79 } else {
80 const data = fs.readFileSync(filepath, "utf-8");
81
82 let parsed;
83 try {
84 parsed = JSON.parse(data);
85 } catch (e: any) {
86 console.warn(
87 `Error updating global context, attempting to salvage security-sensitive values: ${e}`,
88 );
89
90 // Attempt to salvage security-sensitive values before deleting
91 let salvaged: Partial<GlobalContextType> = {};
92 try {
93 // Try to partially parse the corrupted data to extract sharedConfig
94 const match = data.match(/"sharedConfig"\s*:\s*({[^}]*})/);
95 if (match) {
96 const sharedConfigObj = JSON.parse(match[1]);
97 const salvagedSharedConfig = salvageSharedConfig(sharedConfigObj);
98 if (Object.keys(salvagedSharedConfig).length > 0) {
99 salvaged.sharedConfig = salvagedSharedConfig;
100 }
101 }
102 } catch {
103 // If salvage fails, continue with empty salvaged object
104 }
105
106 // Delete the corrupted file and recreate it fresh
107 try {
108 fs.unlinkSync(filepath);
109 } catch (deleteError) {
110 console.warn(
111 `Error deleting corrupted global context file: ${deleteError}`,
112 );
113 }
114
115 // Recreate the file with salvaged values plus the new value
116 const newData = {
117 ...salvaged,
118 [key]: value,
119 };
120
121 fs.writeFileSync(filepath, JSON.stringify(newData, null, 2));
122 return;
123 }
124
125 parsed[key] = value;
126 fs.writeFileSync(filepath, JSON.stringify(parsed, null, 2));
127 }
128 }
129
130 get<T extends keyof GlobalContextType>(
131 key: T,
132 ): GlobalContextType[T] | undefined {
133 const filepath = getGlobalContextFilePath();
134 if (!fs.existsSync(filepath)) {
135 return undefined;
136 }
137
138 const data = fs.readFileSync(filepath, "utf-8");
139 try {
140 const parsed = JSON.parse(data);
141 return parsed[key];
142 } catch (e: any) {
143 console.warn(
144 `Error parsing global context, deleting corrupted file: ${e}`,
145 );
146 // Delete the corrupted file so it can be recreated fresh
147 try {
148 fs.unlinkSync(filepath);
149 } catch (deleteError) {
150 console.warn(
151 `Error deleting corrupted global context file: ${deleteError}`,
152 );
153 }
154 return undefined;
155 }
156 }
157
158 getSharedConfig(): SharedConfigSchema {
159 const sharedConfig = this.get("sharedConfig") ?? {};
160 const result = sharedConfigSchema.safeParse(sharedConfig);
161 if (result.success) {
162 return result.data;
163 } else {
164 // in case of damaged shared config, repair it
165 // Attempt to salvage any values that are security concerns
166 console.error("Failed to load shared config, salvaging...", result.error);
167 const salvagedConfig = salvageSharedConfig(sharedConfig);
168 this.update("sharedConfig", salvagedConfig);
169 return salvagedConfig;
170 }
171 }
172
173 updateSharedConfig(
174 newValues: Partial<SharedConfigSchema>,
175 ): SharedConfigSchema {
176 const currentSharedConfig = this.getSharedConfig();
177 const updatedSharedConfig = {
178 ...currentSharedConfig,
179 ...newValues,
180 };
181 this.update("sharedConfig", updatedSharedConfig);
182 return updatedSharedConfig;
183 }
184
185 updateSelectedModel(
186 profileId: string,
187 role: ModelRole,
188 title: string | null,
189 ): GlobalContextModelSelections {
190 const currentSelections = this.get("selectedModelsByProfileId") ?? {};
191 const forProfile = currentSelections[profileId] ?? {};
192 const newSelections = {
193 ...forProfile,
194 [role]: title,
195 };
196
197 this.update("selectedModelsByProfileId", {
198 ...currentSelections,
199 [profileId]: newSelections,
200 });
201 return newSelections;
202 }
203}