-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathconfig.js
More file actions
214 lines (183 loc) · 6.65 KB
/
config.js
File metadata and controls
214 lines (183 loc) · 6.65 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
import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, writeSync } from 'node:fs';
import os from 'node:os';
import { dirname } from 'node:path';
export const DEFAULT_MODELS = Object.freeze(['deepseek-v4-pro', 'deepseek-v4-flash']);
export const DEFAULT_UPSTREAM_BASE_URL = 'https://api.deepseek.com/anthropic';
export const DEFAULT_CONFIG_PATH = `${os.homedir()}/Library/Application Support/CoworkSwitch/config.json`;
export const DEFAULT_OPENROUTER_BASE_URL = 'https://openrouter.ai/api';
export function parseModelIds(value) {
if (!value) {
return [...DEFAULT_MODELS];
}
return value
.split(',')
.map((model) => model.trim())
.filter(Boolean);
}
function normalizeBaseUrl(value, fallback) {
const candidate = typeof value === 'string' && value.trim() ? value.trim() : fallback;
return candidate.endsWith('/') ? candidate.slice(0, -1) : candidate;
}
function normalizeProviderKind(value) {
const candidate = typeof value === 'string' ? value.trim().toLowerCase() : '';
if (candidate === 'deepseek' || candidate === 'openrouter') {
return candidate;
}
return 'generic';
}
function normalizeProviderId(value, index) {
const candidate = typeof value === 'string' && value.trim() ? value.trim() : `provider-${index + 1}`;
return candidate
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '') || `provider-${index + 1}`;
}
function createLegacyProvider(env) {
return {
id: 'deepseek',
name: 'DeepSeek',
providerKind: 'deepseek',
baseUrl: normalizeBaseUrl(env.DEEPSEEK_ANTHROPIC_BASE_URL, DEFAULT_UPSTREAM_BASE_URL),
apiKey: env.DEEPSEEK_API_KEY ?? env.ANTHROPIC_AUTH_TOKEN ?? '',
useFakeModels: true,
fakeModels: parseModelIds(env.DEEPSEEK_MODELS),
};
}
function createOpenRouterProvider() {
return {
id: 'openrouter',
name: 'OpenRouter',
providerKind: 'openrouter',
baseUrl: DEFAULT_OPENROUTER_BASE_URL,
apiKey: '',
useFakeModels: false,
fakeModels: [],
};
}
function normalizeProvider(provider, index, env) {
const legacyProvider = createLegacyProvider(env);
const baseProvider = provider && typeof provider === 'object' ? provider : {};
const providerKind = normalizeProviderKind(baseProvider.providerKind);
const presetProvider = providerKind === 'deepseek' ? legacyProvider : providerKind === 'openrouter' ? createOpenRouterProvider() : null;
const hasExplicitFakeModels = Object.prototype.hasOwnProperty.call(baseProvider, 'fakeModels');
const fakeModels = Array.isArray(baseProvider.fakeModels)
? baseProvider.fakeModels.map((model) => String(model).trim()).filter(Boolean)
: hasExplicitFakeModels
? String(baseProvider.fakeModels ?? '')
.split(',')
.map((model) => model.trim())
.filter(Boolean)
: [...(presetProvider?.fakeModels ?? legacyProvider.fakeModels)];
const fallbackProvider = presetProvider ?? legacyProvider;
return {
id: normalizeProviderId(baseProvider.id, index),
providerKind,
name:
typeof baseProvider.name === 'string' && baseProvider.name.trim()
? baseProvider.name.trim()
: fallbackProvider.name,
baseUrl: normalizeBaseUrl(baseProvider.baseUrl, fallbackProvider.baseUrl),
apiKey: typeof baseProvider.apiKey === 'string' ? baseProvider.apiKey : '',
useFakeModels:
typeof baseProvider.useFakeModels === 'boolean' ? baseProvider.useFakeModels : fallbackProvider.useFakeModels,
fakeModels,
};
}
function createProviders(input, env) {
if (Array.isArray(input?.providers) && input.providers.length > 0) {
return input.providers.map((provider, index) => normalizeProvider(provider, index, env));
}
if (input?.provider && typeof input.provider === 'object') {
return [normalizeProvider(input.provider, 0, env)];
}
if (input?.upstreamBaseUrl || input?.models || input?.apiKey) {
return [
normalizeProvider(
{
id: 'legacy',
name: 'Legacy Provider',
baseUrl: input.upstreamBaseUrl,
apiKey: input.apiKey ?? '',
useFakeModels: true,
fakeModels: input.models ?? parseModelIds(env.DEEPSEEK_MODELS),
},
0,
env,
),
];
}
return [createLegacyProvider(env)];
}
export function normalizeGatewayConfig(input = {}, env = process.env) {
const providers = createProviders(input, env);
const fallbackProviderId = providers[0]?.id ?? 'deepseek';
const activeProviderId =
typeof input.activeProviderId === 'string' && providers.some((provider) => provider.id === input.activeProviderId)
? input.activeProviderId
: fallbackProviderId;
const portCandidate = Number.parseInt(String(input.port ?? env.PORT ?? '8787'), 10);
return {
host: typeof input.host === 'string' && input.host.trim() ? input.host.trim() : env.HOST ?? '127.0.0.1',
port: Number.isFinite(portCandidate) ? portCandidate : 8787,
activeProviderId,
providers,
};
}
export function createDefaultGatewayConfig(env = process.env) {
return normalizeGatewayConfig({}, env);
}
export function getActiveProvider(config) {
return (
config.providers.find((provider) => provider.id === config.activeProviderId) ??
config.providers[0] ??
createLegacyProvider(process.env)
);
}
export function createInMemoryConfigStore(initialConfig = {}, env = process.env) {
let config = normalizeGatewayConfig(initialConfig, env);
return {
getConfig() {
return config;
},
setConfig(nextConfig) {
config = normalizeGatewayConfig(nextConfig, env);
return config;
},
};
}
export function createFileBackedConfigStore(options = {}) {
const configPath = options.configPath ?? DEFAULT_CONFIG_PATH;
const env = options.env ?? process.env;
let cachedConfig = createDefaultGatewayConfig(env);
function ensureConfigFile() {
mkdirSync(dirname(configPath), { recursive: true });
try {
readFileSync(configPath, 'utf8');
} catch {
writeFileSync(configPath, `${JSON.stringify(cachedConfig, null, 2)}\n`, 'utf8');
}
}
function loadConfigFromDisk() {
ensureConfigFile();
try {
const raw = readFileSync(configPath, 'utf8');
const parsed = JSON.parse(raw);
cachedConfig = normalizeGatewayConfig(parsed, env);
return cachedConfig;
} catch {
return cachedConfig;
}
}
function saveConfig(nextConfig) {
cachedConfig = normalizeGatewayConfig(nextConfig, env);
mkdirSync(dirname(configPath), { recursive: true });
writeFileSync(configPath, `${JSON.stringify(cachedConfig, null, 2)}\n`, 'utf8');
return cachedConfig;
}
cachedConfig = loadConfigFromDisk();
return {
configPath,
getConfig: loadConfigFromDisk,
setConfig: saveConfig,
};
}