Repository navigation
Expand file tree
/
Copy pathconfig.ts
More file actions
224 lines (208 loc) · 8.11 KB
/
Copy pathconfig.ts
File metadata and controls
224 lines (208 loc) · 8.11 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
import { configManager, ServerConfig } from '../config-manager.js';
import { SetConfigValueArgsSchema } from './schemas.js';
import { getSystemInfo } from '../utils/system-info.js';
import { detectAvailableShells } from '../utils/shell.js';
import { currentClient } from '../server.js';
import { featureFlagManager } from '../utils/feature-flags.js';
import {
CONFIG_FIELD_DEFINITIONS,
CONFIG_FIELD_KEYS,
isConfigFieldKey,
} from '../config-field-definitions.js';
const ALLOWED_CONFIG_KEYS = new Set(CONFIG_FIELD_KEYS);
/**
* Get the entire config including system information
*/
export async function getConfig() {
console.error('getConfig called');
try {
const config = await configManager.getConfig();
// Add system information and current client to the config response
const systemInfo = getSystemInfo();
// Get memory usage
const memoryUsage = process.memoryUsage();
const memory = {
rss: `${(memoryUsage.rss / 1024 / 1024).toFixed(2)} MB`,
heapTotal: `${(memoryUsage.heapTotal / 1024 / 1024).toFixed(2)} MB`,
heapUsed: `${(memoryUsage.heapUsed / 1024 / 1024).toFixed(2)} MB`,
external: `${(memoryUsage.external / 1024 / 1024).toFixed(2)} MB`,
arrayBuffers: `${(memoryUsage.arrayBuffers / 1024 / 1024).toFixed(2)} MB`
};
const configWithSystemInfo = {
...config,
currentClient,
featureFlags: featureFlagManager.getAll(),
systemInfo: {
...systemInfo,
memory
}
};
const availableShells = detectAvailableShells();
console.error(`getConfig result: ${JSON.stringify(configWithSystemInfo, null, 2)}`);
return {
content: [{
type: "text",
text: `Current configuration:\n${JSON.stringify(configWithSystemInfo, null, 2)}`
}],
structuredContent: {
config: configWithSystemInfo,
uiHints: {
availableShells,
},
entries: CONFIG_FIELD_KEYS.map((key) => {
const definition = CONFIG_FIELD_DEFINITIONS[key];
const value = (configWithSystemInfo as Record<string, unknown>)[key];
return {
key,
value,
valueType: definition.valueType,
editable: true,
};
}),
},
};
} catch (error) {
console.error(`Error in getConfig: ${error instanceof Error ? error.message : String(error)}`);
console.error(error instanceof Error && error.stack ? error.stack : 'No stack trace available');
// Return empty config rather than crashing
return {
content: [{
type: "text",
text: `Error getting configuration: ${error instanceof Error ? error.message : String(error)}\nUsing empty configuration.`
}],
};
}
}
/**
* Set a specific config value
*/
export async function setConfigValue(args: unknown) {
console.error(`setConfigValue called with args: ${JSON.stringify(args)}`);
try {
const parsed = SetConfigValueArgsSchema.safeParse(args);
if (!parsed.success) {
console.error(`Invalid arguments for set_config_value: ${parsed.error}`);
return {
content: [{
type: "text",
text: `Invalid arguments: ${parsed.error}`
}],
isError: true
};
}
if (!isConfigFieldKey(parsed.data.key)) {
return {
content: [{
type: "text",
text: `Key "${parsed.data.key}" is not configurable via this tool. Allowed keys: ${[...ALLOWED_CONFIG_KEYS].join(', ')}`
}],
isError: true
};
}
try {
const fieldDefinition = CONFIG_FIELD_DEFINITIONS[parsed.data.key];
// Parse string values that should be arrays or objects
let valueToStore = parsed.data.value;
// If the value is a string that looks like an array or object, try to parse it
if (typeof valueToStore === 'string' &&
(valueToStore.startsWith('[') || valueToStore.startsWith('{'))) {
try {
valueToStore = JSON.parse(valueToStore);
console.error(`Parsed string value to object/array: ${JSON.stringify(valueToStore)}`);
} catch (parseError) {
console.error(`Failed to parse string as JSON, using as-is: ${parseError}`);
}
}
// Special handling for known array configuration keys
if (fieldDefinition.valueType === 'array' && !Array.isArray(valueToStore)) {
if (typeof valueToStore === 'string') {
const originalString = valueToStore;
try {
const parsedValue = JSON.parse(originalString);
valueToStore = parsedValue;
} catch (parseError) {
console.error(`Failed to parse string as array for ${parsed.data.key}: ${parseError}`);
// If parsing failed and it's a single value, convert to an array with one item
if (!originalString.includes('[')) {
valueToStore = [originalString];
}
}
} else if (valueToStore !== null) {
// If not a string or array (and not null), convert to an array with one item
valueToStore = [String(valueToStore)];
}
// Ensure the value is an array after all our conversions; null stays
// null and clears the value back to its default, as for number fields
if (valueToStore !== null && !Array.isArray(valueToStore)) {
console.error(`Value for ${parsed.data.key} is still not an array, converting to array`);
valueToStore = [String(valueToStore)];
}
}
// Harden boolean fields against stringly-typed inputs like "false".
if (fieldDefinition.valueType === 'boolean') {
if (typeof valueToStore === 'string') {
const normalized = valueToStore.trim().toLowerCase();
if (normalized === 'true') {
valueToStore = true;
} else if (normalized === 'false') {
valueToStore = false;
}
}
if (typeof valueToStore !== 'boolean') {
return {
content: [{
type: "text",
text: `Value for ${parsed.data.key} must be boolean true/false.`
}],
isError: true
};
}
}
// Numbers may arrive as strings ("5000"); null clears the value back to its default.
if (fieldDefinition.valueType === 'number' && valueToStore !== null) {
const numeric = typeof valueToStore === 'string' && valueToStore.trim() !== '' ? Number(valueToStore) : valueToStore;
if (typeof numeric !== 'number' || !Number.isFinite(numeric)) {
return {
content: [{
type: "text",
text: `Value for ${parsed.data.key} must be a number.`
}],
isError: true
};
}
valueToStore = numeric;
}
// Not saved: in effect all the same, as the answer below says, and saved with the held changes
await configManager.setValue(parsed.data.key, valueToStore, { holdIfNotSaved: true });
// Get the updated configuration to show the user
const updatedConfig = await configManager.getConfig();
console.error(`setConfigValue: Successfully set ${parsed.data.key} to ${JSON.stringify(valueToStore)}`);
return {
content: [{
type: "text",
text: `Successfully set ${parsed.data.key} to ${JSON.stringify(valueToStore, null, 2)}\n\nUpdated configuration:\n${JSON.stringify(updatedConfig, null, 2)}`
}],
};
} catch (saveError: any) {
console.error(`Error saving config: ${saveError.message}`);
// Continue with in-memory change but report error
return {
content: [{
type: "text",
text: `Value changed in memory but couldn't be saved to disk: ${saveError.message}`
}],
isError: true
};
}
} catch (error) {
console.error(`Error in setConfigValue: ${error instanceof Error ? error.message : String(error)}`);
console.error(error instanceof Error && error.stack ? error.stack : 'No stack trace available');
return {
content: [{
type: "text",
text: `Error setting value: ${error instanceof Error ? error.message : String(error)}`
}],
isError: true
};
}
}