-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConfigManager.cs
More file actions
401 lines (349 loc) · 12.5 KB
/
Copy pathConfigManager.cs
File metadata and controls
401 lines (349 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using GitHub.Copilot;
using Newtonsoft.Json;
namespace AIPaste
{
public enum AIProvider
{
NotConfigured = 0,
GitHubCopilot = 1,
Custom = 2
}
public enum ThemeMode { System = 0, Light = 1, Dark = 2 }
public static class ConfigManager
{
private const string ConfigFileName = "config.json";
private static readonly byte[] entropy = Encoding.Unicode.GetBytes("AIPaste_Secret_Entropy");
// Persist config in a stable per-user location (%APPDATA%\AIPaste) so settings,
// custom actions and credentials survive app updates and single-file re-extraction.
// (For the portable build, BaseDirectory points at a volatile temp extraction folder.)
private static string AppDataDir =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "AIPaste");
private static string ConfigFilePath => Path.Combine(AppDataDir, ConfigFileName);
private static AppConfig? _config;
public static AppConfig GetConfig()
{
if (_config == null)
{
LoadConfig();
}
return _config ?? new AppConfig();
}
public static bool IsProviderConfigured()
{
var config = GetConfig();
return config.Provider != AIProvider.NotConfigured;
}
public static bool IsConfigComplete()
{
var config = GetConfig();
if (config.Provider == AIProvider.NotConfigured)
return false;
if (config.Provider == AIProvider.GitHubCopilot)
return true; // CLI auth is handled externally
if (config.Provider == AIProvider.Custom)
{
return !string.IsNullOrEmpty(GetCustomApiKey()) &&
!string.IsNullOrEmpty(config.CustomProvider.Endpoint) &&
!string.IsNullOrEmpty(config.CustomProvider.DeploymentId);
}
return false;
}
public static AIProvider GetProvider()
{
return GetConfig().Provider;
}
public static bool SetProvider(AIProvider provider)
{
try
{
var config = GetConfig();
config.Provider = provider;
SaveConfig();
return true;
}
catch
{
return false;
}
}
// Custom Provider methods
public static string GetCustomApiKey()
{
var config = GetConfig();
if (string.IsNullOrEmpty(config.CustomProvider.EncryptedApiKey))
{
return string.Empty;
}
try
{
byte[] encryptedData = Convert.FromBase64String(config.CustomProvider.EncryptedApiKey);
byte[] decryptedData = ProtectedData.Unprotect(encryptedData, entropy, DataProtectionScope.CurrentUser);
return Encoding.Unicode.GetString(decryptedData);
}
catch
{
return string.Empty;
}
}
public static string GetCustomEndpoint()
{
return GetConfig().CustomProvider.Endpoint;
}
public static string GetCustomDeploymentId()
{
return GetConfig().CustomProvider.DeploymentId;
}
public static bool SetCustomApiKey(string apiKey)
{
try
{
var config = GetConfig();
byte[] data = Encoding.Unicode.GetBytes(apiKey);
byte[] encrypted = ProtectedData.Protect(data, entropy, DataProtectionScope.CurrentUser);
config.CustomProvider.EncryptedApiKey = Convert.ToBase64String(encrypted);
SaveConfig();
return true;
}
catch
{
return false;
}
}
public static bool SetCustomEndpoint(string endpoint)
{
try
{
var config = GetConfig();
config.CustomProvider.Endpoint = endpoint;
SaveConfig();
return true;
}
catch
{
return false;
}
}
public static bool SetCustomDeploymentId(string deploymentId)
{
try
{
var config = GetConfig();
config.CustomProvider.DeploymentId = deploymentId;
SaveConfig();
return true;
}
catch
{
return false;
}
}
// GitHub Copilot methods
public static string GetCopilotPreferredModel()
{
return GetConfig().GitHubCopilot.PreferredModel;
}
public static bool SetCopilotPreferredModel(string model)
{
try
{
var config = GetConfig();
config.GitHubCopilot.PreferredModel = model;
SaveConfig();
return true;
}
catch
{
return false;
}
}
// Theme
public static ThemeMode GetThemeMode() => GetConfig().Theme;
public static bool SetThemeMode(ThemeMode mode)
{
try
{
var config = GetConfig();
config.Theme = mode;
SaveConfig();
return true;
}
catch
{
return false;
}
}
// Custom Actions
public static List<CustomAction> GetCustomActions()
{
return GetConfig().CustomActions;
}
public static bool SaveCustomAction(CustomAction action)
{
try
{
var config = GetConfig();
var existingAction = config.CustomActions.FirstOrDefault(a => a.Id == action.Id);
if (existingAction != null)
{
int index = config.CustomActions.IndexOf(existingAction);
config.CustomActions[index] = action;
}
else
{
if (string.IsNullOrEmpty(action.Id))
{
action.Id = Guid.NewGuid().ToString();
}
config.CustomActions.Add(action);
}
SaveConfig();
return true;
}
catch
{
return false;
}
}
public static bool DeleteCustomAction(string actionId)
{
try
{
var config = GetConfig();
var action = config.CustomActions.FirstOrDefault(a => a.Id == actionId);
if (action != null)
{
config.CustomActions.Remove(action);
SaveConfig();
}
return true;
}
catch
{
return false;
}
}
private static void LoadConfig()
{
if (File.Exists(ConfigFilePath))
{
try
{
string json = File.ReadAllText(ConfigFilePath);
_config = JsonConvert.DeserializeObject<AppConfig>(json) ?? new AppConfig();
return;
}
catch
{
// If loading fails, create a new config
}
}
_config = new AppConfig();
}
private static void SaveConfig()
{
Directory.CreateDirectory(AppDataDir);
string json = JsonConvert.SerializeObject(_config, Formatting.Indented);
File.WriteAllText(ConfigFilePath, json);
}
public static void ReloadConfig()
{
_config = null;
LoadConfig();
}
// Centralized Copilot SDK methods
private static List<ModelInfo>? _cachedModels;
private static DateTime _modelsCacheTime = DateTime.MinValue;
private static readonly TimeSpan ModelsCacheDuration = TimeSpan.FromMinutes(5);
public static async Task<List<ModelInfo>?> GetCopilotModelsAsync(bool forceRefresh = false)
{
// Return cached models if still valid
if (!forceRefresh && _cachedModels != null && DateTime.Now - _modelsCacheTime < ModelsCacheDuration)
{
return _cachedModels;
}
try
{
// Use singleton client manager
var models = await CopilotClientManager.Instance.ListModelsAsync();
if (models != null && models.Count > 0)
{
_cachedModels = models.ToList();
_modelsCacheTime = DateTime.Now;
return _cachedModels;
}
// No models returned - clear cache
_cachedModels = null;
return null;
}
catch
{
// Auth failed - clear cache and reset client
if (forceRefresh)
{
_cachedModels = null;
await CopilotClientManager.Instance.ResetAsync();
}
throw;
}
}
public static async Task<(bool IsAuthenticated, string Message)> CheckCopilotAuthAsync()
{
try
{
var models = await GetCopilotModelsAsync(forceRefresh: true);
if (models != null && models.Count > 0)
{
return (true, "Authenticated!");
}
return (false, "No models available. Please login first.\nRun 'copilot' and type /login");
}
catch (Exception ex)
{
string errorMsg = ex.Message.ToLower();
if (errorMsg.Contains("not found") || errorMsg.Contains("cannot find") || errorMsg.Contains("not recognized"))
{
return (false, "Copilot CLI not found.\nInstall: winget install GitHub.Copilot");
}
else if (errorMsg.Contains("auth") || errorMsg.Contains("login") || errorMsg.Contains("unauthorized"))
{
return (false, "Not authenticated.\nRun 'copilot' and type /login");
}
return (false, $"Error: {ex.Message}");
}
}
}
public class AppConfig
{
public AIProvider Provider { get; set; } = AIProvider.NotConfigured;
public ThemeMode Theme { get; set; } = ThemeMode.System;
public GitHubCopilotConfig GitHubCopilot { get; set; } = new GitHubCopilotConfig();
public CustomProviderConfig CustomProvider { get; set; } = new CustomProviderConfig();
public List<CustomAction> CustomActions { get; set; } = new List<CustomAction>();
}
public class GitHubCopilotConfig
{
public string PreferredModel { get; set; } = "gpt-4o";
/// <summary>
/// Optional absolute path to a copilot.exe. When empty, CliPathResolver
/// auto-discovers one from PATH / winget / npm-global. Set this to pin a
/// specific install if multiple copies exist on the machine.
/// </summary>
public string CliPathOverride { get; set; } = string.Empty;
}
public class CustomProviderConfig
{
public string EncryptedApiKey { get; set; } = string.Empty;
public string Endpoint { get; set; } = string.Empty;
public string DeploymentId { get; set; } = string.Empty;
}
public class CustomAction
{
public string Id { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public string Prompt { get; set; } = string.Empty;
}
}