Elffuss BraidHub

kikocis/continue public

94f7b85f6068 · 5.6 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 showConfigUpdateToast: boolean;
43 isSupportedLanceDbCpuTargetForLinux: boolean;
44 sharedConfig: SharedConfigSchema;
45 failedDocs: SiteIndexingConfig[];
46 shownDeprecatedProviderWarnings: {
47 [providerTitle: string]: boolean;
48 };
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 */
61export 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(
69 filepath,
70 JSON.stringify(
71 {
72 [key]: value,
73 },
74 null,
75 2,
76 ),
77 );
78 } else {
79 const data = fs.readFileSync(filepath, "utf-8");
80
81 let parsed;
82 try {
83 parsed = JSON.parse(data);
84 } catch (e: any) {
85 console.warn(
86 `Error updating global context, attempting to salvage security-sensitive values: ${e}`,
87 );
88
89 // Attempt to salvage security-sensitive values before deleting
90 let salvaged: Partial<GlobalContextType> = {};
91 try {
92 // Try to partially parse the corrupted data to extract sharedConfig
93 const match = data.match(/"sharedConfig"\s*:\s*({[^}]*})/);
94 if (match) {
95 const sharedConfigObj = JSON.parse(match[1]);
96 const salvagedSharedConfig = salvageSharedConfig(sharedConfigObj);
97 if (Object.keys(salvagedSharedConfig).length > 0) {
98 salvaged.sharedConfig = salvagedSharedConfig;
99 }
100 }
101 } catch {
102 // If salvage fails, continue with empty salvaged object
103 }
104
105 // Delete the corrupted file and recreate it fresh
106 try {
107 fs.unlinkSync(filepath);
108 } catch (deleteError) {
109 console.warn(
110 `Error deleting corrupted global context file: ${deleteError}`,
111 );
112 }
113
114 // Recreate the file with salvaged values plus the new value
115 const newData = {
116 ...salvaged,
117 [key]: value,
118 };
119
120 fs.writeFileSync(filepath, JSON.stringify(newData, null, 2));
121 return;
122 }
123
124 parsed[key] = value;
125 fs.writeFileSync(filepath, JSON.stringify(parsed, null, 2));
126 }
127 }
128
129 get<T extends keyof GlobalContextType>(
130 key: T,
131 ): GlobalContextType[T] | undefined {
132 const filepath = getGlobalContextFilePath();
133 if (!fs.existsSync(filepath)) {
134 return undefined;
135 }
136
137 const data = fs.readFileSync(filepath, "utf-8");
138 try {
139 const parsed = JSON.parse(data);
140 return parsed[key];
141 } catch (e: any) {
142 console.warn(
143 `Error parsing global context, deleting corrupted file: ${e}`,
144 );
145 // Delete the corrupted file so it can be recreated fresh
146 try {
147 fs.unlinkSync(filepath);
148 } catch (deleteError) {
149 console.warn(
150 `Error deleting corrupted global context file: ${deleteError}`,
151 );
152 }
153 return undefined;
154 }
155 }
156
157 getSharedConfig(): SharedConfigSchema {
158 const sharedConfig = this.get("sharedConfig") ?? {};
159 const result = sharedConfigSchema.safeParse(sharedConfig);
160 if (result.success) {
161 return result.data;
162 } else {
163 // in case of damaged shared config, repair it
164 // Attempt to salvage any values that are security concerns
165 console.error("Failed to load shared config, salvaging...", result.error);
166 const salvagedConfig = salvageSharedConfig(sharedConfig);
167 this.update("sharedConfig", salvagedConfig);
168 return salvagedConfig;
169 }
170 }
171
172 updateSharedConfig(
173 newValues: Partial<SharedConfigSchema>,
174 ): SharedConfigSchema {
175 const currentSharedConfig = this.getSharedConfig();
176 const updatedSharedConfig = {
177 ...currentSharedConfig,
178 ...newValues,
179 };
180 this.update("sharedConfig", updatedSharedConfig);
181 return updatedSharedConfig;
182 }
183
184 updateSelectedModel(
185 profileId: string,
186 role: ModelRole,
187 title: string | null,
188 ): GlobalContextModelSelections {
189 const currentSelections = this.get("selectedModelsByProfileId") ?? {};
190 const forProfile = currentSelections[profileId] ?? {};
191 const newSelections = {
192 ...forProfile,
193 [role]: title,
194 };
195
196 this.update("selectedModelsByProfileId", {
197 ...currentSelections,
198 [profileId]: newSelections,
199 });
200 return newSelections;
201 }
202}