-
Notifications
You must be signed in to change notification settings - Fork 378
Expand file tree
/
Copy pathconfig.ts
More file actions
196 lines (173 loc) · 5.37 KB
/
config.ts
File metadata and controls
196 lines (173 loc) · 5.37 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
import fs from 'fs/promises';
import path from 'path';
import os from 'os';
import ini from 'ini';
import type { TiktokenModel } from '@dqbd/tiktoken';
import { KnownError, handleCliError } from './error';
import * as p from '@clack/prompts';
import { red } from 'kolorist';
const { hasOwnProperty } = Object.prototype;
export const hasOwn = (object: unknown, key: PropertyKey) =>
hasOwnProperty.call(object, key);
export const normalizeOpenAiKey = (key?: string) => key?.trim();
export const hasOpenAiKey = (key?: string) => {
const normalizedKey = normalizeOpenAiKey(key);
return !!normalizedKey && normalizedKey.toLowerCase() !== 'cancel';
};
const configParsers = {
OPENAI_KEY(key?: string) {
return normalizeOpenAiKey(key);
},
ANTHROPIC_KEY(key?: string) {
return key;
},
MODEL(model?: string) {
if (!model || model.length === 0) {
return 'gpt-4o';
}
return model as TiktokenModel;
},
ANTHROPIC_MODEL(model?: string) {
if (!model || model.length === 0) {
return 'claude-3-5-sonnet-20241022';
}
return model;
},
USE_ASSISTANT(useAssistant?: string) {
return useAssistant !== 'false';
},
OPENAI_API_ENDPOINT(apiEndpoint?: string) {
return apiEndpoint || 'https://api.openai.com/v1';
},
LANGUAGE(language?: string) {
return language || 'en';
},
MOCK_LLM_RECORD_FILE(filename?: string) {
return filename;
},
USE_MOCK_LLM(useMockLlm?: string) {
return useMockLlm === 'true';
},
} as const;
type ConfigKeys = keyof typeof configParsers;
type RawConfig = {
[key in ConfigKeys]?: string;
};
type ValidConfig = {
[Key in ConfigKeys]: ReturnType<(typeof configParsers)[Key]>;
};
const configPath = path.join(os.homedir(), '.micro-agent');
const fileExists = (filePath: string) =>
fs.lstat(filePath).then(
() => true,
() => false
);
const readConfigFile = async (): Promise<RawConfig> => {
const configExists = await fileExists(configPath);
if (!configExists) {
return Object.create(null);
}
const configString = await fs.readFile(configPath, 'utf8');
return ini.parse(configString);
};
export const getConfig = async (
cliConfig?: RawConfig
): Promise<ValidConfig> => {
const config = await readConfigFile();
const parsedConfig: Record<string, unknown> = {};
for (const key of Object.keys(configParsers) as ConfigKeys[]) {
const parser = configParsers[key];
const value = cliConfig?.[key] ?? config[key];
parsedConfig[key] = parser(value);
}
return { ...(parsedConfig as ValidConfig), ...process.env };
};
export const setConfigs = async (keyValues: [key: string, value: string][]) => {
const config = await readConfigFile();
for (const [key, value] of keyValues) {
if (!hasOwn(configParsers, key)) {
throw new KnownError(`Invalid config property: ${key}`);
}
const parsed = configParsers[key as ConfigKeys](value);
config[key as ConfigKeys] = parsed as any;
}
await fs.writeFile(configPath, ini.stringify(config), 'utf8');
};
export const showConfigUI = async () => {
try {
const config = await getConfig();
const choice = (await p.select({
message: 'Set config' + ':',
options: [
{
label: 'OpenAI Key',
value: 'OPENAI_KEY',
hint: hasOwn(config, 'OPENAI_KEY')
? // Obfuscate the key
'sk-...' + (config.OPENAI_KEY?.slice(-3) || '')
: '(not set)',
},
{
label: 'Anthropic Key',
value: 'ANTHROPIC_KEY',
hint: hasOwn(config, 'ANTHROPIC_KEY')
? // Obfuscate the key
'sk-ant-...' + (config.ANTHROPIC_KEY?.slice(-3) || '')
: '(not set)',
},
{
label: 'Model',
value: 'MODEL',
hint: hasOwn(config, 'MODEL') ? config.MODEL : '(not set)',
},
{
label: 'OpenAI API Endpoint',
value: 'OPENAI_API_ENDPOINT',
hint: hasOwn(config, 'OPENAI_API_ENDPOINT')
? config.OPENAI_API_ENDPOINT
: '(not set)',
},
{
label: 'Done',
value: 'cancel',
hint: 'Exit',
},
],
})) as ConfigKeys | 'cancel' | symbol;
if (p.isCancel(choice)) return;
if (choice === 'OPENAI_KEY') {
const key = await p.text({
message: 'Enter your OpenAI API key',
validate: (value) => {
const normalizedKey = normalizeOpenAiKey(value);
if (!normalizedKey) {
return 'Please enter a key';
}
if (normalizedKey.toLowerCase() === 'cancel') {
return 'Press Ctrl+C to cancel';
}
},
});
if (p.isCancel(key)) return;
await setConfigs([['OPENAI_KEY', normalizeOpenAiKey(key as string)!]]);
} else if (choice === 'OPENAI_API_ENDPOINT') {
const apiEndpoint = await p.text({
message: 'Enter your OpenAI API Endpoint',
});
if (p.isCancel(apiEndpoint)) return;
await setConfigs([['OPENAI_API_ENDPOINT', apiEndpoint]]);
} else if (choice === 'MODEL') {
const model = await p.text({
message: 'Enter the model you want to use',
});
if (p.isCancel(model)) return;
await setConfigs([['MODEL', model]]);
}
if (choice === 'cancel') return;
await showConfigUI();
} catch (error: any) {
console.error(`\n${red('✖')} ${error.message}`);
handleCliError(error);
process.exit(1);
}
};