@hexclave/shared-backend 1.0.35 → 1.0.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config-agent.d.ts +22 -1
- package/dist/config-agent.d.ts.map +1 -1
- package/dist/config-agent.js +54 -2
- package/dist/config-agent.js.map +1 -1
- package/dist/config-file.d.ts +15 -0
- package/dist/config-file.d.ts.map +1 -0
- package/dist/config-file.js +90 -0
- package/dist/config-file.js.map +1 -0
- package/dist/config-updater.d.ts +7 -0
- package/dist/config-updater.d.ts.map +1 -0
- package/dist/config-updater.js +330 -0
- package/dist/config-updater.js.map +1 -0
- package/dist/esm/config-agent.d.ts +22 -1
- package/dist/esm/config-agent.d.ts.map +1 -1
- package/dist/esm/config-agent.js +51 -3
- package/dist/esm/config-agent.js.map +1 -1
- package/dist/esm/config-file.d.ts +15 -0
- package/dist/esm/config-file.d.ts.map +1 -0
- package/dist/esm/config-file.js +82 -0
- package/dist/esm/config-file.js.map +1 -0
- package/dist/esm/config-updater.d.ts +7 -0
- package/dist/esm/config-updater.d.ts.map +1 -0
- package/dist/esm/config-updater.js +327 -0
- package/dist/esm/config-updater.js.map +1 -0
- package/dist/esm/index.d.ts +2 -16
- package/dist/esm/index.js +3 -446
- package/dist/index.d.ts +3 -16
- package/dist/index.js +15 -455
- package/package.json +2 -2
- package/dist/esm/index.d.ts.map +0 -1
- package/dist/esm/index.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,457 +1,17 @@
|
|
|
1
|
-
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_chunk = require('./chunk-BE-pF4vm.js');
|
|
3
|
-
let path = require("path");
|
|
4
|
-
path = require_chunk.__toESM(path);
|
|
5
|
-
let fs = require("fs");
|
|
6
|
-
let _hexclave_shared_dist_config_authoring = require("@hexclave/shared/dist/config-authoring");
|
|
7
|
-
let _hexclave_shared_dist_config_rendering = require("@hexclave/shared/dist/config-rendering");
|
|
8
|
-
let _hexclave_shared_dist_config_format = require("@hexclave/shared/dist/config/format");
|
|
9
|
-
let _hexclave_shared_dist_utils_errors = require("@hexclave/shared/dist/utils/errors");
|
|
10
|
-
let crypto = require("crypto");
|
|
11
|
-
let jiti = require("jiti");
|
|
12
|
-
let __config_agent_js = require("./config-agent.js");
|
|
13
1
|
|
|
14
|
-
//#region src/index.ts
|
|
15
|
-
const jiti$1 = (0, jiti.createJiti)(require("url").pathToFileURL(__filename).href, { moduleCache: false });
|
|
16
|
-
const LOG_PREFIX = "[Stack config updater]";
|
|
17
|
-
const DEFAULT_AGENT_TIMEOUT_MS = 12e4;
|
|
18
|
-
const CONFIG_UPDATE_LOG_PATH_LIMIT = 40;
|
|
19
|
-
const AGENT_OUTPUT_LOG_MAX_LENGTH = 2e4;
|
|
20
|
-
function formatConfigUpdaterErrorForLog(error) {
|
|
21
|
-
if (error instanceof Error) return {
|
|
22
|
-
errorName: error.name,
|
|
23
|
-
errorMessage: error.message,
|
|
24
|
-
errorStack: error.stack
|
|
25
|
-
};
|
|
26
|
-
return { errorMessage: String(error) };
|
|
27
|
-
}
|
|
28
|
-
function configUpdatePathDetailsForLog(changes) {
|
|
29
|
-
const paths = changes.map(({ path: configPath }) => configPath).sort();
|
|
30
|
-
return {
|
|
31
|
-
configUpdatePathCount: paths.length,
|
|
32
|
-
configUpdatePaths: paths.slice(0, CONFIG_UPDATE_LOG_PATH_LIMIT),
|
|
33
|
-
configUpdatePathsTruncated: paths.length > CONFIG_UPDATE_LOG_PATH_LIMIT
|
|
34
|
-
};
|
|
35
|
-
}
|
|
36
|
-
function appendBoundedAgentOutput(current, chunk) {
|
|
37
|
-
const next = `${current}${chunk}`;
|
|
38
|
-
if (next.length <= AGENT_OUTPUT_LOG_MAX_LENGTH) return next;
|
|
39
|
-
return next.slice(next.length - AGENT_OUTPUT_LOG_MAX_LENGTH);
|
|
40
|
-
}
|
|
41
|
-
function stringifyAgentMessageForLog(message) {
|
|
42
|
-
try {
|
|
43
|
-
return `${JSON.stringify(message)}\n`;
|
|
44
|
-
} catch {
|
|
45
|
-
return `${String(message)}\n`;
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
function agentOutputDetailsForLog(agentStdout, agentStderr) {
|
|
49
|
-
return {
|
|
50
|
-
agentStdout,
|
|
51
|
-
agentStdoutTruncated: agentStdout.length >= AGENT_OUTPUT_LOG_MAX_LENGTH,
|
|
52
|
-
agentStderr,
|
|
53
|
-
agentStderrTruncated: agentStderr.length >= AGENT_OUTPUT_LOG_MAX_LENGTH
|
|
54
|
-
};
|
|
55
|
-
}
|
|
56
|
-
function isConfigModule(value) {
|
|
57
|
-
return value !== null && typeof value === "object";
|
|
58
|
-
}
|
|
59
|
-
function sha256String(value) {
|
|
60
|
-
return (0, crypto.createHash)("sha256").update(value).digest("hex");
|
|
61
|
-
}
|
|
62
|
-
function resolveConfigFilePath(inputPath) {
|
|
63
|
-
const resolved = path.default.resolve(inputPath);
|
|
64
|
-
if (/\.(ts|js|mjs|cjs)$/i.test(resolved)) return resolved;
|
|
65
|
-
const hexclaveCandidate = path.default.join(resolved, "hexclave.config.ts");
|
|
66
|
-
const legacyCandidate = path.default.join(resolved, "stack.config.ts");
|
|
67
|
-
if ((0, fs.existsSync)(hexclaveCandidate)) return hexclaveCandidate;
|
|
68
|
-
if ((0, fs.existsSync)(legacyCandidate)) return legacyCandidate;
|
|
69
|
-
return hexclaveCandidate;
|
|
70
|
-
}
|
|
71
|
-
function ensureConfigFileExists(configFilePath) {
|
|
72
|
-
if ((0, fs.existsSync)(configFilePath)) return;
|
|
73
|
-
(0, fs.mkdirSync)(path.default.dirname(configFilePath), { recursive: true });
|
|
74
|
-
renderConfigObjectToFile(configFilePath, {});
|
|
75
|
-
}
|
|
76
|
-
async function readConfigObject(configFilePath) {
|
|
77
|
-
return (await readConfigFile(configFilePath)).config;
|
|
78
|
-
}
|
|
79
|
-
async function readConfigFile(configFilePath) {
|
|
80
|
-
ensureConfigFileExists(configFilePath);
|
|
81
|
-
if ((0, fs.readFileSync)(configFilePath, "utf-8").trim() === "") return {
|
|
82
|
-
config: {},
|
|
83
|
-
showOnboarding: false
|
|
84
|
-
};
|
|
85
|
-
let configModule;
|
|
86
|
-
try {
|
|
87
|
-
configModule = await jiti$1.import(configFilePath);
|
|
88
|
-
} catch (error) {
|
|
89
|
-
(0, _hexclave_shared_dist_utils_errors.captureError)("shared-backend/readConfigFile", error);
|
|
90
|
-
throw new Error(`Failed to load config file ${configFilePath}.`);
|
|
91
|
-
}
|
|
92
|
-
if (!isConfigModule(configModule)) throw new Error(`Invalid config in ${configFilePath}. The file must export a plain \`config\` object or "show-onboarding".`);
|
|
93
|
-
const config = configModule.config;
|
|
94
|
-
if (config === _hexclave_shared_dist_config_authoring.showOnboardingHexclaveConfigValue) return {
|
|
95
|
-
config: {},
|
|
96
|
-
showOnboarding: true
|
|
97
|
-
};
|
|
98
|
-
if (!(0, _hexclave_shared_dist_config_format.isValidConfig)(config)) throw new Error(`Invalid config in ${configFilePath}.`);
|
|
99
|
-
return {
|
|
100
|
-
config,
|
|
101
|
-
showOnboarding: false
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
function renderConfigObjectToString(configFilePath, config) {
|
|
105
|
-
return (0, _hexclave_shared_dist_config_rendering.renderConfigFileContent)(config, (0, _hexclave_shared_dist_config_rendering.detectImportPackageFromDir)(path.default.dirname(configFilePath)));
|
|
106
|
-
}
|
|
107
|
-
function writeFileAtomic(configFilePath, content) {
|
|
108
|
-
const dir = path.default.dirname(configFilePath);
|
|
109
|
-
(0, fs.mkdirSync)(dir, { recursive: true });
|
|
110
|
-
const tempPath = path.default.join(dir, `.stack.config.${Math.random().toString(36).slice(2)}.tmp`);
|
|
111
|
-
(0, fs.writeFileSync)(tempPath, content, "utf-8");
|
|
112
|
-
try {
|
|
113
|
-
(0, fs.renameSync)(tempPath, configFilePath);
|
|
114
|
-
} catch (error) {
|
|
115
|
-
try {
|
|
116
|
-
(0, fs.rmSync)(tempPath);
|
|
117
|
-
} catch {}
|
|
118
|
-
throw error;
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
function renderConfigObjectToFile(configFilePath, config) {
|
|
122
|
-
writeFileAtomic(configFilePath, renderConfigObjectToString(configFilePath, config));
|
|
123
|
-
}
|
|
124
|
-
async function updateConfigObject(configFilePath, configUpdate) {
|
|
125
|
-
const startedAtMs = performance.now();
|
|
126
|
-
ensureConfigFileExists(configFilePath);
|
|
127
|
-
const changes = flattenConfigUpdate(configUpdate);
|
|
128
|
-
if (changes.length === 0) {
|
|
129
|
-
console.log(`${LOG_PREFIX} Skipping config update because it contains no changes`, { configFilePath });
|
|
130
|
-
return;
|
|
131
|
-
}
|
|
132
|
-
const updateLogDetails = {
|
|
133
|
-
configFilePath,
|
|
134
|
-
...configUpdatePathDetailsForLog(changes)
|
|
135
|
-
};
|
|
136
|
-
console.log(`${LOG_PREFIX} Starting config file update`, updateLogDetails);
|
|
137
|
-
const content = (0, fs.readFileSync)(configFilePath, "utf-8");
|
|
138
|
-
const staticConfig = tryParseStaticConfigFileContent(content, configFilePath);
|
|
139
|
-
if (staticConfig != null && (0, _hexclave_shared_dist_config_format.isValidConfig)(staticConfig)) {
|
|
140
|
-
console.log(`${LOG_PREFIX} Applying config update with static config rewrite`, updateLogDetails);
|
|
141
|
-
const merged = (0, _hexclave_shared_dist_config_format.override)(staticConfig, configUpdate);
|
|
142
|
-
if (!(0, _hexclave_shared_dist_config_format.isValidConfig)(merged)) throw new Error(`${LOG_PREFIX} Merged config is invalid after applying update to ${configFilePath}`);
|
|
143
|
-
renderConfigObjectToFile(configFilePath, merged);
|
|
144
|
-
console.log(`${LOG_PREFIX} Finished config update with static config rewrite`, {
|
|
145
|
-
...updateLogDetails,
|
|
146
|
-
elapsedMs: Math.round(performance.now() - startedAtMs)
|
|
147
|
-
});
|
|
148
|
-
return;
|
|
149
|
-
}
|
|
150
|
-
console.log(`${LOG_PREFIX} Applying config update with agent-assisted rewrite`, {
|
|
151
|
-
...updateLogDetails,
|
|
152
|
-
configDirectory: path.default.dirname(configFilePath)
|
|
153
|
-
});
|
|
154
|
-
const baselineConfig = await tryReadConfigForValidation(configFilePath);
|
|
155
|
-
const { snapshots, seen } = snapshotConfigFiles(configFilePath, content);
|
|
156
|
-
try {
|
|
157
|
-
await runConfigUpdateAgent({
|
|
158
|
-
prompt: buildConfigUpdatePrompt(path.default.basename(configFilePath), configUpdate, baselineConfig),
|
|
159
|
-
cwd: path.default.dirname(configFilePath),
|
|
160
|
-
onFileWillChange: (filePath) => captureSnapshotIfAbsent(snapshots, filePath, seen)
|
|
161
|
-
});
|
|
162
|
-
await validateAgentUpdate(configFilePath, baselineConfig, configUpdate, snapshots);
|
|
163
|
-
} catch (error) {
|
|
164
|
-
console.warn(`${LOG_PREFIX} Config update failed; restoring files from snapshots`, {
|
|
165
|
-
...updateLogDetails,
|
|
166
|
-
snapshotCount: snapshots.length,
|
|
167
|
-
elapsedMs: Math.round(performance.now() - startedAtMs),
|
|
168
|
-
...formatConfigUpdaterErrorForLog(error)
|
|
169
|
-
});
|
|
170
|
-
try {
|
|
171
|
-
restoreConfigFiles(snapshots);
|
|
172
|
-
console.warn(`${LOG_PREFIX} Restored files after failed config update`, {
|
|
173
|
-
...updateLogDetails,
|
|
174
|
-
snapshotCount: snapshots.length
|
|
175
|
-
});
|
|
176
|
-
} catch (restoreError) {
|
|
177
|
-
console.error(`${LOG_PREFIX} Failed to fully roll back config files after a failed update of ${configFilePath}; some files may be left in a partially-restored state`, {
|
|
178
|
-
configFilePath,
|
|
179
|
-
...formatConfigUpdaterErrorForLog(restoreError)
|
|
180
|
-
});
|
|
181
|
-
}
|
|
182
|
-
throw error;
|
|
183
|
-
}
|
|
184
|
-
console.log(`${LOG_PREFIX} Finished config update with agent-assisted rewrite`, {
|
|
185
|
-
...updateLogDetails,
|
|
186
|
-
elapsedMs: Math.round(performance.now() - startedAtMs),
|
|
187
|
-
snapshotCount: snapshots.length
|
|
188
|
-
});
|
|
189
|
-
}
|
|
190
|
-
async function replaceConfigObject(configFilePath, config) {
|
|
191
|
-
renderConfigObjectToFile(configFilePath, config);
|
|
192
|
-
}
|
|
193
|
-
async function runConfigUpdateAgent(options) {
|
|
194
|
-
const timeoutMs = parseAgentTimeoutMs();
|
|
195
|
-
const deniedOutOfBoundsWrites = /* @__PURE__ */ new Set();
|
|
196
|
-
const startedAtMs = performance.now();
|
|
197
|
-
let agentStdout = "";
|
|
198
|
-
let agentStderr = "";
|
|
199
|
-
console.log(`${LOG_PREFIX} Starting config update agent`, {
|
|
200
|
-
cwd: options.cwd,
|
|
201
|
-
timeoutMs
|
|
202
|
-
});
|
|
203
|
-
try {
|
|
204
|
-
await (0, __config_agent_js.runHeadlessClaudeAgent)({
|
|
205
|
-
prompt: options.prompt,
|
|
206
|
-
cwd: options.cwd,
|
|
207
|
-
allowedTools: [
|
|
208
|
-
"Read",
|
|
209
|
-
"Write",
|
|
210
|
-
"Edit",
|
|
211
|
-
"Glob",
|
|
212
|
-
"Grep"
|
|
213
|
-
],
|
|
214
|
-
strictIsolation: true,
|
|
215
|
-
timeoutMs,
|
|
216
|
-
stderr: (data) => {
|
|
217
|
-
agentStderr = appendBoundedAgentOutput(agentStderr, data);
|
|
218
|
-
console.warn(`${LOG_PREFIX} [agent] ${data}`);
|
|
219
|
-
},
|
|
220
|
-
onMessage: (message) => {
|
|
221
|
-
agentStdout = appendBoundedAgentOutput(agentStdout, stringifyAgentMessageForLog(message));
|
|
222
|
-
},
|
|
223
|
-
onPreToolUse: (input) => {
|
|
224
|
-
const target = (0, __config_agent_js.getToolWriteTargetPath)(input.tool_name, input.tool_input, options.cwd);
|
|
225
|
-
if (target == null) return { continue: true };
|
|
226
|
-
if (!(0, __config_agent_js.isPathInsideDir)(options.cwd, target)) {
|
|
227
|
-
deniedOutOfBoundsWrites.add(target);
|
|
228
|
-
return { hookSpecificOutput: {
|
|
229
|
-
hookEventName: "PreToolUse",
|
|
230
|
-
permissionDecision: "deny",
|
|
231
|
-
permissionDecisionReason: `Refusing to modify ${target}: config updates may only change files inside the config directory.`
|
|
232
|
-
} };
|
|
233
|
-
}
|
|
234
|
-
options.onFileWillChange?.(target);
|
|
235
|
-
return { continue: true };
|
|
236
|
-
}
|
|
237
|
-
});
|
|
238
|
-
} catch (error) {
|
|
239
|
-
if (error instanceof __config_agent_js.ClaudeAgentTimeoutError) {
|
|
240
|
-
console.warn(`${LOG_PREFIX} Config update agent timed out`, {
|
|
241
|
-
cwd: options.cwd,
|
|
242
|
-
timeoutMs,
|
|
243
|
-
elapsedMs: Math.round(performance.now() - startedAtMs),
|
|
244
|
-
...formatConfigUpdaterErrorForLog(error),
|
|
245
|
-
...agentOutputDetailsForLog(agentStdout, agentStderr)
|
|
246
|
-
});
|
|
247
|
-
throw new Error(`Config update agent timed out after ${timeoutMs}ms. It was unable to apply the config changes to the file.`);
|
|
248
|
-
}
|
|
249
|
-
if (error instanceof __config_agent_js.ClaudeAgentFailureError) {
|
|
250
|
-
console.warn(`${LOG_PREFIX} Config update agent failed`, {
|
|
251
|
-
cwd: options.cwd,
|
|
252
|
-
timeoutMs,
|
|
253
|
-
elapsedMs: Math.round(performance.now() - startedAtMs),
|
|
254
|
-
...formatConfigUpdaterErrorForLog(error),
|
|
255
|
-
...agentOutputDetailsForLog(agentStdout, agentStderr)
|
|
256
|
-
});
|
|
257
|
-
throw new Error(`${error.message} It was unable to apply the config changes to the file.`);
|
|
258
|
-
}
|
|
259
|
-
console.warn(`${LOG_PREFIX} Config update agent failed unexpectedly`, {
|
|
260
|
-
cwd: options.cwd,
|
|
261
|
-
timeoutMs,
|
|
262
|
-
elapsedMs: Math.round(performance.now() - startedAtMs),
|
|
263
|
-
...formatConfigUpdaterErrorForLog(error),
|
|
264
|
-
...agentOutputDetailsForLog(agentStdout, agentStderr)
|
|
265
|
-
});
|
|
266
|
-
throw error;
|
|
267
|
-
}
|
|
268
|
-
console.log(`${LOG_PREFIX} Finished config update agent`, {
|
|
269
|
-
cwd: options.cwd,
|
|
270
|
-
timeoutMs,
|
|
271
|
-
elapsedMs: Math.round(performance.now() - startedAtMs),
|
|
272
|
-
deniedOutOfBoundsWriteCount: deniedOutOfBoundsWrites.size
|
|
273
|
-
});
|
|
274
|
-
if (deniedOutOfBoundsWrites.size > 0) {
|
|
275
|
-
console.warn(`${LOG_PREFIX} Config update agent attempted out-of-bounds writes`, {
|
|
276
|
-
cwd: options.cwd,
|
|
277
|
-
deniedOutOfBoundsWriteCount: deniedOutOfBoundsWrites.size,
|
|
278
|
-
deniedOutOfBoundsWrites: [...deniedOutOfBoundsWrites]
|
|
279
|
-
});
|
|
280
|
-
throw new Error(`Config update agent tried to modify ${deniedOutOfBoundsWrites.size} file(s) outside the config directory, which is not allowed: ${[...deniedOutOfBoundsWrites].join(", ")}. The config was not updated.`);
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
function parseAgentTimeoutMs() {
|
|
284
|
-
const raw = process.env.STACK_CONFIG_UPDATE_AGENT_TIMEOUT_MS;
|
|
285
|
-
if (raw == null || raw.trim() === "") return DEFAULT_AGENT_TIMEOUT_MS;
|
|
286
|
-
const parsed = Number(raw);
|
|
287
|
-
if (!Number.isFinite(parsed) || parsed <= 0) throw new Error(`Invalid STACK_CONFIG_UPDATE_AGENT_TIMEOUT_MS: ${JSON.stringify(raw)}. Expected a positive number of milliseconds.`);
|
|
288
|
-
return parsed;
|
|
289
|
-
}
|
|
290
|
-
function captureSnapshotIfAbsent(snapshots, filePath, seen) {
|
|
291
|
-
const resolved = path.default.resolve(filePath);
|
|
292
|
-
if (seen.has(resolved)) return;
|
|
293
|
-
seen.add(resolved);
|
|
294
|
-
snapshots.push({
|
|
295
|
-
path: resolved,
|
|
296
|
-
content: (0, fs.existsSync)(resolved) ? (0, fs.readFileSync)(resolved, "utf-8") : null
|
|
297
|
-
});
|
|
298
|
-
}
|
|
299
|
-
function snapshotConfigFiles(configFilePath, configContent) {
|
|
300
|
-
const dir = path.default.dirname(configFilePath);
|
|
301
|
-
const resolvedConfig = path.default.resolve(configFilePath);
|
|
302
|
-
const snapshots = [{
|
|
303
|
-
path: resolvedConfig,
|
|
304
|
-
content: configContent
|
|
305
|
-
}];
|
|
306
|
-
const seen = new Set([resolvedConfig]);
|
|
307
|
-
for (const specifier of getRelativeImportSpecifiers(configContent)) {
|
|
308
|
-
const resolved = path.default.resolve(dir, specifier);
|
|
309
|
-
if (!(0, __config_agent_js.isPathInsideDir)(dir, resolved)) continue;
|
|
310
|
-
captureSnapshotIfAbsent(snapshots, resolved, seen);
|
|
311
|
-
}
|
|
312
|
-
return {
|
|
313
|
-
snapshots,
|
|
314
|
-
seen
|
|
315
|
-
};
|
|
316
|
-
}
|
|
317
|
-
function restoreConfigFiles(snapshots) {
|
|
318
|
-
const failures = [];
|
|
319
|
-
for (const { path: filePath, content } of snapshots) try {
|
|
320
|
-
if (content === null) {
|
|
321
|
-
if ((0, fs.existsSync)(filePath)) (0, fs.rmSync)(filePath);
|
|
322
|
-
} else (0, fs.writeFileSync)(filePath, content, "utf-8");
|
|
323
|
-
} catch (error) {
|
|
324
|
-
failures.push(`${filePath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
325
|
-
}
|
|
326
|
-
if (failures.length > 0) throw new Error(`Failed to restore ${failures.length} file(s) during rollback: ${failures.join("; ")}`);
|
|
327
|
-
}
|
|
328
|
-
async function tryReadConfigForValidation(configFilePath) {
|
|
329
|
-
try {
|
|
330
|
-
return (await readConfigFile(configFilePath)).config;
|
|
331
|
-
} catch (error) {
|
|
332
|
-
console.warn(`${LOG_PREFIX} Could not evaluate config for validation baseline; will fall back to a structural check`, {
|
|
333
|
-
configFilePath,
|
|
334
|
-
error: error instanceof Error ? error.message : String(error)
|
|
335
|
-
});
|
|
336
|
-
return null;
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
async function validateAgentUpdate(configFilePath, baselineConfig, configUpdate, snapshots) {
|
|
340
|
-
if (baselineConfig != null) {
|
|
341
|
-
const target = canonicalizeConfig((0, _hexclave_shared_dist_config_format.override)(baselineConfig, configUpdate));
|
|
342
|
-
if (!configsEqual(canonicalizeConfig((await readConfigFile(configFilePath)).config), target)) throw new Error(`Config update validation failed for ${configFilePath}: the updated file does not evaluate to the expected configuration.`);
|
|
343
|
-
return;
|
|
344
|
-
}
|
|
345
|
-
if (flattenConfigUpdate(configUpdate).length > 0 && !snapshotsChangedOnDisk(snapshots)) console.warn(`${LOG_PREFIX} Agent did not modify any file for ${configFilePath}; assuming values are already up to date.`);
|
|
346
|
-
if (!configFileExportsConfig((0, fs.readFileSync)(configFilePath, "utf-8"), configFilePath)) throw new Error(`Config update validation failed for ${configFilePath}: the updated file no longer exports a valid \`config\`.`);
|
|
347
|
-
}
|
|
348
|
-
function tryParseStaticConfigFileContent(content, configFilePath) {
|
|
349
|
-
try {
|
|
350
|
-
const parsed = (0, _hexclave_shared_dist_config_rendering.parseHexclaveConfigFileContent)(content, configFilePath);
|
|
351
|
-
return (0, _hexclave_shared_dist_config_format.isValidConfig)(parsed) ? parsed : null;
|
|
352
|
-
} catch {
|
|
353
|
-
return null;
|
|
354
|
-
}
|
|
355
|
-
}
|
|
356
|
-
function configFileExportsConfig(content, configFilePath) {
|
|
357
|
-
try {
|
|
358
|
-
(0, _hexclave_shared_dist_config_rendering.parseHexclaveConfigFileContent)(content, configFilePath);
|
|
359
|
-
return true;
|
|
360
|
-
} catch {
|
|
361
|
-
return /\bexport\s+const\s+config\b/.test(content);
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
function getRelativeImportSpecifiers(content) {
|
|
365
|
-
const specifiers = [];
|
|
366
|
-
const importPattern = /\bimport\b(?:[^'"]*?\bfrom\s*)?["'](\.{1,2}\/[^"']+)["']/g;
|
|
367
|
-
let match;
|
|
368
|
-
while ((match = importPattern.exec(content)) !== null) specifiers.push(match[1]);
|
|
369
|
-
return specifiers;
|
|
370
|
-
}
|
|
371
|
-
function snapshotsChangedOnDisk(snapshots) {
|
|
372
|
-
return snapshots.some(({ path: filePath, content }) => {
|
|
373
|
-
return ((0, fs.existsSync)(filePath) ? (0, fs.readFileSync)(filePath, "utf-8") : null) !== content;
|
|
374
|
-
});
|
|
375
|
-
}
|
|
376
|
-
function flattenConfigUpdate(update) {
|
|
377
|
-
const changes = [];
|
|
378
|
-
const walk = (prefix, obj) => {
|
|
379
|
-
for (const [key, value] of Object.entries(obj)) {
|
|
380
|
-
const fullPath = prefix === "" ? key : `${prefix}.${key}`;
|
|
381
|
-
if (value === void 0) continue;
|
|
382
|
-
if (value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0) walk(fullPath, value);
|
|
383
|
-
else changes.push({
|
|
384
|
-
path: fullPath,
|
|
385
|
-
value
|
|
386
|
-
});
|
|
387
|
-
}
|
|
388
|
-
};
|
|
389
|
-
walk("", update);
|
|
390
|
-
return changes;
|
|
391
|
-
}
|
|
392
|
-
function buildConfigUpdatePrompt(configFileName, configUpdate, baselineConfig) {
|
|
393
|
-
const changeLines = flattenConfigUpdate(configUpdate).map(({ path: configPath, value }) => {
|
|
394
|
-
return `- ${JSON.stringify(configPath)}: set to ${JSON.stringify(value)}`;
|
|
395
|
-
}).join("\n");
|
|
396
|
-
const expectedConfig = baselineConfig == null ? null : canonicalizeConfig((0, _hexclave_shared_dist_config_format.override)(baselineConfig, configUpdate));
|
|
397
|
-
const expectedConfigSection = expectedConfig == null ? "" : `
|
|
398
|
-
After the edit, evaluating the exported \`config\` must produce this exact JSON value:
|
|
399
2
|
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
Rules:
|
|
417
|
-
- Change ONLY the config paths listed above. Leave every other part of the file byte-for-byte unchanged: imports, comments, formatting, helper wrappers, and any config fields not listed.
|
|
418
|
-
- If a listed path's value is currently provided by an imported external file (like the \`import ... with { type: "text" }\` example above), DO NOT inline the new value into the config file. Instead, overwrite that external file with the new value and keep the import statement intact.
|
|
419
|
-
- If a listed path's value is a plain inline literal, edit it inline.
|
|
420
|
-
- Keep the file valid: it must still export a \`config\` that, once evaluated, reflects the new values exactly.
|
|
421
|
-
- Do not run any shell commands and do not create files other than what is required to apply these changes.`;
|
|
422
|
-
}
|
|
423
|
-
function canonicalizeConfig(config) {
|
|
424
|
-
const droppedKeys = [];
|
|
425
|
-
const normalized = (0, _hexclave_shared_dist_config_format.normalize)(config, {
|
|
426
|
-
onDotIntoNonObject: "ignore",
|
|
427
|
-
onDotIntoNull: "empty-object",
|
|
428
|
-
droppedKeys
|
|
429
|
-
});
|
|
430
|
-
if (droppedKeys.length > 0) throw new Error(`Config update has conflicting keys that would be dropped during normalization: ${droppedKeys.map((key) => JSON.stringify(key)).join(", ")}`);
|
|
431
|
-
return normalized;
|
|
432
|
-
}
|
|
433
|
-
function configsEqual(a, b) {
|
|
434
|
-
if (a === b) return true;
|
|
435
|
-
if (a === null || b === null) return a === b;
|
|
436
|
-
if (Array.isArray(a) || Array.isArray(b)) {
|
|
437
|
-
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
|
|
438
|
-
return a.every((value, index) => configsEqual(value, b[index]));
|
|
439
|
-
}
|
|
440
|
-
if (typeof a === "object" && typeof b === "object") {
|
|
441
|
-
const aEntries = Object.entries(a);
|
|
442
|
-
const bMap = new Map(Object.entries(b));
|
|
443
|
-
if (aEntries.length !== bMap.size) return false;
|
|
444
|
-
return aEntries.every(([key, value]) => bMap.has(key) && configsEqual(value, bMap.get(key)));
|
|
445
|
-
}
|
|
446
|
-
return false;
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
//#endregion
|
|
450
|
-
exports.ensureConfigFileExists = ensureConfigFileExists;
|
|
451
|
-
exports.readConfigFile = readConfigFile;
|
|
452
|
-
exports.readConfigObject = readConfigObject;
|
|
453
|
-
exports.replaceConfigObject = replaceConfigObject;
|
|
454
|
-
exports.resolveConfigFilePath = resolveConfigFilePath;
|
|
455
|
-
exports.sha256String = sha256String;
|
|
456
|
-
exports.updateConfigObject = updateConfigObject;
|
|
457
|
-
//# sourceMappingURL=index.js.map
|
|
3
|
+
var __config_file_js = require("./config-file.js");
|
|
4
|
+
Object.keys(__config_file_js).forEach(function (k) {
|
|
5
|
+
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
|
|
6
|
+
enumerable: true,
|
|
7
|
+
get: function () { return __config_file_js[k]; }
|
|
8
|
+
});
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
var __config_updater_js = require("./config-updater.js");
|
|
12
|
+
Object.keys(__config_updater_js).forEach(function (k) {
|
|
13
|
+
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
|
|
14
|
+
enumerable: true,
|
|
15
|
+
get: function () { return __config_updater_js[k]; }
|
|
16
|
+
});
|
|
17
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hexclave/shared-backend",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.37",
|
|
4
4
|
"repository": "https://github.com/hexclave/hexclave",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
"dependencies": {
|
|
30
30
|
"@anthropic-ai/claude-agent-sdk": "^0.2.73",
|
|
31
31
|
"jiti": "^2.4.2",
|
|
32
|
-
"@hexclave/shared": "1.0.
|
|
32
|
+
"@hexclave/shared": "1.0.37"
|
|
33
33
|
},
|
|
34
34
|
"devDependencies": {
|
|
35
35
|
"@types/node": "20.17.6",
|
package/dist/esm/index.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/index.ts"],"mappings":";;;iBA4EgB,YAAA,CAAa,KAAA;AAAA,iBAIb,qBAAA,CAAsB,SAAA;AAAA,iBAkBtB,sBAAA,CAAuB,cAAA;AAAA,iBAMjB,gBAAA,CAAiB,cAAA,WAAyB,OAAA,CAAQ,MAAA;AAAA,iBAIlD,cAAA,CAAe,cAAA,WAAyB,OAAA;EAAU,MAAA,EAAQ,MAAA;EAAQ,cAAA;AAAA;AAAA,iBAkElE,kBAAA,CAAmB,cAAA,UAAwB,YAAA,EAAc,MAAA,GAAS,OAAA;AAAA,iBA+ElE,mBAAA,CAAoB,cAAA,UAAwB,MAAA,EAAQ,MAAA,GAAS,OAAA"}
|
package/dist/esm/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["import { showOnboardingHexclaveConfigValue } from \"@hexclave/shared/dist/config-authoring\";\nimport { detectImportPackageFromDir, parseHexclaveConfigFileContent, renderConfigFileContent } from \"@hexclave/shared/dist/config-rendering\";\nimport type { Config, ConfigValue, NormalizedConfig } from \"@hexclave/shared/dist/config/format\";\nimport { isValidConfig, normalize, override } from \"@hexclave/shared/dist/config/format\";\nimport { captureError } from \"@hexclave/shared/dist/utils/errors\";\nimport { createHash } from \"crypto\";\nimport { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"fs\";\nimport { createJiti } from \"jiti\";\nimport path from \"path\";\nimport { ClaudeAgentFailureError, ClaudeAgentTimeoutError, getToolWriteTargetPath, isPathInsideDir, runHeadlessClaudeAgent } from \"./config-agent\";\n\nconst jiti = createJiti(import.meta.url, { moduleCache: false });\n\nconst LOG_PREFIX = \"[Stack config updater]\";\nconst DEFAULT_AGENT_TIMEOUT_MS = 120_000;\nconst CONFIG_UPDATE_LOG_PATH_LIMIT = 40;\nconst AGENT_OUTPUT_LOG_MAX_LENGTH = 20_000;\n\ntype ConfigModule = {\n config?: unknown,\n};\n\ntype ConfigFileSnapshot = { path: string, content: string | null };\ntype ConfigChange = { path: string, value: ConfigValue };\n\nfunction formatConfigUpdaterErrorForLog(error: unknown): Record<string, unknown> {\n if (error instanceof Error) {\n return {\n errorName: error.name,\n errorMessage: error.message,\n errorStack: error.stack,\n };\n }\n return {\n errorMessage: String(error),\n };\n}\n\nfunction configUpdatePathDetailsForLog(changes: ConfigChange[]): Record<string, unknown> {\n const paths = changes.map(({ path: configPath }) => configPath).sort();\n return {\n configUpdatePathCount: paths.length,\n configUpdatePaths: paths.slice(0, CONFIG_UPDATE_LOG_PATH_LIMIT),\n configUpdatePathsTruncated: paths.length > CONFIG_UPDATE_LOG_PATH_LIMIT,\n };\n}\n\nfunction appendBoundedAgentOutput(current: string, chunk: string): string {\n const next = `${current}${chunk}`;\n if (next.length <= AGENT_OUTPUT_LOG_MAX_LENGTH) {\n return next;\n }\n return next.slice(next.length - AGENT_OUTPUT_LOG_MAX_LENGTH);\n}\n\nfunction stringifyAgentMessageForLog(message: unknown): string {\n try {\n return `${JSON.stringify(message)}\\n`;\n } catch {\n return `${String(message)}\\n`;\n }\n}\n\nfunction agentOutputDetailsForLog(agentStdout: string, agentStderr: string): Record<string, unknown> {\n return {\n agentStdout,\n agentStdoutTruncated: agentStdout.length >= AGENT_OUTPUT_LOG_MAX_LENGTH,\n agentStderr,\n agentStderrTruncated: agentStderr.length >= AGENT_OUTPUT_LOG_MAX_LENGTH,\n };\n}\n\nfunction isConfigModule(value: unknown): value is ConfigModule {\n return value !== null && typeof value === \"object\";\n}\n\nexport function sha256String(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nexport function resolveConfigFilePath(inputPath: string): string {\n const resolved = path.resolve(inputPath);\n const looksLikeConfigFile = /\\.(ts|js|mjs|cjs)$/i.test(resolved);\n if (looksLikeConfigFile) {\n return resolved;\n }\n // Prefer hexclave.config.ts, fall back to stack.config.ts, default to the new name.\n const hexclaveCandidate = path.join(resolved, \"hexclave.config.ts\");\n const legacyCandidate = path.join(resolved, \"stack.config.ts\");\n if (existsSync(hexclaveCandidate)) {\n return hexclaveCandidate;\n }\n if (existsSync(legacyCandidate)) {\n return legacyCandidate;\n }\n return hexclaveCandidate;\n}\n\nexport function ensureConfigFileExists(configFilePath: string): void {\n if (existsSync(configFilePath)) return;\n mkdirSync(path.dirname(configFilePath), { recursive: true });\n renderConfigObjectToFile(configFilePath, {});\n}\n\nexport async function readConfigObject(configFilePath: string): Promise<Config> {\n return (await readConfigFile(configFilePath)).config;\n}\n\nexport async function readConfigFile(configFilePath: string): Promise<{ config: Config, showOnboarding: boolean }> {\n ensureConfigFileExists(configFilePath);\n const content = readFileSync(configFilePath, \"utf-8\");\n if (content.trim() === \"\") {\n return {\n config: {},\n showOnboarding: false,\n };\n }\n\n let configModule: unknown;\n try {\n configModule = await jiti.import<unknown>(configFilePath);\n } catch (error) {\n // Capture the raw jiti/framework error for diagnostics, but don't attach it as `cause` on the thrown error:\n // dashboard error formatting renders causes recursively, which would leak framework internals into the\n // user-facing message we're deliberately replacing.\n captureError(\"shared-backend/readConfigFile\", error);\n throw new Error(\n `Failed to load config file ${configFilePath}.`,\n );\n }\n if (!isConfigModule(configModule)) {\n throw new Error(`Invalid config in ${configFilePath}. The file must export a plain \\`config\\` object or \"show-onboarding\".`);\n }\n\n const config = configModule.config;\n if (config === showOnboardingHexclaveConfigValue) {\n return {\n config: {},\n showOnboarding: true,\n };\n }\n if (!isValidConfig(config)) {\n throw new Error(`Invalid config in ${configFilePath}.`);\n }\n return {\n config,\n showOnboarding: false,\n };\n}\n\nfunction renderConfigObjectToString(configFilePath: string, config: Config): string {\n const importPackage = detectImportPackageFromDir(path.dirname(configFilePath));\n return renderConfigFileContent(config, importPackage);\n}\n\nfunction writeFileAtomic(configFilePath: string, content: string): void {\n const dir = path.dirname(configFilePath);\n mkdirSync(dir, { recursive: true });\n const tempPath = path.join(dir, `.stack.config.${Math.random().toString(36).slice(2)}.tmp`);\n writeFileSync(tempPath, content, \"utf-8\");\n try {\n renameSync(tempPath, configFilePath);\n } catch (error) {\n try {\n rmSync(tempPath);\n } catch { /* best-effort cleanup */ }\n throw error;\n }\n}\n\nfunction renderConfigObjectToFile(configFilePath: string, config: Config): void {\n writeFileAtomic(configFilePath, renderConfigObjectToString(configFilePath, config));\n}\n\nexport async function updateConfigObject(configFilePath: string, configUpdate: Config): Promise<void> {\n const startedAtMs = performance.now();\n ensureConfigFileExists(configFilePath);\n\n const changes = flattenConfigUpdate(configUpdate);\n if (changes.length === 0) {\n console.log(`${LOG_PREFIX} Skipping config update because it contains no changes`, {\n configFilePath,\n });\n return;\n }\n const updateLogDetails = {\n configFilePath,\n ...configUpdatePathDetailsForLog(changes),\n };\n console.log(`${LOG_PREFIX} Starting config file update`, updateLogDetails);\n\n const content = readFileSync(configFilePath, \"utf-8\");\n\n // Fast path: if the config is a plain static literal (no imports, no helpers),\n // apply the update deterministically without invoking the AI agent.\n const staticConfig = tryParseStaticConfigFileContent(content, configFilePath);\n if (staticConfig != null && isValidConfig(staticConfig)) {\n console.log(`${LOG_PREFIX} Applying config update with static config rewrite`, updateLogDetails);\n const merged = override(staticConfig, configUpdate);\n if (!isValidConfig(merged)) {\n throw new Error(`${LOG_PREFIX} Merged config is invalid after applying update to ${configFilePath}`);\n }\n renderConfigObjectToFile(configFilePath, merged);\n console.log(`${LOG_PREFIX} Finished config update with static config rewrite`, {\n ...updateLogDetails,\n elapsedMs: Math.round(performance.now() - startedAtMs),\n });\n return;\n }\n\n // Agent path: config has custom structure (imports, helpers, external files)\n // that must be preserved — delegate to the AI agent.\n console.log(`${LOG_PREFIX} Applying config update with agent-assisted rewrite`, {\n ...updateLogDetails,\n configDirectory: path.dirname(configFilePath),\n });\n const baselineConfig = await tryReadConfigForValidation(configFilePath);\n const { snapshots, seen } = snapshotConfigFiles(configFilePath, content);\n try {\n await runConfigUpdateAgent({\n prompt: buildConfigUpdatePrompt(path.basename(configFilePath), configUpdate, baselineConfig),\n cwd: path.dirname(configFilePath),\n onFileWillChange: (filePath) => captureSnapshotIfAbsent(snapshots, filePath, seen),\n });\n await validateAgentUpdate(configFilePath, baselineConfig, configUpdate, snapshots);\n } catch (error) {\n console.warn(`${LOG_PREFIX} Config update failed; restoring files from snapshots`, {\n ...updateLogDetails,\n snapshotCount: snapshots.length,\n elapsedMs: Math.round(performance.now() - startedAtMs),\n ...formatConfigUpdaterErrorForLog(error),\n });\n try {\n restoreConfigFiles(snapshots);\n console.warn(`${LOG_PREFIX} Restored files after failed config update`, {\n ...updateLogDetails,\n snapshotCount: snapshots.length,\n });\n } catch (restoreError) {\n console.error(`${LOG_PREFIX} Failed to fully roll back config files after a failed update of ${configFilePath}; some files may be left in a partially-restored state`, {\n configFilePath,\n ...formatConfigUpdaterErrorForLog(restoreError),\n });\n }\n throw error;\n }\n console.log(`${LOG_PREFIX} Finished config update with agent-assisted rewrite`, {\n ...updateLogDetails,\n elapsedMs: Math.round(performance.now() - startedAtMs),\n snapshotCount: snapshots.length,\n });\n}\n\nexport async function replaceConfigObject(configFilePath: string, config: Config): Promise<void> {\n renderConfigObjectToFile(configFilePath, config);\n}\n\nasync function runConfigUpdateAgent(options: {\n prompt: string,\n cwd: string,\n onFileWillChange?: (filePath: string) => void,\n}): Promise<void> {\n const timeoutMs = parseAgentTimeoutMs();\n const deniedOutOfBoundsWrites = new Set<string>();\n const startedAtMs = performance.now();\n let agentStdout = \"\";\n let agentStderr = \"\";\n console.log(`${LOG_PREFIX} Starting config update agent`, {\n cwd: options.cwd,\n timeoutMs,\n });\n try {\n await runHeadlessClaudeAgent({\n prompt: options.prompt,\n cwd: options.cwd,\n allowedTools: [\"Read\", \"Write\", \"Edit\", \"Glob\", \"Grep\"],\n strictIsolation: true,\n timeoutMs,\n stderr: (data) => {\n agentStderr = appendBoundedAgentOutput(agentStderr, data);\n console.warn(`${LOG_PREFIX} [agent] ${data}`);\n },\n onMessage: (message) => {\n agentStdout = appendBoundedAgentOutput(agentStdout, stringifyAgentMessageForLog(message));\n },\n onPreToolUse: (input) => {\n const target = getToolWriteTargetPath(input.tool_name, input.tool_input, options.cwd);\n if (target == null) return { continue: true };\n if (!isPathInsideDir(options.cwd, target)) {\n deniedOutOfBoundsWrites.add(target);\n return {\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: `Refusing to modify ${target}: config updates may only change files inside the config directory.`,\n },\n };\n }\n options.onFileWillChange?.(target);\n return { continue: true };\n },\n });\n } catch (error) {\n if (error instanceof ClaudeAgentTimeoutError) {\n console.warn(`${LOG_PREFIX} Config update agent timed out`, {\n cwd: options.cwd,\n timeoutMs,\n elapsedMs: Math.round(performance.now() - startedAtMs),\n ...formatConfigUpdaterErrorForLog(error),\n ...agentOutputDetailsForLog(agentStdout, agentStderr),\n });\n throw new Error(`Config update agent timed out after ${timeoutMs}ms. It was unable to apply the config changes to the file.`);\n }\n if (error instanceof ClaudeAgentFailureError) {\n console.warn(`${LOG_PREFIX} Config update agent failed`, {\n cwd: options.cwd,\n timeoutMs,\n elapsedMs: Math.round(performance.now() - startedAtMs),\n ...formatConfigUpdaterErrorForLog(error),\n ...agentOutputDetailsForLog(agentStdout, agentStderr),\n });\n throw new Error(`${error.message} It was unable to apply the config changes to the file.`);\n }\n console.warn(`${LOG_PREFIX} Config update agent failed unexpectedly`, {\n cwd: options.cwd,\n timeoutMs,\n elapsedMs: Math.round(performance.now() - startedAtMs),\n ...formatConfigUpdaterErrorForLog(error),\n ...agentOutputDetailsForLog(agentStdout, agentStderr),\n });\n throw error;\n }\n console.log(`${LOG_PREFIX} Finished config update agent`, {\n cwd: options.cwd,\n timeoutMs,\n elapsedMs: Math.round(performance.now() - startedAtMs),\n deniedOutOfBoundsWriteCount: deniedOutOfBoundsWrites.size,\n });\n if (deniedOutOfBoundsWrites.size > 0) {\n console.warn(`${LOG_PREFIX} Config update agent attempted out-of-bounds writes`, {\n cwd: options.cwd,\n deniedOutOfBoundsWriteCount: deniedOutOfBoundsWrites.size,\n deniedOutOfBoundsWrites: [...deniedOutOfBoundsWrites],\n });\n throw new Error(`Config update agent tried to modify ${deniedOutOfBoundsWrites.size} file(s) outside the config directory, which is not allowed: ${[...deniedOutOfBoundsWrites].join(\", \")}. The config was not updated.`);\n }\n}\n\nfunction parseAgentTimeoutMs(): number {\n const raw = process.env.STACK_CONFIG_UPDATE_AGENT_TIMEOUT_MS;\n if (raw == null || raw.trim() === \"\") return DEFAULT_AGENT_TIMEOUT_MS;\n const parsed = Number(raw);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(`Invalid STACK_CONFIG_UPDATE_AGENT_TIMEOUT_MS: ${JSON.stringify(raw)}. Expected a positive number of milliseconds.`);\n }\n return parsed;\n}\n\nfunction captureSnapshotIfAbsent(snapshots: ConfigFileSnapshot[], filePath: string, seen: Set<string>): void {\n const resolved = path.resolve(filePath);\n if (seen.has(resolved)) return;\n seen.add(resolved);\n snapshots.push({ path: resolved, content: existsSync(resolved) ? readFileSync(resolved, \"utf-8\") : null });\n}\n\nfunction snapshotConfigFiles(configFilePath: string, configContent: string): { snapshots: ConfigFileSnapshot[]; seen: Set<string> } {\n const dir = path.dirname(configFilePath);\n const resolvedConfig = path.resolve(configFilePath);\n const snapshots: ConfigFileSnapshot[] = [{ path: resolvedConfig, content: configContent }];\n const seen = new Set<string>([resolvedConfig]);\n for (const specifier of getRelativeImportSpecifiers(configContent)) {\n const resolved = path.resolve(dir, specifier);\n if (!isPathInsideDir(dir, resolved)) continue;\n captureSnapshotIfAbsent(snapshots, resolved, seen);\n }\n return { snapshots, seen };\n}\n\nfunction restoreConfigFiles(snapshots: ConfigFileSnapshot[]): void {\n const failures: string[] = [];\n for (const { path: filePath, content } of snapshots) {\n try {\n if (content === null) {\n if (existsSync(filePath)) rmSync(filePath);\n } else {\n writeFileSync(filePath, content, \"utf-8\");\n }\n } catch (error) {\n failures.push(`${filePath}: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n if (failures.length > 0) {\n throw new Error(`Failed to restore ${failures.length} file(s) during rollback: ${failures.join(\"; \")}`);\n }\n}\n\nasync function tryReadConfigForValidation(configFilePath: string): Promise<Config | null> {\n try {\n return (await readConfigFile(configFilePath)).config;\n } catch (error) {\n console.warn(`${LOG_PREFIX} Could not evaluate config for validation baseline; will fall back to a structural check`, {\n configFilePath,\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n}\n\nasync function validateAgentUpdate(configFilePath: string, baselineConfig: Config | null, configUpdate: Config, snapshots: ConfigFileSnapshot[]): Promise<void> {\n if (baselineConfig != null) {\n const target = canonicalizeConfig(override(baselineConfig, configUpdate));\n const result = canonicalizeConfig((await readConfigFile(configFilePath)).config);\n if (!configsEqual(result, target)) {\n throw new Error(`Config update validation failed for ${configFilePath}: the updated file does not evaluate to the expected configuration.`);\n }\n return;\n }\n\n // Structural-only fallback: when jiti can't evaluate the config (e.g. missing\n // runtime dependencies in import-with attributes), we can only verify that\n // (a) something changed on disk and (b) the file still exports `config`.\n // This cannot catch silently mis-applied values — an accepted tradeoff vs.\n // blocking updates entirely for configs we can't evaluate.\n // When nothing changed on disk the update is either already applied or the\n // agent couldn't figure out what to do. Treat it as a no-op rather than a\n // hard failure: the structural check below still verifies the file is valid.\n if (flattenConfigUpdate(configUpdate).length > 0 && !snapshotsChangedOnDisk(snapshots)) {\n console.warn(`${LOG_PREFIX} Agent did not modify any file for ${configFilePath}; assuming values are already up to date.`);\n }\n\n const content = readFileSync(configFilePath, \"utf-8\");\n if (!configFileExportsConfig(content, configFilePath)) {\n throw new Error(`Config update validation failed for ${configFilePath}: the updated file no longer exports a valid \\`config\\`.`);\n }\n}\n\nfunction tryParseStaticConfigFileContent(content: string, configFilePath: string): Config | null {\n try {\n const parsed = parseHexclaveConfigFileContent(content, configFilePath);\n return isValidConfig(parsed) ? parsed : null;\n } catch {\n return null;\n }\n}\n\nfunction configFileExportsConfig(content: string, configFilePath: string): boolean {\n try {\n parseHexclaveConfigFileContent(content, configFilePath);\n return true;\n } catch {\n // Dynamic configs can be valid even when the static parser cannot evaluate\n // them. For the structural fallback we only need to know that a runtime\n // config binding still exists after the agent edited the file.\n return /\\bexport\\s+const\\s+config\\b/.test(content);\n }\n}\n\nfunction getRelativeImportSpecifiers(content: string): string[] {\n const specifiers: string[] = [];\n const importPattern = /\\bimport\\b(?:[^'\"]*?\\bfrom\\s*)?[\"'](\\.{1,2}\\/[^\"']+)[\"']/g;\n let match: RegExpExecArray | null;\n while ((match = importPattern.exec(content)) !== null) {\n specifiers.push(match[1]);\n }\n return specifiers;\n}\n\nfunction snapshotsChangedOnDisk(snapshots: ConfigFileSnapshot[]): boolean {\n return snapshots.some(({ path: filePath, content }) => {\n const current = existsSync(filePath) ? readFileSync(filePath, \"utf-8\") : null;\n return current !== content;\n });\n}\n\nfunction flattenConfigUpdate(update: Config): ConfigChange[] {\n const changes: ConfigChange[] = [];\n const walk = (prefix: string, obj: Config): void => {\n for (const [key, value] of Object.entries(obj)) {\n const fullPath = prefix === \"\" ? key : `${prefix}.${key}`;\n if (value === undefined) continue;\n if (value !== null && typeof value === \"object\" && !Array.isArray(value) && Object.keys(value).length > 0) {\n walk(fullPath, value);\n } else {\n changes.push({ path: fullPath, value });\n }\n }\n };\n walk(\"\", update);\n return changes;\n}\n\nfunction buildConfigUpdatePrompt(configFileName: string, configUpdate: Config, baselineConfig: Config | null): string {\n const changes = flattenConfigUpdate(configUpdate);\n const changeLines = changes.map(({ path: configPath, value }) => {\n return `- ${JSON.stringify(configPath)}: set to ${JSON.stringify(value)}`;\n }).join(\"\\n\");\n const expectedConfig = baselineConfig == null ? null : canonicalizeConfig(override(baselineConfig, configUpdate));\n const expectedConfigSection = expectedConfig == null ? \"\" : `\nAfter the edit, evaluating the exported \\`config\\` must produce this exact JSON value:\n\n${JSON.stringify(expectedConfig, null, 2)}\n`;\n\n return `You are editing a Hexclave / Stack Auth configuration file in place. Apply a set of configuration changes WITHOUT changing how the file is written.\n\nConfig file: ${JSON.stringify(configFileName)} (in the current working directory).\n\nThe file exports a \\`config\\` object (it may be wrapped in a helper such as \\`defineStackConfig(...)\\`). Some config values may be sourced from other files via imports, for example:\n\n import welcomeEmail from \"./welcome-email.tsx\" with { type: \"text\" };\n export const config = { emails: { templates: { welcome: welcomeEmail } } };\n\nApply EXACTLY these changes. Paths use dot notation, so \\`a.b.c\\` refers to \\`config.a.b.c\\`:\n\n${changeLines}\n${expectedConfigSection}\n\nRules:\n- Change ONLY the config paths listed above. Leave every other part of the file byte-for-byte unchanged: imports, comments, formatting, helper wrappers, and any config fields not listed.\n- If a listed path's value is currently provided by an imported external file (like the \\`import ... with { type: \"text\" }\\` example above), DO NOT inline the new value into the config file. Instead, overwrite that external file with the new value and keep the import statement intact.\n- If a listed path's value is a plain inline literal, edit it inline.\n- Keep the file valid: it must still export a \\`config\\` that, once evaluated, reflects the new values exactly.\n- Do not run any shell commands and do not create files other than what is required to apply these changes.`;\n}\n\nfunction canonicalizeConfig(config: Config): NormalizedConfig {\n const droppedKeys: string[] = [];\n const normalized = normalize(config, {\n onDotIntoNonObject: \"ignore\",\n onDotIntoNull: \"empty-object\",\n droppedKeys,\n });\n if (droppedKeys.length > 0) {\n throw new Error(`Config update has conflicting keys that would be dropped during normalization: ${droppedKeys.map((key) => JSON.stringify(key)).join(\", \")}`);\n }\n return normalized;\n}\n\nfunction configsEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a === null || b === null) return a === b;\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n return a.every((value, index) => configsEqual(value, b[index]));\n }\n if (typeof a === \"object\" && typeof b === \"object\") {\n const aEntries = Object.entries(a);\n const bMap = new Map(Object.entries(b));\n if (aEntries.length !== bMap.size) return false;\n return aEntries.every(([key, value]) => bMap.has(key) && configsEqual(value, bMap.get(key)));\n }\n return false;\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,OAAO,WAAW,OAAO,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ources":["../src/index.ts"],"mappings":";;;iBA4EgB,YAAA,CAAa,KAAA;AAAA,iBAIb,qBAAA,CAAsB,SAAA;AAAA,iBAkBtB,sBAAA,CAAuB,cAAA;AAAA,iBAMjB,gBAAA,CAAiB,cAAA,WAAyB,OAAA,CAAQ,MAAA;AAAA,iBAIlD,cAAA,CAAe,cAAA,WAAyB,OAAA;EAAU,MAAA,EAAQ,MAAA;EAAQ,cAAA;AAAA;AAAA,iBAkElE,kBAAA,CAAmB,cAAA,UAAwB,YAAA,EAAc,MAAA,GAAS,OAAA;AAAA,iBA+ElE,mBAAA,CAAoB,cAAA,UAAwB,MAAA,EAAQ,MAAA,GAAS,OAAA"}
|
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["jiti","showOnboardingHexclaveConfigValue","ClaudeAgentTimeoutError","ClaudeAgentFailureError"],"sources":["../src/index.ts"],"sourcesContent":["import { showOnboardingHexclaveConfigValue } from \"@hexclave/shared/dist/config-authoring\";\nimport { detectImportPackageFromDir, parseHexclaveConfigFileContent, renderConfigFileContent } from \"@hexclave/shared/dist/config-rendering\";\nimport type { Config, ConfigValue, NormalizedConfig } from \"@hexclave/shared/dist/config/format\";\nimport { isValidConfig, normalize, override } from \"@hexclave/shared/dist/config/format\";\nimport { captureError } from \"@hexclave/shared/dist/utils/errors\";\nimport { createHash } from \"crypto\";\nimport { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"fs\";\nimport { createJiti } from \"jiti\";\nimport path from \"path\";\nimport { ClaudeAgentFailureError, ClaudeAgentTimeoutError, getToolWriteTargetPath, isPathInsideDir, runHeadlessClaudeAgent } from \"./config-agent\";\n\nconst jiti = createJiti(import.meta.url, { moduleCache: false });\n\nconst LOG_PREFIX = \"[Stack config updater]\";\nconst DEFAULT_AGENT_TIMEOUT_MS = 120_000;\nconst CONFIG_UPDATE_LOG_PATH_LIMIT = 40;\nconst AGENT_OUTPUT_LOG_MAX_LENGTH = 20_000;\n\ntype ConfigModule = {\n config?: unknown,\n};\n\ntype ConfigFileSnapshot = { path: string, content: string | null };\ntype ConfigChange = { path: string, value: ConfigValue };\n\nfunction formatConfigUpdaterErrorForLog(error: unknown): Record<string, unknown> {\n if (error instanceof Error) {\n return {\n errorName: error.name,\n errorMessage: error.message,\n errorStack: error.stack,\n };\n }\n return {\n errorMessage: String(error),\n };\n}\n\nfunction configUpdatePathDetailsForLog(changes: ConfigChange[]): Record<string, unknown> {\n const paths = changes.map(({ path: configPath }) => configPath).sort();\n return {\n configUpdatePathCount: paths.length,\n configUpdatePaths: paths.slice(0, CONFIG_UPDATE_LOG_PATH_LIMIT),\n configUpdatePathsTruncated: paths.length > CONFIG_UPDATE_LOG_PATH_LIMIT,\n };\n}\n\nfunction appendBoundedAgentOutput(current: string, chunk: string): string {\n const next = `${current}${chunk}`;\n if (next.length <= AGENT_OUTPUT_LOG_MAX_LENGTH) {\n return next;\n }\n return next.slice(next.length - AGENT_OUTPUT_LOG_MAX_LENGTH);\n}\n\nfunction stringifyAgentMessageForLog(message: unknown): string {\n try {\n return `${JSON.stringify(message)}\\n`;\n } catch {\n return `${String(message)}\\n`;\n }\n}\n\nfunction agentOutputDetailsForLog(agentStdout: string, agentStderr: string): Record<string, unknown> {\n return {\n agentStdout,\n agentStdoutTruncated: agentStdout.length >= AGENT_OUTPUT_LOG_MAX_LENGTH,\n agentStderr,\n agentStderrTruncated: agentStderr.length >= AGENT_OUTPUT_LOG_MAX_LENGTH,\n };\n}\n\nfunction isConfigModule(value: unknown): value is ConfigModule {\n return value !== null && typeof value === \"object\";\n}\n\nexport function sha256String(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nexport function resolveConfigFilePath(inputPath: string): string {\n const resolved = path.resolve(inputPath);\n const looksLikeConfigFile = /\\.(ts|js|mjs|cjs)$/i.test(resolved);\n if (looksLikeConfigFile) {\n return resolved;\n }\n // Prefer hexclave.config.ts, fall back to stack.config.ts, default to the new name.\n const hexclaveCandidate = path.join(resolved, \"hexclave.config.ts\");\n const legacyCandidate = path.join(resolved, \"stack.config.ts\");\n if (existsSync(hexclaveCandidate)) {\n return hexclaveCandidate;\n }\n if (existsSync(legacyCandidate)) {\n return legacyCandidate;\n }\n return hexclaveCandidate;\n}\n\nexport function ensureConfigFileExists(configFilePath: string): void {\n if (existsSync(configFilePath)) return;\n mkdirSync(path.dirname(configFilePath), { recursive: true });\n renderConfigObjectToFile(configFilePath, {});\n}\n\nexport async function readConfigObject(configFilePath: string): Promise<Config> {\n return (await readConfigFile(configFilePath)).config;\n}\n\nexport async function readConfigFile(configFilePath: string): Promise<{ config: Config, showOnboarding: boolean }> {\n ensureConfigFileExists(configFilePath);\n const content = readFileSync(configFilePath, \"utf-8\");\n if (content.trim() === \"\") {\n return {\n config: {},\n showOnboarding: false,\n };\n }\n\n let configModule: unknown;\n try {\n configModule = await jiti.import<unknown>(configFilePath);\n } catch (error) {\n // Capture the raw jiti/framework error for diagnostics, but don't attach it as `cause` on the thrown error:\n // dashboard error formatting renders causes recursively, which would leak framework internals into the\n // user-facing message we're deliberately replacing.\n captureError(\"shared-backend/readConfigFile\", error);\n throw new Error(\n `Failed to load config file ${configFilePath}.`,\n );\n }\n if (!isConfigModule(configModule)) {\n throw new Error(`Invalid config in ${configFilePath}. The file must export a plain \\`config\\` object or \"show-onboarding\".`);\n }\n\n const config = configModule.config;\n if (config === showOnboardingHexclaveConfigValue) {\n return {\n config: {},\n showOnboarding: true,\n };\n }\n if (!isValidConfig(config)) {\n throw new Error(`Invalid config in ${configFilePath}.`);\n }\n return {\n config,\n showOnboarding: false,\n };\n}\n\nfunction renderConfigObjectToString(configFilePath: string, config: Config): string {\n const importPackage = detectImportPackageFromDir(path.dirname(configFilePath));\n return renderConfigFileContent(config, importPackage);\n}\n\nfunction writeFileAtomic(configFilePath: string, content: string): void {\n const dir = path.dirname(configFilePath);\n mkdirSync(dir, { recursive: true });\n const tempPath = path.join(dir, `.stack.config.${Math.random().toString(36).slice(2)}.tmp`);\n writeFileSync(tempPath, content, \"utf-8\");\n try {\n renameSync(tempPath, configFilePath);\n } catch (error) {\n try {\n rmSync(tempPath);\n } catch { /* best-effort cleanup */ }\n throw error;\n }\n}\n\nfunction renderConfigObjectToFile(configFilePath: string, config: Config): void {\n writeFileAtomic(configFilePath, renderConfigObjectToString(configFilePath, config));\n}\n\nexport async function updateConfigObject(configFilePath: string, configUpdate: Config): Promise<void> {\n const startedAtMs = performance.now();\n ensureConfigFileExists(configFilePath);\n\n const changes = flattenConfigUpdate(configUpdate);\n if (changes.length === 0) {\n console.log(`${LOG_PREFIX} Skipping config update because it contains no changes`, {\n configFilePath,\n });\n return;\n }\n const updateLogDetails = {\n configFilePath,\n ...configUpdatePathDetailsForLog(changes),\n };\n console.log(`${LOG_PREFIX} Starting config file update`, updateLogDetails);\n\n const content = readFileSync(configFilePath, \"utf-8\");\n\n // Fast path: if the config is a plain static literal (no imports, no helpers),\n // apply the update deterministically without invoking the AI agent.\n const staticConfig = tryParseStaticConfigFileContent(content, configFilePath);\n if (staticConfig != null && isValidConfig(staticConfig)) {\n console.log(`${LOG_PREFIX} Applying config update with static config rewrite`, updateLogDetails);\n const merged = override(staticConfig, configUpdate);\n if (!isValidConfig(merged)) {\n throw new Error(`${LOG_PREFIX} Merged config is invalid after applying update to ${configFilePath}`);\n }\n renderConfigObjectToFile(configFilePath, merged);\n console.log(`${LOG_PREFIX} Finished config update with static config rewrite`, {\n ...updateLogDetails,\n elapsedMs: Math.round(performance.now() - startedAtMs),\n });\n return;\n }\n\n // Agent path: config has custom structure (imports, helpers, external files)\n // that must be preserved — delegate to the AI agent.\n console.log(`${LOG_PREFIX} Applying config update with agent-assisted rewrite`, {\n ...updateLogDetails,\n configDirectory: path.dirname(configFilePath),\n });\n const baselineConfig = await tryReadConfigForValidation(configFilePath);\n const { snapshots, seen } = snapshotConfigFiles(configFilePath, content);\n try {\n await runConfigUpdateAgent({\n prompt: buildConfigUpdatePrompt(path.basename(configFilePath), configUpdate, baselineConfig),\n cwd: path.dirname(configFilePath),\n onFileWillChange: (filePath) => captureSnapshotIfAbsent(snapshots, filePath, seen),\n });\n await validateAgentUpdate(configFilePath, baselineConfig, configUpdate, snapshots);\n } catch (error) {\n console.warn(`${LOG_PREFIX} Config update failed; restoring files from snapshots`, {\n ...updateLogDetails,\n snapshotCount: snapshots.length,\n elapsedMs: Math.round(performance.now() - startedAtMs),\n ...formatConfigUpdaterErrorForLog(error),\n });\n try {\n restoreConfigFiles(snapshots);\n console.warn(`${LOG_PREFIX} Restored files after failed config update`, {\n ...updateLogDetails,\n snapshotCount: snapshots.length,\n });\n } catch (restoreError) {\n console.error(`${LOG_PREFIX} Failed to fully roll back config files after a failed update of ${configFilePath}; some files may be left in a partially-restored state`, {\n configFilePath,\n ...formatConfigUpdaterErrorForLog(restoreError),\n });\n }\n throw error;\n }\n console.log(`${LOG_PREFIX} Finished config update with agent-assisted rewrite`, {\n ...updateLogDetails,\n elapsedMs: Math.round(performance.now() - startedAtMs),\n snapshotCount: snapshots.length,\n });\n}\n\nexport async function replaceConfigObject(configFilePath: string, config: Config): Promise<void> {\n renderConfigObjectToFile(configFilePath, config);\n}\n\nasync function runConfigUpdateAgent(options: {\n prompt: string,\n cwd: string,\n onFileWillChange?: (filePath: string) => void,\n}): Promise<void> {\n const timeoutMs = parseAgentTimeoutMs();\n const deniedOutOfBoundsWrites = new Set<string>();\n const startedAtMs = performance.now();\n let agentStdout = \"\";\n let agentStderr = \"\";\n console.log(`${LOG_PREFIX} Starting config update agent`, {\n cwd: options.cwd,\n timeoutMs,\n });\n try {\n await runHeadlessClaudeAgent({\n prompt: options.prompt,\n cwd: options.cwd,\n allowedTools: [\"Read\", \"Write\", \"Edit\", \"Glob\", \"Grep\"],\n strictIsolation: true,\n timeoutMs,\n stderr: (data) => {\n agentStderr = appendBoundedAgentOutput(agentStderr, data);\n console.warn(`${LOG_PREFIX} [agent] ${data}`);\n },\n onMessage: (message) => {\n agentStdout = appendBoundedAgentOutput(agentStdout, stringifyAgentMessageForLog(message));\n },\n onPreToolUse: (input) => {\n const target = getToolWriteTargetPath(input.tool_name, input.tool_input, options.cwd);\n if (target == null) return { continue: true };\n if (!isPathInsideDir(options.cwd, target)) {\n deniedOutOfBoundsWrites.add(target);\n return {\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: `Refusing to modify ${target}: config updates may only change files inside the config directory.`,\n },\n };\n }\n options.onFileWillChange?.(target);\n return { continue: true };\n },\n });\n } catch (error) {\n if (error instanceof ClaudeAgentTimeoutError) {\n console.warn(`${LOG_PREFIX} Config update agent timed out`, {\n cwd: options.cwd,\n timeoutMs,\n elapsedMs: Math.round(performance.now() - startedAtMs),\n ...formatConfigUpdaterErrorForLog(error),\n ...agentOutputDetailsForLog(agentStdout, agentStderr),\n });\n throw new Error(`Config update agent timed out after ${timeoutMs}ms. It was unable to apply the config changes to the file.`);\n }\n if (error instanceof ClaudeAgentFailureError) {\n console.warn(`${LOG_PREFIX} Config update agent failed`, {\n cwd: options.cwd,\n timeoutMs,\n elapsedMs: Math.round(performance.now() - startedAtMs),\n ...formatConfigUpdaterErrorForLog(error),\n ...agentOutputDetailsForLog(agentStdout, agentStderr),\n });\n throw new Error(`${error.message} It was unable to apply the config changes to the file.`);\n }\n console.warn(`${LOG_PREFIX} Config update agent failed unexpectedly`, {\n cwd: options.cwd,\n timeoutMs,\n elapsedMs: Math.round(performance.now() - startedAtMs),\n ...formatConfigUpdaterErrorForLog(error),\n ...agentOutputDetailsForLog(agentStdout, agentStderr),\n });\n throw error;\n }\n console.log(`${LOG_PREFIX} Finished config update agent`, {\n cwd: options.cwd,\n timeoutMs,\n elapsedMs: Math.round(performance.now() - startedAtMs),\n deniedOutOfBoundsWriteCount: deniedOutOfBoundsWrites.size,\n });\n if (deniedOutOfBoundsWrites.size > 0) {\n console.warn(`${LOG_PREFIX} Config update agent attempted out-of-bounds writes`, {\n cwd: options.cwd,\n deniedOutOfBoundsWriteCount: deniedOutOfBoundsWrites.size,\n deniedOutOfBoundsWrites: [...deniedOutOfBoundsWrites],\n });\n throw new Error(`Config update agent tried to modify ${deniedOutOfBoundsWrites.size} file(s) outside the config directory, which is not allowed: ${[...deniedOutOfBoundsWrites].join(\", \")}. The config was not updated.`);\n }\n}\n\nfunction parseAgentTimeoutMs(): number {\n const raw = process.env.STACK_CONFIG_UPDATE_AGENT_TIMEOUT_MS;\n if (raw == null || raw.trim() === \"\") return DEFAULT_AGENT_TIMEOUT_MS;\n const parsed = Number(raw);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(`Invalid STACK_CONFIG_UPDATE_AGENT_TIMEOUT_MS: ${JSON.stringify(raw)}. Expected a positive number of milliseconds.`);\n }\n return parsed;\n}\n\nfunction captureSnapshotIfAbsent(snapshots: ConfigFileSnapshot[], filePath: string, seen: Set<string>): void {\n const resolved = path.resolve(filePath);\n if (seen.has(resolved)) return;\n seen.add(resolved);\n snapshots.push({ path: resolved, content: existsSync(resolved) ? readFileSync(resolved, \"utf-8\") : null });\n}\n\nfunction snapshotConfigFiles(configFilePath: string, configContent: string): { snapshots: ConfigFileSnapshot[]; seen: Set<string> } {\n const dir = path.dirname(configFilePath);\n const resolvedConfig = path.resolve(configFilePath);\n const snapshots: ConfigFileSnapshot[] = [{ path: resolvedConfig, content: configContent }];\n const seen = new Set<string>([resolvedConfig]);\n for (const specifier of getRelativeImportSpecifiers(configContent)) {\n const resolved = path.resolve(dir, specifier);\n if (!isPathInsideDir(dir, resolved)) continue;\n captureSnapshotIfAbsent(snapshots, resolved, seen);\n }\n return { snapshots, seen };\n}\n\nfunction restoreConfigFiles(snapshots: ConfigFileSnapshot[]): void {\n const failures: string[] = [];\n for (const { path: filePath, content } of snapshots) {\n try {\n if (content === null) {\n if (existsSync(filePath)) rmSync(filePath);\n } else {\n writeFileSync(filePath, content, \"utf-8\");\n }\n } catch (error) {\n failures.push(`${filePath}: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n if (failures.length > 0) {\n throw new Error(`Failed to restore ${failures.length} file(s) during rollback: ${failures.join(\"; \")}`);\n }\n}\n\nasync function tryReadConfigForValidation(configFilePath: string): Promise<Config | null> {\n try {\n return (await readConfigFile(configFilePath)).config;\n } catch (error) {\n console.warn(`${LOG_PREFIX} Could not evaluate config for validation baseline; will fall back to a structural check`, {\n configFilePath,\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n}\n\nasync function validateAgentUpdate(configFilePath: string, baselineConfig: Config | null, configUpdate: Config, snapshots: ConfigFileSnapshot[]): Promise<void> {\n if (baselineConfig != null) {\n const target = canonicalizeConfig(override(baselineConfig, configUpdate));\n const result = canonicalizeConfig((await readConfigFile(configFilePath)).config);\n if (!configsEqual(result, target)) {\n throw new Error(`Config update validation failed for ${configFilePath}: the updated file does not evaluate to the expected configuration.`);\n }\n return;\n }\n\n // Structural-only fallback: when jiti can't evaluate the config (e.g. missing\n // runtime dependencies in import-with attributes), we can only verify that\n // (a) something changed on disk and (b) the file still exports `config`.\n // This cannot catch silently mis-applied values — an accepted tradeoff vs.\n // blocking updates entirely for configs we can't evaluate.\n // When nothing changed on disk the update is either already applied or the\n // agent couldn't figure out what to do. Treat it as a no-op rather than a\n // hard failure: the structural check below still verifies the file is valid.\n if (flattenConfigUpdate(configUpdate).length > 0 && !snapshotsChangedOnDisk(snapshots)) {\n console.warn(`${LOG_PREFIX} Agent did not modify any file for ${configFilePath}; assuming values are already up to date.`);\n }\n\n const content = readFileSync(configFilePath, \"utf-8\");\n if (!configFileExportsConfig(content, configFilePath)) {\n throw new Error(`Config update validation failed for ${configFilePath}: the updated file no longer exports a valid \\`config\\`.`);\n }\n}\n\nfunction tryParseStaticConfigFileContent(content: string, configFilePath: string): Config | null {\n try {\n const parsed = parseHexclaveConfigFileContent(content, configFilePath);\n return isValidConfig(parsed) ? parsed : null;\n } catch {\n return null;\n }\n}\n\nfunction configFileExportsConfig(content: string, configFilePath: string): boolean {\n try {\n parseHexclaveConfigFileContent(content, configFilePath);\n return true;\n } catch {\n // Dynamic configs can be valid even when the static parser cannot evaluate\n // them. For the structural fallback we only need to know that a runtime\n // config binding still exists after the agent edited the file.\n return /\\bexport\\s+const\\s+config\\b/.test(content);\n }\n}\n\nfunction getRelativeImportSpecifiers(content: string): string[] {\n const specifiers: string[] = [];\n const importPattern = /\\bimport\\b(?:[^'\"]*?\\bfrom\\s*)?[\"'](\\.{1,2}\\/[^\"']+)[\"']/g;\n let match: RegExpExecArray | null;\n while ((match = importPattern.exec(content)) !== null) {\n specifiers.push(match[1]);\n }\n return specifiers;\n}\n\nfunction snapshotsChangedOnDisk(snapshots: ConfigFileSnapshot[]): boolean {\n return snapshots.some(({ path: filePath, content }) => {\n const current = existsSync(filePath) ? readFileSync(filePath, \"utf-8\") : null;\n return current !== content;\n });\n}\n\nfunction flattenConfigUpdate(update: Config): ConfigChange[] {\n const changes: ConfigChange[] = [];\n const walk = (prefix: string, obj: Config): void => {\n for (const [key, value] of Object.entries(obj)) {\n const fullPath = prefix === \"\" ? key : `${prefix}.${key}`;\n if (value === undefined) continue;\n if (value !== null && typeof value === \"object\" && !Array.isArray(value) && Object.keys(value).length > 0) {\n walk(fullPath, value);\n } else {\n changes.push({ path: fullPath, value });\n }\n }\n };\n walk(\"\", update);\n return changes;\n}\n\nfunction buildConfigUpdatePrompt(configFileName: string, configUpdate: Config, baselineConfig: Config | null): string {\n const changes = flattenConfigUpdate(configUpdate);\n const changeLines = changes.map(({ path: configPath, value }) => {\n return `- ${JSON.stringify(configPath)}: set to ${JSON.stringify(value)}`;\n }).join(\"\\n\");\n const expectedConfig = baselineConfig == null ? null : canonicalizeConfig(override(baselineConfig, configUpdate));\n const expectedConfigSection = expectedConfig == null ? \"\" : `\nAfter the edit, evaluating the exported \\`config\\` must produce this exact JSON value:\n\n${JSON.stringify(expectedConfig, null, 2)}\n`;\n\n return `You are editing a Hexclave / Stack Auth configuration file in place. Apply a set of configuration changes WITHOUT changing how the file is written.\n\nConfig file: ${JSON.stringify(configFileName)} (in the current working directory).\n\nThe file exports a \\`config\\` object (it may be wrapped in a helper such as \\`defineStackConfig(...)\\`). Some config values may be sourced from other files via imports, for example:\n\n import welcomeEmail from \"./welcome-email.tsx\" with { type: \"text\" };\n export const config = { emails: { templates: { welcome: welcomeEmail } } };\n\nApply EXACTLY these changes. Paths use dot notation, so \\`a.b.c\\` refers to \\`config.a.b.c\\`:\n\n${changeLines}\n${expectedConfigSection}\n\nRules:\n- Change ONLY the config paths listed above. Leave every other part of the file byte-for-byte unchanged: imports, comments, formatting, helper wrappers, and any config fields not listed.\n- If a listed path's value is currently provided by an imported external file (like the \\`import ... with { type: \"text\" }\\` example above), DO NOT inline the new value into the config file. Instead, overwrite that external file with the new value and keep the import statement intact.\n- If a listed path's value is a plain inline literal, edit it inline.\n- Keep the file valid: it must still export a \\`config\\` that, once evaluated, reflects the new values exactly.\n- Do not run any shell commands and do not create files other than what is required to apply these changes.`;\n}\n\nfunction canonicalizeConfig(config: Config): NormalizedConfig {\n const droppedKeys: string[] = [];\n const normalized = normalize(config, {\n onDotIntoNonObject: \"ignore\",\n onDotIntoNull: \"empty-object\",\n droppedKeys,\n });\n if (droppedKeys.length > 0) {\n throw new Error(`Config update has conflicting keys that would be dropped during normalization: ${droppedKeys.map((key) => JSON.stringify(key)).join(\", \")}`);\n }\n return normalized;\n}\n\nfunction configsEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a === null || b === null) return a === b;\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n return a.every((value, index) => configsEqual(value, b[index]));\n }\n if (typeof a === \"object\" && typeof b === \"object\") {\n const aEntries = Object.entries(a);\n const bMap = new Map(Object.entries(b));\n if (aEntries.length !== bMap.size) return false;\n return aEntries.every(([key, value]) => bMap.has(key) && configsEqual(value, bMap.get(key)));\n }\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;AAWA,MA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