Elffuss BraidHub

kikocis/continue public

f433400a74a4 · 4.9 KiBRawPermalink
1import fs from "node:fs";
2
3import { ModelRole } from "@continuedev/config-yaml";
4
5import { SiteIndexingConfig } from "..";
6import {
7 salvageSharedConfig,
8 sharedConfigSchema,
9 SharedConfigSchema,
10} from "../config/sharedConfig";
11
12import {
13 OAuthClientInformationFull,
14 OAuthTokens,
15} from "@modelcontextprotocol/sdk/shared/auth.js";
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 mcpOauthStorage: Record<
47 string,
48 {
49 clientInformation?: OAuthClientInformationFull;
50 tokens?: OAuthTokens;
51 codeVerifier?: string;
52 }
53 >;
54 shownDeprecatedProviderWarnings: {
55 [providerTitle: string]: boolean;
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, deleting corrupted file: ${e}`,
88 );
89 // Delete the corrupted file and recreate it fresh
90 try {
91 fs.unlinkSync(filepath);
92 } catch (deleteError) {
93 console.warn(
94 `Error deleting corrupted global context file: ${deleteError}`,
95 );
96 }
97 // Recreate the file with just the new value
98 fs.writeFileSync(
99 filepath,
100 JSON.stringify(
101 {
102 [key]: value,
103 },
104 null,
105 2,
106 ),
107 );
108 return;
109 }
110
111 parsed[key] = value;
112 fs.writeFileSync(filepath, JSON.stringify(parsed, null, 2));
113 }
114 }
115
116 get<T extends keyof GlobalContextType>(
117 key: T,
118 ): GlobalContextType[T] | undefined {
119 const filepath = getGlobalContextFilePath();
120 if (!fs.existsSync(filepath)) {
121 return undefined;
122 }
123
124 const data = fs.readFileSync(filepath, "utf-8");
125 try {
126 const parsed = JSON.parse(data);
127 return parsed[key];
128 } catch (e: any) {
129 console.warn(
130 `Error parsing global context, deleting corrupted file: ${e}`,
131 );
132 // Delete the corrupted file so it can be recreated fresh
133 try {
134 fs.unlinkSync(filepath);
135 } catch (deleteError) {
136 console.warn(
137 `Error deleting corrupted global context file: ${deleteError}`,
138 );
139 }
140 return undefined;
141 }
142 }
143
144 getSharedConfig(): SharedConfigSchema {
145 const sharedConfig = this.get("sharedConfig") ?? {};
146 const result = sharedConfigSchema.safeParse(sharedConfig);
147 if (result.success) {
148 return result.data;
149 } else {
150 // in case of damaged shared config, repair it
151 // Attempt to salvage any values that are security concerns
152 console.error("Failed to load shared config, salvaging...", result.error);
153 const salvagedConfig = salvageSharedConfig(sharedConfig);
154 this.update("sharedConfig", salvagedConfig);
155 return salvagedConfig;
156 }
157 }
158
159 updateSharedConfig(
160 newValues: Partial<SharedConfigSchema>,
161 ): SharedConfigSchema {
162 const currentSharedConfig = this.getSharedConfig();
163 const updatedSharedConfig = {
164 ...currentSharedConfig,
165 ...newValues,
166 };
167 this.update("sharedConfig", updatedSharedConfig);
168 return updatedSharedConfig;
169 }
170
171 updateSelectedModel(
172 profileId: string,
173 role: ModelRole,
174 title: string | null,
175 ): GlobalContextModelSelections {
176 const currentSelections = this.get("selectedModelsByProfileId") ?? {};
177 const forProfile = currentSelections[profileId] ?? {};
178 const newSelections = {
179 ...forProfile,
180 [role]: title,
181 };
182
183 this.update("selectedModelsByProfileId", {
184 ...currentSelections,
185 [profileId]: newSelections,
186 });
187 return newSelections;
188 }
189}