@synapsync/syntra-mcp 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +38 -2
- package/THIRD-PARTY-NOTICES.md +1255 -0
- package/bin/launcher.cjs +170 -0
- package/bin/setup.cjs +1317 -0
- package/bin/vendor/dependencies.json +32 -0
- package/bin/vendor/jsonc-parser/LICENSE.md +21 -0
- package/bin/vendor/jsonc-parser/lib/umd/impl/edit.js +201 -0
- package/bin/vendor/jsonc-parser/lib/umd/impl/format.js +275 -0
- package/bin/vendor/jsonc-parser/lib/umd/impl/parser.js +682 -0
- package/bin/vendor/jsonc-parser/lib/umd/impl/scanner.js +456 -0
- package/bin/vendor/jsonc-parser/lib/umd/impl/string-intern.js +42 -0
- package/bin/vendor/jsonc-parser/lib/umd/main.js +194 -0
- package/bin/vendor/smol-toml/LICENSE +24 -0
- package/bin/vendor/smol-toml/index.cjs +771 -0
- package/package.json +34 -4
- package/skills/syntra/SKILL.md +31 -0
- package/skills/syntra/references/tools.md +24 -0
package/bin/setup.cjs
ADDED
|
@@ -0,0 +1,1317 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const { randomUUID } = require('node:crypto');
|
|
6
|
+
const { isDeepStrictEqual, TextDecoder } = require('node:util');
|
|
7
|
+
const jsonc = require('./vendor/jsonc-parser/lib/umd/main.js');
|
|
8
|
+
const toml = require('./vendor/smol-toml/index.cjs');
|
|
9
|
+
const packageManifest = require('../package.json');
|
|
10
|
+
|
|
11
|
+
const MAX_CONFIG_BYTES = 4 * 1024 * 1024;
|
|
12
|
+
const SKILL_FILES = Object.freeze(['SKILL.md', 'references/tools.md']);
|
|
13
|
+
const SKILL_DIRECTORIES = Object.freeze(['references']);
|
|
14
|
+
const AGENT_NAMES = Object.freeze(['codex', 'claude-code', 'opencode']);
|
|
15
|
+
|
|
16
|
+
class SetupError extends Error {
|
|
17
|
+
constructor(message) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.name = 'SetupError';
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function fail(message) {
|
|
24
|
+
throw new SetupError(message);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function parseSetupArgs(args) {
|
|
28
|
+
let agent = null;
|
|
29
|
+
let dryRun = false;
|
|
30
|
+
let sawAgent = false;
|
|
31
|
+
let sawDryRun = false;
|
|
32
|
+
|
|
33
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
34
|
+
const argument = args[index];
|
|
35
|
+
if (argument === '--agent') {
|
|
36
|
+
if (sawAgent) fail('--agent may be supplied only once.');
|
|
37
|
+
sawAgent = true;
|
|
38
|
+
const value = args[index + 1];
|
|
39
|
+
if (!value || value.startsWith('--')) fail('--agent requires codex, claude-code, or opencode.');
|
|
40
|
+
agent = value;
|
|
41
|
+
index += 1;
|
|
42
|
+
} else if (argument === '--dry-run') {
|
|
43
|
+
if (sawDryRun) fail('--dry-run may be supplied only once.');
|
|
44
|
+
sawDryRun = true;
|
|
45
|
+
dryRun = true;
|
|
46
|
+
} else {
|
|
47
|
+
fail('Unknown setup option. Use --agent and --dry-run only.');
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (!agent) fail('Choose a host with --agent codex, --agent claude-code, or --agent opencode.');
|
|
52
|
+
if (!AGENT_NAMES.includes(agent)) fail('Supported setup hosts are codex, claude-code, and opencode.');
|
|
53
|
+
return { agent, dryRun };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function pathApi(platform) {
|
|
57
|
+
return platform === 'win32' ? path.win32 : path;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function homeDirectory(env, platform, pathModule) {
|
|
61
|
+
const value = platform === 'win32'
|
|
62
|
+
? (env.USERPROFILE || env.HOME)
|
|
63
|
+
: (env.HOME || env.USERPROFILE);
|
|
64
|
+
if (typeof value !== 'string' || !value || !pathModule.isAbsolute(value)) {
|
|
65
|
+
fail('An absolute user home directory is required to preview setup.');
|
|
66
|
+
}
|
|
67
|
+
return pathModule.normalize(value);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function selectedDirectory(env, variable, fallback, pathModule, label) {
|
|
71
|
+
const value = env[variable];
|
|
72
|
+
if (value === undefined || value === '') return fallback;
|
|
73
|
+
if (typeof value !== 'string' || !pathModule.isAbsolute(value)) {
|
|
74
|
+
fail(`${variable} must be an absolute path for ${label}.`);
|
|
75
|
+
}
|
|
76
|
+
return pathModule.normalize(value);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function shellCommand(platform) {
|
|
80
|
+
const version = packageManifest.version;
|
|
81
|
+
if (packageManifest.name !== '@synapsync/syntra-mcp' || typeof packageManifest.private !== 'boolean' ||
|
|
82
|
+
typeof version !== 'string' || !/^[0-9A-Za-z][0-9A-Za-z.+-]*$/.test(version)) {
|
|
83
|
+
fail('The Syntra package manifest has invalid setup metadata.');
|
|
84
|
+
}
|
|
85
|
+
const pinnedPackage = `${packageManifest.name}@${version}`;
|
|
86
|
+
if (platform === 'win32') {
|
|
87
|
+
// npx is a Windows .cmd entry point. cmd /d /c is the documented MCP wrapper;
|
|
88
|
+
// every argument is a fixed token and no user input is interpolated.
|
|
89
|
+
return Object.freeze({
|
|
90
|
+
command: 'cmd.exe',
|
|
91
|
+
args: Object.freeze(['/d', '/c', 'npx', '-y', pinnedPackage, 'mcp']),
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
return Object.freeze({
|
|
95
|
+
command: 'npx',
|
|
96
|
+
args: Object.freeze(['-y', pinnedPackage, 'mcp']),
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function tomlValue(value) {
|
|
101
|
+
if (Array.isArray(value)) return `[${value.map(item => JSON.stringify(item)).join(', ')}]`;
|
|
102
|
+
return JSON.stringify(value);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function hostPlan(agent, env = process.env, platform = process.platform) {
|
|
106
|
+
const paths = pathApi(platform);
|
|
107
|
+
const home = homeDirectory(env, platform, paths);
|
|
108
|
+
const command = shellCommand(platform);
|
|
109
|
+
|
|
110
|
+
if (agent === 'codex') {
|
|
111
|
+
const configHome = selectedDirectory(
|
|
112
|
+
env,
|
|
113
|
+
'CODEX_HOME',
|
|
114
|
+
paths.join(home, '.codex'),
|
|
115
|
+
paths,
|
|
116
|
+
'Codex',
|
|
117
|
+
);
|
|
118
|
+
return {
|
|
119
|
+
agent,
|
|
120
|
+
displayName: 'Codex',
|
|
121
|
+
format: 'toml',
|
|
122
|
+
configPath: paths.join(configHome, 'config.toml'),
|
|
123
|
+
skillPath: paths.join(home, '.agents', 'skills', 'syntra'),
|
|
124
|
+
registration: { command: command.command, args: command.args },
|
|
125
|
+
registrationPath: ['mcp_servers', 'syntra'],
|
|
126
|
+
tomlSnippet: [
|
|
127
|
+
'[mcp_servers.syntra]',
|
|
128
|
+
`command = ${tomlValue(command.command)}`,
|
|
129
|
+
`args = ${tomlValue(command.args)}`,
|
|
130
|
+
'',
|
|
131
|
+
].join('\n'),
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (agent === 'claude-code') {
|
|
136
|
+
const configDirectory = env.CLAUDE_CONFIG_DIR === undefined || env.CLAUDE_CONFIG_DIR === ''
|
|
137
|
+
? null
|
|
138
|
+
: selectedDirectory(env, 'CLAUDE_CONFIG_DIR', null, paths, 'Claude Code');
|
|
139
|
+
const claudeDirectory = configDirectory || paths.join(home, '.claude');
|
|
140
|
+
return {
|
|
141
|
+
agent,
|
|
142
|
+
displayName: 'Claude Code',
|
|
143
|
+
format: 'json',
|
|
144
|
+
configPath: configDirectory
|
|
145
|
+
? paths.join(configDirectory, '.claude.json')
|
|
146
|
+
: paths.join(home, '.claude.json'),
|
|
147
|
+
skillPath: paths.join(claudeDirectory, 'skills', 'syntra'),
|
|
148
|
+
registration: { type: 'stdio', command: command.command, args: command.args },
|
|
149
|
+
registrationPath: ['mcpServers', 'syntra'],
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (agent === 'opencode') {
|
|
154
|
+
const customOverrides = ['OPENCODE_CONFIG', 'OPENCODE_CONFIG_DIR', 'OPENCODE_CONFIG_CONTENT']
|
|
155
|
+
.filter(variable => env[variable] !== undefined && env[variable] !== '');
|
|
156
|
+
if (customOverrides.length > 0) {
|
|
157
|
+
fail(`OpenCode custom environment override${customOverrides.length === 1 ? '' : 's'} active (${customOverrides.join(', ')}); clear them before previewing global setup.`);
|
|
158
|
+
}
|
|
159
|
+
const xdgConfigHome = selectedDirectory(
|
|
160
|
+
env,
|
|
161
|
+
'XDG_CONFIG_HOME',
|
|
162
|
+
paths.join(home, '.config'),
|
|
163
|
+
paths,
|
|
164
|
+
'OpenCode',
|
|
165
|
+
);
|
|
166
|
+
const configDirectory = paths.join(xdgConfigHome, 'opencode');
|
|
167
|
+
const jsonPath = paths.join(configDirectory, 'opencode.json');
|
|
168
|
+
const jsoncPath = paths.join(configDirectory, 'opencode.jsonc');
|
|
169
|
+
const jsonInfo = inspectPath(jsonPath, 'file', platform);
|
|
170
|
+
const jsoncInfo = inspectPath(jsoncPath, 'file', platform);
|
|
171
|
+
if (jsonInfo.exists && jsoncInfo.exists) {
|
|
172
|
+
fail('OpenCode has both global JSON and JSONC config files; choose one before setup.');
|
|
173
|
+
}
|
|
174
|
+
return {
|
|
175
|
+
agent,
|
|
176
|
+
displayName: 'OpenCode',
|
|
177
|
+
format: 'jsonc',
|
|
178
|
+
configPath: jsoncInfo.exists ? jsoncPath : jsonPath,
|
|
179
|
+
skillPath: paths.join(xdgConfigHome, 'opencode', 'skills', 'syntra'),
|
|
180
|
+
registration: { type: 'local', command: command.args
|
|
181
|
+
? [command.command, ...command.args]
|
|
182
|
+
: [command.command] },
|
|
183
|
+
registrationPath: ['mcp', 'servers', 'syntra'],
|
|
184
|
+
openCodeConfigCandidates: [jsonPath, jsoncPath],
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
fail('Supported setup hosts are codex, claude-code, and opencode.');
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function inspectPath(target, finalKind, platform = process.platform) {
|
|
192
|
+
const paths = pathApi(platform);
|
|
193
|
+
if (typeof target !== 'string' || !paths.isAbsolute(target)) {
|
|
194
|
+
fail('A setup destination must be an absolute path.');
|
|
195
|
+
}
|
|
196
|
+
const normalized = paths.normalize(target);
|
|
197
|
+
const root = paths.parse(normalized).root;
|
|
198
|
+
const components = normalized.slice(root.length).split(paths.sep).filter(Boolean);
|
|
199
|
+
let cursor = root;
|
|
200
|
+
let missing = false;
|
|
201
|
+
let finalStat = null;
|
|
202
|
+
|
|
203
|
+
for (let index = 0; index < components.length; index += 1) {
|
|
204
|
+
cursor = paths.join(cursor, components[index]);
|
|
205
|
+
if (missing) continue;
|
|
206
|
+
let info;
|
|
207
|
+
try {
|
|
208
|
+
info = fs.lstatSync(cursor);
|
|
209
|
+
} catch (error) {
|
|
210
|
+
if (error && error.code === 'ENOENT') {
|
|
211
|
+
missing = true;
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
fail('A setup destination path could not be safely inspected.');
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
if (info.isSymbolicLink()) fail('A setup destination contains a symbolic link.');
|
|
218
|
+
const isFinal = index === components.length - 1;
|
|
219
|
+
if (!isFinal && !info.isDirectory()) fail('A setup destination has a non-directory parent.');
|
|
220
|
+
if (isFinal && finalKind === 'file' && !info.isFile()) fail('A setup config destination is not a regular file.');
|
|
221
|
+
if (isFinal && finalKind === 'directory' && !info.isDirectory()) fail('A skill destination is not a directory.');
|
|
222
|
+
if (isFinal && finalKind === 'file' && info.nlink > 1) fail('A setup config destination has multiple hard links.');
|
|
223
|
+
if (isFinal) finalStat = info;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
return { exists: !missing, stat: finalStat };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function fileObservation(stat) {
|
|
230
|
+
return {
|
|
231
|
+
dev: stat.dev,
|
|
232
|
+
ino: stat.ino,
|
|
233
|
+
mode: stat.mode & 0o777,
|
|
234
|
+
nlink: stat.nlink,
|
|
235
|
+
size: stat.size,
|
|
236
|
+
mtimeMs: stat.mtimeMs,
|
|
237
|
+
ctimeMs: stat.ctimeMs,
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function sameFileObservation(left, right) {
|
|
242
|
+
return isDeepStrictEqual(fileObservation(left), fileObservation(right));
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function sameFileIdentity(left, right) {
|
|
246
|
+
return left.dev === right.dev && left.ino === right.ino;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function sameConfigSnapshot(expected, current) {
|
|
250
|
+
if (!expected.exists || !current.exists) return expected.exists === current.exists;
|
|
251
|
+
return isDeepStrictEqual(expected.identity, current.identity) && expected.bytes.equals(current.bytes);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function writeAll(fd, bytes) {
|
|
255
|
+
let offset = 0;
|
|
256
|
+
while (offset < bytes.length) {
|
|
257
|
+
const written = fs.writeSync(fd, bytes, offset, bytes.length - offset);
|
|
258
|
+
if (written <= 0) fail('A setup file could not be written completely.');
|
|
259
|
+
offset += written;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function ensureDirectoryChain(target, platform, createdDirectories) {
|
|
264
|
+
const paths = pathApi(platform);
|
|
265
|
+
const normalized = paths.normalize(target);
|
|
266
|
+
if (!paths.isAbsolute(normalized)) fail('A setup directory must be absolute.');
|
|
267
|
+
const root = paths.parse(normalized).root;
|
|
268
|
+
const components = normalized.slice(root.length).split(paths.sep).filter(Boolean);
|
|
269
|
+
let current = root;
|
|
270
|
+
|
|
271
|
+
for (const component of components) {
|
|
272
|
+
current = paths.join(current, component);
|
|
273
|
+
let stat;
|
|
274
|
+
try {
|
|
275
|
+
stat = fs.lstatSync(current);
|
|
276
|
+
} catch (error) {
|
|
277
|
+
if (!error || error.code !== 'ENOENT') fail('A setup directory could not be safely inspected.');
|
|
278
|
+
try {
|
|
279
|
+
fs.mkdirSync(current, { mode: 0o700 });
|
|
280
|
+
stat = fs.lstatSync(current);
|
|
281
|
+
const record = { path: current, identity: fileObservation(stat) };
|
|
282
|
+
createdDirectories.push(record);
|
|
283
|
+
if (platform !== 'win32') fs.chmodSync(current, 0o700);
|
|
284
|
+
stat = fs.lstatSync(current);
|
|
285
|
+
} catch (createError) {
|
|
286
|
+
if (createError && createError.code === 'EEXIST') {
|
|
287
|
+
try { stat = fs.lstatSync(current); } catch { fail('A setup directory could not be safely inspected.'); }
|
|
288
|
+
} else {
|
|
289
|
+
fail('A setup directory could not be created safely.');
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
if (stat.isSymbolicLink()) fail('A setup destination contains a symbolic link.');
|
|
294
|
+
if (!stat.isDirectory()) fail('A setup destination has a non-directory parent.');
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function removeCreatedDirectories(createdDirectories) {
|
|
299
|
+
for (const created of [...createdDirectories].reverse()) {
|
|
300
|
+
try {
|
|
301
|
+
const stat = fs.lstatSync(created.path);
|
|
302
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() ||
|
|
303
|
+
!sameFileIdentity(created.identity, fileObservation(stat))) continue;
|
|
304
|
+
fs.rmdirSync(created.path);
|
|
305
|
+
} catch (error) {
|
|
306
|
+
if (!error || !['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) {
|
|
307
|
+
// A nonempty or replaced directory is intentionally left for its owner.
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function readConfig(configPath, format, platform) {
|
|
314
|
+
const info = inspectPath(configPath, 'file', platform);
|
|
315
|
+
if (!info.exists) return { exists: false, text: '', bytes: Buffer.alloc(0), snapshot: { exists: false } };
|
|
316
|
+
if (!info.stat || info.stat.size > MAX_CONFIG_BYTES) fail('The host config is too large to inspect safely.');
|
|
317
|
+
let fd;
|
|
318
|
+
try {
|
|
319
|
+
const noFollow = fs.constants.O_NOFOLLOW || 0;
|
|
320
|
+
fd = fs.openSync(configPath, fs.constants.O_RDONLY | noFollow);
|
|
321
|
+
const before = fs.fstatSync(fd);
|
|
322
|
+
if (!before.isFile() || before.nlink > 1 || before.size > MAX_CONFIG_BYTES) {
|
|
323
|
+
fail('The host config is not a safe regular file.');
|
|
324
|
+
}
|
|
325
|
+
const bytes = fs.readFileSync(fd);
|
|
326
|
+
const after = fs.fstatSync(fd);
|
|
327
|
+
const currentPath = fs.lstatSync(configPath);
|
|
328
|
+
if (currentPath.isSymbolicLink() || !sameFileObservation(before, after) ||
|
|
329
|
+
!sameFileObservation(after, currentPath)) {
|
|
330
|
+
fail('The host config changed while it was being inspected.');
|
|
331
|
+
}
|
|
332
|
+
const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
|
|
333
|
+
if (!Buffer.from(text, 'utf8').equals(bytes)) fail(`The ${format.toUpperCase()} host config is not lossless UTF-8.`);
|
|
334
|
+
return {
|
|
335
|
+
exists: true,
|
|
336
|
+
text,
|
|
337
|
+
bytes,
|
|
338
|
+
snapshot: { exists: true, identity: fileObservation(after), bytes, mode: after.mode & 0o777 },
|
|
339
|
+
};
|
|
340
|
+
} catch (error) {
|
|
341
|
+
if (error instanceof SetupError) throw error;
|
|
342
|
+
if (error instanceof TypeError) fail(`The ${format.toUpperCase()} host config is not valid UTF-8.`);
|
|
343
|
+
fail(`The ${format.toUpperCase()} host config cannot be read safely.`);
|
|
344
|
+
} finally {
|
|
345
|
+
if (fd !== undefined) {
|
|
346
|
+
try { fs.closeSync(fd); } catch { /* The read result or safe error is already determined. */ }
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function readBundledSkill() {
|
|
352
|
+
const skillRoot = path.resolve(__dirname, '..', 'skills', 'syntra');
|
|
353
|
+
const files = new Map();
|
|
354
|
+
for (const relative of SKILL_FILES) {
|
|
355
|
+
const source = path.join(skillRoot, ...relative.split('/'));
|
|
356
|
+
const info = inspectPath(source, 'file', process.platform);
|
|
357
|
+
if (!info.exists || !info.stat || info.stat.size > MAX_CONFIG_BYTES) {
|
|
358
|
+
fail('The bundled Syntra skill is incomplete.');
|
|
359
|
+
}
|
|
360
|
+
try {
|
|
361
|
+
files.set(relative, fs.readFileSync(source));
|
|
362
|
+
} catch {
|
|
363
|
+
fail('The bundled Syntra skill cannot be read.');
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
return { skillRoot, files };
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function inspectExistingSkill(skillPath, bundleFiles, platform) {
|
|
370
|
+
const info = inspectPath(skillPath, 'directory', platform);
|
|
371
|
+
if (!info.exists) return 'absent';
|
|
372
|
+
|
|
373
|
+
const observedFiles = [];
|
|
374
|
+
const observedDirectories = [];
|
|
375
|
+
const paths = pathApi(platform);
|
|
376
|
+
const walk = (current, relative) => {
|
|
377
|
+
let entries;
|
|
378
|
+
try {
|
|
379
|
+
entries = fs.readdirSync(current, { withFileTypes: true });
|
|
380
|
+
} catch {
|
|
381
|
+
fail('The existing skill directory cannot be safely inspected.');
|
|
382
|
+
}
|
|
383
|
+
for (const entry of entries) {
|
|
384
|
+
const child = paths.join(current, entry.name);
|
|
385
|
+
const childRelative = relative ? `${relative}/${entry.name}` : entry.name;
|
|
386
|
+
const childInfo = inspectPath(child, entry.isDirectory() ? 'directory' : 'file', platform);
|
|
387
|
+
if (entry.isSymbolicLink() || !childInfo.exists) fail('The existing skill contains an unsafe path.');
|
|
388
|
+
if (entry.isDirectory()) {
|
|
389
|
+
observedDirectories.push(childRelative);
|
|
390
|
+
walk(child, childRelative);
|
|
391
|
+
} else if (entry.isFile()) {
|
|
392
|
+
observedFiles.push(childRelative);
|
|
393
|
+
} else {
|
|
394
|
+
fail('The existing skill contains a non-regular file.');
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
};
|
|
398
|
+
walk(skillPath, '');
|
|
399
|
+
|
|
400
|
+
observedFiles.sort();
|
|
401
|
+
observedDirectories.sort();
|
|
402
|
+
if (!isDeepStrictEqual(observedFiles, [...bundleFiles.keys()].sort()) ||
|
|
403
|
+
!isDeepStrictEqual(observedDirectories, [...SKILL_DIRECTORIES].sort())) {
|
|
404
|
+
return 'conflict';
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
for (const relative of bundleFiles.keys()) {
|
|
408
|
+
try {
|
|
409
|
+
const actual = fs.readFileSync(paths.join(skillPath, ...relative.split('/')));
|
|
410
|
+
if (!actual.equals(bundleFiles.get(relative))) return 'conflict';
|
|
411
|
+
} catch {
|
|
412
|
+
return 'conflict';
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
return 'matching';
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function propertyChildren(node) {
|
|
419
|
+
if (!node || node.type !== 'object' || !Array.isArray(node.children)) return [];
|
|
420
|
+
return node.children.filter(child => child.type === 'property');
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function assertUnambiguousJsonTree(node) {
|
|
424
|
+
if (!node) return;
|
|
425
|
+
if (node.type === 'object') {
|
|
426
|
+
const names = new Set();
|
|
427
|
+
for (const property of propertyChildren(node)) {
|
|
428
|
+
const keyNode = property.children && property.children[0];
|
|
429
|
+
if (!keyNode || typeof keyNode.value !== 'string') fail('The host config has an ambiguous object key.');
|
|
430
|
+
if (names.has(keyNode.value)) fail('The host config contains duplicate object keys.');
|
|
431
|
+
if (['__proto__', 'constructor', 'prototype'].includes(keyNode.value)) {
|
|
432
|
+
fail('The host config contains an unsafe object key.');
|
|
433
|
+
}
|
|
434
|
+
names.add(keyNode.value);
|
|
435
|
+
assertUnambiguousJsonTree(property.children[1]);
|
|
436
|
+
}
|
|
437
|
+
} else if (node.children) {
|
|
438
|
+
for (const child of node.children) assertUnambiguousJsonTree(child);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function parseJsonDocument(text, format, allowComments) {
|
|
443
|
+
const errors = [];
|
|
444
|
+
const tree = jsonc.parseTree(text, errors, {
|
|
445
|
+
allowEmptyContent: false,
|
|
446
|
+
allowTrailingComma: allowComments,
|
|
447
|
+
disallowComments: !allowComments,
|
|
448
|
+
});
|
|
449
|
+
if (errors.length || !tree || tree.type !== 'object') {
|
|
450
|
+
fail(`The ${format.toUpperCase()} host config is malformed or is not an object.`);
|
|
451
|
+
}
|
|
452
|
+
assertUnambiguousJsonTree(tree);
|
|
453
|
+
return { tree, value: jsonc.getNodeValue(tree) };
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function getOwnPath(value, segments) {
|
|
457
|
+
let current = value;
|
|
458
|
+
for (const segment of segments) {
|
|
459
|
+
if (!current || typeof current !== 'object' || Array.isArray(current) ||
|
|
460
|
+
!Object.prototype.hasOwnProperty.call(current, segment)) return { exists: false, value: undefined };
|
|
461
|
+
current = current[segment];
|
|
462
|
+
}
|
|
463
|
+
return { exists: true, value: current };
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function deepPlainCopy(value) {
|
|
467
|
+
if (Array.isArray(value)) return value.map(deepPlainCopy);
|
|
468
|
+
if (!value || typeof value !== 'object') return value;
|
|
469
|
+
const copy = {};
|
|
470
|
+
for (const [key, child] of Object.entries(value)) copy[key] = deepPlainCopy(child);
|
|
471
|
+
return copy;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function removeRegistrationAndNewParents(value, segments, original) {
|
|
475
|
+
const copy = deepPlainCopy(value);
|
|
476
|
+
let current = copy;
|
|
477
|
+
for (const segment of segments.slice(0, -1)) {
|
|
478
|
+
if (!current || typeof current !== 'object' || !Object.prototype.hasOwnProperty.call(current, segment)) return copy;
|
|
479
|
+
current = current[segment];
|
|
480
|
+
}
|
|
481
|
+
if (!current || typeof current !== 'object') return copy;
|
|
482
|
+
delete current[segments[segments.length - 1]];
|
|
483
|
+
|
|
484
|
+
for (let length = segments.length - 1; length > 0; length -= 1) {
|
|
485
|
+
const prefix = segments.slice(0, length);
|
|
486
|
+
const candidate = getOwnPath(copy, prefix);
|
|
487
|
+
const wasPresent = getOwnPath(original, prefix).exists;
|
|
488
|
+
if (!candidate.exists || wasPresent || !candidate.value || typeof candidate.value !== 'object' ||
|
|
489
|
+
Array.isArray(candidate.value) || Object.keys(candidate.value).length !== 0) break;
|
|
490
|
+
let parent = copy;
|
|
491
|
+
for (const segment of prefix.slice(0, -1)) parent = parent[segment];
|
|
492
|
+
delete parent[prefix[prefix.length - 1]];
|
|
493
|
+
}
|
|
494
|
+
return copy;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function checkJsonParentTypes(tree, registrationPath) {
|
|
498
|
+
let current = tree;
|
|
499
|
+
for (const segment of registrationPath.slice(0, -1)) {
|
|
500
|
+
const next = jsonc.findNodeAtLocation(current, [segment]);
|
|
501
|
+
if (!next) return;
|
|
502
|
+
if (next.type !== 'object') fail('The host config has a conflicting parent value for the Syntra registration.');
|
|
503
|
+
current = next;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
function jsonLineEnding(text) {
|
|
508
|
+
const match = /\r\n|\n|\r/.exec(text);
|
|
509
|
+
return match ? match[0] : '\n';
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function indentationAt(text, offset) {
|
|
513
|
+
const lineStart = Math.max(text.lastIndexOf('\n', offset - 1), text.lastIndexOf('\r', offset - 1)) + 1;
|
|
514
|
+
const prefix = text.slice(lineStart, offset);
|
|
515
|
+
return /^[\t ]*$/.test(prefix) ? prefix : '';
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
function lastCommentEnd(text, objectNode) {
|
|
519
|
+
const closeOffset = objectNode.offset + objectNode.length - 1;
|
|
520
|
+
const scanner = jsonc.createScanner(text, false);
|
|
521
|
+
let last = -1;
|
|
522
|
+
while (true) {
|
|
523
|
+
const kind = scanner.scan();
|
|
524
|
+
const tokenOffset = scanner.getTokenOffset();
|
|
525
|
+
if (kind === jsonc.SyntaxKind.EOF || tokenOffset >= closeOffset) break;
|
|
526
|
+
if (tokenOffset > objectNode.offset &&
|
|
527
|
+
(kind === jsonc.SyntaxKind.LineCommentTrivia || kind === jsonc.SyntaxKind.BlockCommentTrivia)) {
|
|
528
|
+
last = tokenOffset + scanner.getTokenLength();
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
return last;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
function valueForMissingPath(segments, value) {
|
|
535
|
+
let nested = value;
|
|
536
|
+
for (let index = segments.length - 1; index >= 0; index -= 1) {
|
|
537
|
+
const wrapper = Object.create(null);
|
|
538
|
+
wrapper[segments[index]] = nested;
|
|
539
|
+
nested = wrapper;
|
|
540
|
+
}
|
|
541
|
+
return nested;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
function serializeJsonValue(value, inline, indent, eol) {
|
|
545
|
+
if (inline) return JSON.stringify(value);
|
|
546
|
+
return JSON.stringify(value, null, 2)
|
|
547
|
+
.split('\n')
|
|
548
|
+
.map((line, index) => index === 0 ? line : `${indent}${line}`)
|
|
549
|
+
.join(eol);
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
function insertJsonProperty(text, objectNode, key, value) {
|
|
553
|
+
const openOffset = objectNode.offset;
|
|
554
|
+
const closeOffset = openOffset + objectNode.length - 1;
|
|
555
|
+
const properties = propertyChildren(objectNode);
|
|
556
|
+
const eol = jsonLineEnding(text.slice(openOffset, closeOffset + 1));
|
|
557
|
+
const closeIndent = indentationAt(text, closeOffset);
|
|
558
|
+
const nested = valueForMissingPath([key], value);
|
|
559
|
+
|
|
560
|
+
if (properties.length > 0) {
|
|
561
|
+
const first = properties[0];
|
|
562
|
+
const leading = text.slice(openOffset + 1, first.offset);
|
|
563
|
+
const inline = !/[\r\n]/.test(leading);
|
|
564
|
+
const indent = inline ? '' : (indentationAt(text, first.offset) || `${closeIndent} `);
|
|
565
|
+
const property = `${JSON.stringify(key)}: ${serializeJsonValue(nested[key], inline, indent, eol)}`;
|
|
566
|
+
const startsWithSpace = /^[\t ]/.test(text.slice(openOffset + 1, openOffset + 2));
|
|
567
|
+
const suffix = inline && !startsWithSpace && text[openOffset + 1] !== undefined ? ' ' : '';
|
|
568
|
+
const insertion = inline ? ` ${property},${suffix}` : `${eol}${indent}${property},`;
|
|
569
|
+
return `${text.slice(0, openOffset + 1)}${insertion}${text.slice(openOffset + 1)}`;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
const inner = text.slice(openOffset + 1, closeOffset);
|
|
573
|
+
const commentEnd = lastCommentEnd(text, objectNode);
|
|
574
|
+
const lineStyle = /[\r\n]/.test(inner);
|
|
575
|
+
const property = `${JSON.stringify(key)}: ${serializeJsonValue(nested[key], !lineStyle, `${closeIndent} `, eol)}`;
|
|
576
|
+
|
|
577
|
+
if (commentEnd >= 0) {
|
|
578
|
+
const suffix = text.slice(commentEnd, closeOffset);
|
|
579
|
+
const insertion = lineStyle
|
|
580
|
+
? `${eol}${closeIndent} ${property}${/[\r\n]/.test(suffix) ? '' : `${eol}${closeIndent}`}`
|
|
581
|
+
: ` ${property}`;
|
|
582
|
+
return `${text.slice(0, commentEnd)}${insertion}${text.slice(commentEnd)}`;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
if (lineStyle) {
|
|
586
|
+
const insertionOffset = closeOffset - closeIndent.length;
|
|
587
|
+
const insertion = `${closeIndent} ${property}${eol}`;
|
|
588
|
+
return `${text.slice(0, insertionOffset)}${insertion}${text.slice(insertionOffset)}`;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
return `${text.slice(0, closeOffset)}${property}${text.slice(closeOffset)}`;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
function computeJsonCandidate(text, registrationPath, registration, format, existingTree = null) {
|
|
595
|
+
try {
|
|
596
|
+
if (!text) {
|
|
597
|
+
const nested = valueForMissingPath(registrationPath, registration);
|
|
598
|
+
return `${JSON.stringify(nested, null, 2)}\n`;
|
|
599
|
+
}
|
|
600
|
+
const tree = existingTree || parseJsonDocument(text, format, format === 'jsonc').tree;
|
|
601
|
+
let objectNode = tree;
|
|
602
|
+
let index = 0;
|
|
603
|
+
for (; index < registrationPath.length - 1; index += 1) {
|
|
604
|
+
const property = propertyChildren(objectNode).find(candidate => {
|
|
605
|
+
const keyNode = candidate.children && candidate.children[0];
|
|
606
|
+
return keyNode && keyNode.value === registrationPath[index];
|
|
607
|
+
});
|
|
608
|
+
if (!property) break;
|
|
609
|
+
objectNode = property.children[1];
|
|
610
|
+
if (!objectNode || objectNode.type !== 'object') {
|
|
611
|
+
fail('The host config has a conflicting parent value for the Syntra registration.');
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
if (!objectNode || objectNode.type !== 'object') {
|
|
615
|
+
fail('The host config has a conflicting parent value for the Syntra registration.');
|
|
616
|
+
}
|
|
617
|
+
const remaining = registrationPath.slice(index);
|
|
618
|
+
const nested = valueForMissingPath(remaining, registration);
|
|
619
|
+
const insertionKey = remaining[0];
|
|
620
|
+
const insertionValue = nested[insertionKey];
|
|
621
|
+
return insertJsonProperty(text, objectNode, insertionKey, insertionValue);
|
|
622
|
+
} catch (error) {
|
|
623
|
+
if (error instanceof SetupError) throw error;
|
|
624
|
+
fail(`The ${format.toUpperCase()} host config cannot be edited without ambiguity.`);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
function previewJsonRegistration(config, plan) {
|
|
629
|
+
const allowComments = plan.format === 'jsonc';
|
|
630
|
+
const before = config.exists
|
|
631
|
+
? parseJsonDocument(config.text, plan.format, allowComments)
|
|
632
|
+
: { tree: null, value: {} };
|
|
633
|
+
if (before.tree) checkJsonParentTypes(before.tree, plan.registrationPath);
|
|
634
|
+
const existing = before.tree
|
|
635
|
+
? getOwnPath(before.value, plan.registrationPath)
|
|
636
|
+
: { exists: false, value: undefined };
|
|
637
|
+
|
|
638
|
+
if (existing.exists) {
|
|
639
|
+
if (!isDeepStrictEqual(deepPlainCopy(existing.value), deepPlainCopy(plan.registration))) {
|
|
640
|
+
fail('A different Syntra host registration already exists; it was not changed.');
|
|
641
|
+
}
|
|
642
|
+
return { changed: false, status: 'matching', safeDelta: null };
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
const proposedText = computeJsonCandidate(
|
|
646
|
+
config.text,
|
|
647
|
+
plan.registrationPath,
|
|
648
|
+
plan.registration,
|
|
649
|
+
plan.format,
|
|
650
|
+
before.tree,
|
|
651
|
+
);
|
|
652
|
+
|
|
653
|
+
const after = parseJsonDocument(proposedText, plan.format, allowComments);
|
|
654
|
+
const afterRegistration = getOwnPath(after.value, plan.registrationPath);
|
|
655
|
+
if (!afterRegistration.exists || !isDeepStrictEqual(
|
|
656
|
+
deepPlainCopy(afterRegistration.value),
|
|
657
|
+
deepPlainCopy(plan.registration),
|
|
658
|
+
)) {
|
|
659
|
+
fail('The proposed host registration could not be validated.');
|
|
660
|
+
}
|
|
661
|
+
const oldUnrelated = removeRegistrationAndNewParents(before.value, plan.registrationPath, before.value);
|
|
662
|
+
const newUnrelated = removeRegistrationAndNewParents(after.value, plan.registrationPath, before.value);
|
|
663
|
+
if (!isDeepStrictEqual(oldUnrelated, newUnrelated)) {
|
|
664
|
+
fail('The proposed host edit would alter unrelated settings.');
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
return {
|
|
668
|
+
changed: true,
|
|
669
|
+
status: 'add',
|
|
670
|
+
safeDelta: {
|
|
671
|
+
path: plan.registrationPath.join('.'),
|
|
672
|
+
value: plan.registration,
|
|
673
|
+
},
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
function normalizeTomlValue(value) {
|
|
678
|
+
if (Array.isArray(value)) return value.map(normalizeTomlValue);
|
|
679
|
+
if (value instanceof Date) return value.toISOString();
|
|
680
|
+
if (!value || typeof value !== 'object') return value;
|
|
681
|
+
const normalized = {};
|
|
682
|
+
for (const key of Object.keys(value).sort()) normalized[key] = normalizeTomlValue(value[key]);
|
|
683
|
+
return normalized;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
function computeTomlCandidate(text, snippet) {
|
|
687
|
+
const remainder = text.replace(/\r\n/g, '');
|
|
688
|
+
const lineEnding = text.includes('\r\n') && !remainder.includes('\n') ? '\r\n' : '\n';
|
|
689
|
+
const separator = !text ? '' : (text.endsWith('\n') || text.endsWith('\r') ? '' : lineEnding);
|
|
690
|
+
const formattedSnippet = snippet.replace(/\r\n|\n/g, lineEnding);
|
|
691
|
+
return `${text}${separator}${formattedSnippet}`;
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
function previewTomlRegistration(config, plan) {
|
|
695
|
+
let before;
|
|
696
|
+
try {
|
|
697
|
+
before = config.exists ? toml.parse(config.text) : Object.create(null);
|
|
698
|
+
} catch {
|
|
699
|
+
fail('The TOML host config is malformed.');
|
|
700
|
+
}
|
|
701
|
+
const existing = getOwnPath(before, plan.registrationPath);
|
|
702
|
+
if (existing.exists) {
|
|
703
|
+
if (!isDeepStrictEqual(normalizeTomlValue(existing.value), normalizeTomlValue(plan.registration))) {
|
|
704
|
+
fail('A different Syntra host registration already exists; it was not changed.');
|
|
705
|
+
}
|
|
706
|
+
return { changed: false, status: 'matching', safeDelta: null };
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
const snippet = plan.tomlSnippet;
|
|
710
|
+
const proposedText = computeTomlCandidate(config.text, snippet);
|
|
711
|
+
let after;
|
|
712
|
+
try {
|
|
713
|
+
after = toml.parse(proposedText);
|
|
714
|
+
} catch {
|
|
715
|
+
fail('The TOML host config cannot safely accept the Syntra table.');
|
|
716
|
+
}
|
|
717
|
+
const afterRegistration = getOwnPath(after, plan.registrationPath);
|
|
718
|
+
if (!afterRegistration.exists || !isDeepStrictEqual(
|
|
719
|
+
normalizeTomlValue(afterRegistration.value),
|
|
720
|
+
normalizeTomlValue(plan.registration),
|
|
721
|
+
)) {
|
|
722
|
+
fail('The proposed TOML registration could not be validated.');
|
|
723
|
+
}
|
|
724
|
+
if (!isDeepStrictEqual(
|
|
725
|
+
normalizeTomlValue(removeRegistrationAndNewParents(after, plan.registrationPath, before)),
|
|
726
|
+
normalizeTomlValue(removeRegistrationAndNewParents(before, plan.registrationPath, before)),
|
|
727
|
+
)) {
|
|
728
|
+
fail('The proposed TOML edit would alter unrelated settings.');
|
|
729
|
+
}
|
|
730
|
+
return {
|
|
731
|
+
changed: true,
|
|
732
|
+
status: 'add',
|
|
733
|
+
safeDelta: { path: plan.registrationPath.join('.'), toml: snippet },
|
|
734
|
+
};
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
function buildPlan(agent, env = process.env, platform = process.platform) {
|
|
738
|
+
const plan = hostPlan(agent, env, platform);
|
|
739
|
+
inspectPath(plan.configPath, 'file', platform);
|
|
740
|
+
inspectPath(plan.skillPath, 'directory', platform);
|
|
741
|
+
const config = readConfig(plan.configPath, plan.format, platform);
|
|
742
|
+
const bundle = readBundledSkill();
|
|
743
|
+
const skillStatus = inspectExistingSkill(plan.skillPath, bundle.files, platform);
|
|
744
|
+
if (skillStatus === 'conflict') {
|
|
745
|
+
fail('The existing Syntra skill differs from the bundled files; it was preserved.');
|
|
746
|
+
}
|
|
747
|
+
const registration = plan.format === 'toml'
|
|
748
|
+
? previewTomlRegistration(config, plan)
|
|
749
|
+
: previewJsonRegistration(config, plan);
|
|
750
|
+
return {
|
|
751
|
+
...plan,
|
|
752
|
+
configExists: config.exists,
|
|
753
|
+
configSnapshot: config.snapshot,
|
|
754
|
+
bundleFiles: bundle.files,
|
|
755
|
+
registration,
|
|
756
|
+
skillStatus,
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
function renderPlan(plan) {
|
|
761
|
+
const lines = [
|
|
762
|
+
`Syntra setup preview for ${plan.displayName}`,
|
|
763
|
+
`Config: ${plan.configPath}${plan.configExists ? '' : ' (not created)'}`,
|
|
764
|
+
`Bundled skill destination: ${plan.skillPath}`,
|
|
765
|
+
];
|
|
766
|
+
|
|
767
|
+
if (plan.registration.status === 'matching') {
|
|
768
|
+
lines.push('MCP registration: the exact pinned Syntra entry is already present.');
|
|
769
|
+
} else {
|
|
770
|
+
lines.push('Proposed Syntra-only config change (unrelated settings are omitted):');
|
|
771
|
+
if (plan.registration.safeDelta.toml) {
|
|
772
|
+
for (const line of plan.registration.safeDelta.toml.trimEnd().split('\n')) lines.push(`+ ${line}`);
|
|
773
|
+
} else {
|
|
774
|
+
lines.push(`+ ${plan.registration.safeDelta.path} = ${JSON.stringify(plan.registration.safeDelta.value, null, 2)}`);
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
if (plan.skillStatus === 'matching') {
|
|
779
|
+
lines.push('Bundled skill: the destination already matches the packaged files.');
|
|
780
|
+
} else {
|
|
781
|
+
lines.push('+ install the bundled skill files (SKILL.md and references/tools.md).');
|
|
782
|
+
}
|
|
783
|
+
lines.push('Dry run only: no files were changed.');
|
|
784
|
+
return `${lines.join('\n')}\n`;
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
function readRegularSnapshot(targetPath, allowHardlinks = false) {
|
|
788
|
+
let fd;
|
|
789
|
+
try {
|
|
790
|
+
const beforePath = fs.lstatSync(targetPath);
|
|
791
|
+
if (beforePath.isSymbolicLink() || !beforePath.isFile() || (!allowHardlinks && beforePath.nlink > 1)) return null;
|
|
792
|
+
const noFollow = fs.constants.O_NOFOLLOW || 0;
|
|
793
|
+
fd = fs.openSync(targetPath, fs.constants.O_RDONLY | noFollow);
|
|
794
|
+
const before = fs.fstatSync(fd);
|
|
795
|
+
const bytes = fs.readFileSync(fd);
|
|
796
|
+
const after = fs.fstatSync(fd);
|
|
797
|
+
const afterPath = fs.lstatSync(targetPath);
|
|
798
|
+
if (!sameFileObservation(before, after) || !sameFileObservation(after, afterPath)) return null;
|
|
799
|
+
return { bytes, identity: fileObservation(after) };
|
|
800
|
+
} catch {
|
|
801
|
+
return null;
|
|
802
|
+
} finally {
|
|
803
|
+
if (fd !== undefined) {
|
|
804
|
+
try { fs.closeSync(fd); } catch { /* The snapshot is discarded if closing is relevant. */ }
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
function safeRemoveOwnedFile(record, allowPrefix = false) {
|
|
810
|
+
if (!record) return true;
|
|
811
|
+
const snapshot = readRegularSnapshot(record.path, record.allowHardlinks === true);
|
|
812
|
+
if (!snapshot || !sameFileIdentity(record.identity, snapshot.identity)) return false;
|
|
813
|
+
const expected = record.bytes;
|
|
814
|
+
const matches = snapshot.bytes.equals(expected) ||
|
|
815
|
+
(allowPrefix && snapshot.bytes.length <= expected.length &&
|
|
816
|
+
expected.subarray(0, snapshot.bytes.length).equals(snapshot.bytes));
|
|
817
|
+
if (!matches) return false;
|
|
818
|
+
try {
|
|
819
|
+
fs.unlinkSync(record.path);
|
|
820
|
+
return true;
|
|
821
|
+
} catch {
|
|
822
|
+
return false;
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
function safeRemoveOwnedDirectory(record) {
|
|
827
|
+
if (!record) return true;
|
|
828
|
+
try {
|
|
829
|
+
const stat = fs.lstatSync(record.path);
|
|
830
|
+
if (stat.isSymbolicLink() || !stat.isDirectory() ||
|
|
831
|
+
!sameFileIdentity(record.identity, fileObservation(stat))) return false;
|
|
832
|
+
fs.rmdirSync(record.path);
|
|
833
|
+
return true;
|
|
834
|
+
} catch (error) {
|
|
835
|
+
if (error && error.code === 'ENOENT') return true;
|
|
836
|
+
return false;
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
function createExclusiveFile(targetPath, bytes, mode, platform) {
|
|
841
|
+
const expected = Buffer.from(bytes);
|
|
842
|
+
let fd;
|
|
843
|
+
let identity = null;
|
|
844
|
+
try {
|
|
845
|
+
const noFollow = fs.constants.O_NOFOLLOW || 0;
|
|
846
|
+
fd = fs.openSync(
|
|
847
|
+
targetPath,
|
|
848
|
+
fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | noFollow,
|
|
849
|
+
mode,
|
|
850
|
+
);
|
|
851
|
+
identity = fileObservation(fs.fstatSync(fd));
|
|
852
|
+
if (platform !== 'win32') fs.fchmodSync(fd, mode & 0o777);
|
|
853
|
+
writeAll(fd, expected);
|
|
854
|
+
fs.fsyncSync(fd);
|
|
855
|
+
const stat = fs.fstatSync(fd);
|
|
856
|
+
if (!sameFileIdentity(identity, fileObservation(stat)) || stat.size !== expected.length) {
|
|
857
|
+
fail('A setup file changed while it was being written.');
|
|
858
|
+
}
|
|
859
|
+
identity = fileObservation(stat);
|
|
860
|
+
return { path: targetPath, identity, bytes: expected, mode: mode & 0o777 };
|
|
861
|
+
} catch (error) {
|
|
862
|
+
if (identity) safeRemoveOwnedFile({ path: targetPath, identity, bytes: expected }, true);
|
|
863
|
+
if (error instanceof SetupError) throw error;
|
|
864
|
+
fail('A private setup file could not be created safely.');
|
|
865
|
+
} finally {
|
|
866
|
+
if (fd !== undefined) {
|
|
867
|
+
try { fs.closeSync(fd); } catch { /* The operation result has already been determined. */ }
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
function createExclusiveDirectory(targetPath, mode, platform) {
|
|
873
|
+
let created = null;
|
|
874
|
+
try {
|
|
875
|
+
fs.mkdirSync(targetPath, { mode });
|
|
876
|
+
const initial = fs.lstatSync(targetPath);
|
|
877
|
+
if (initial.isSymbolicLink() || !initial.isDirectory()) fail('A setup directory was replaced unexpectedly.');
|
|
878
|
+
const identity = fileObservation(initial);
|
|
879
|
+
created = { path: targetPath, identity };
|
|
880
|
+
if (platform !== 'win32') fs.chmodSync(targetPath, mode & 0o777);
|
|
881
|
+
const finalStat = fs.lstatSync(targetPath);
|
|
882
|
+
if (!sameFileIdentity(identity, fileObservation(finalStat)) || !finalStat.isDirectory()) {
|
|
883
|
+
fail('A setup directory changed while it was being created.');
|
|
884
|
+
}
|
|
885
|
+
return { path: targetPath, identity: fileObservation(finalStat) };
|
|
886
|
+
} catch (error) {
|
|
887
|
+
if (created) safeRemoveOwnedDirectory(created);
|
|
888
|
+
if (error instanceof SetupError) throw error;
|
|
889
|
+
if (error && error.code === 'EEXIST') fail('A setup destination appeared during installation.');
|
|
890
|
+
fail('A setup directory could not be created safely.');
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
function syncDirectory(targetPath, platform) {
|
|
895
|
+
if (platform === 'win32') return false;
|
|
896
|
+
let fd;
|
|
897
|
+
try {
|
|
898
|
+
const directoryFlag = fs.constants.O_DIRECTORY || 0;
|
|
899
|
+
fd = fs.openSync(targetPath, fs.constants.O_RDONLY | directoryFlag);
|
|
900
|
+
fs.fsyncSync(fd);
|
|
901
|
+
return true;
|
|
902
|
+
} catch (error) {
|
|
903
|
+
if (error && ['EINVAL', 'ENOTSUP', 'EISDIR', 'EBADF'].includes(error.code)) return false;
|
|
904
|
+
throw error;
|
|
905
|
+
} finally {
|
|
906
|
+
if (fd !== undefined) {
|
|
907
|
+
try { fs.closeSync(fd); } catch { /* Directory durability is best-effort on supported hosts. */ }
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
function createSkillStage(plan, token, platform) {
|
|
913
|
+
const paths = pathApi(platform);
|
|
914
|
+
const parent = paths.dirname(plan.skillPath);
|
|
915
|
+
const rootPath = paths.join(parent, `.syntra-skill-stage-${token}`);
|
|
916
|
+
const stage = { root: null, directories: [], files: [] };
|
|
917
|
+
try {
|
|
918
|
+
stage.root = createExclusiveDirectory(rootPath, 0o700, platform);
|
|
919
|
+
const referencesPath = paths.join(rootPath, 'references');
|
|
920
|
+
stage.directories.push(createExclusiveDirectory(referencesPath, 0o755, platform));
|
|
921
|
+
for (const [relative, bytes] of plan.bundleFiles) {
|
|
922
|
+
const target = paths.join(rootPath, ...relative.split('/'));
|
|
923
|
+
stage.files.push(createExclusiveFile(target, bytes, 0o644, platform));
|
|
924
|
+
}
|
|
925
|
+
return stage;
|
|
926
|
+
} catch (error) {
|
|
927
|
+
cleanupSkillStage(stage);
|
|
928
|
+
throw error;
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
function cleanupSkillStage(stage) {
|
|
933
|
+
if (!stage) return true;
|
|
934
|
+
let clean = true;
|
|
935
|
+
for (const file of [...stage.files].reverse()) {
|
|
936
|
+
if (!safeRemoveOwnedFile(file)) clean = false;
|
|
937
|
+
}
|
|
938
|
+
for (const directory of [...stage.directories].reverse()) {
|
|
939
|
+
if (!safeRemoveOwnedDirectory(directory)) clean = false;
|
|
940
|
+
}
|
|
941
|
+
if (stage.root && !safeRemoveOwnedDirectory(stage.root)) clean = false;
|
|
942
|
+
return clean;
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
function installStagedSkill(plan, stage, platform) {
|
|
946
|
+
const paths = pathApi(platform);
|
|
947
|
+
const installed = { directories: [], files: [] };
|
|
948
|
+
const current = inspectExistingSkill(plan.skillPath, plan.bundleFiles, platform);
|
|
949
|
+
if (current === 'matching') return installed;
|
|
950
|
+
if (current !== 'absent') fail('The Syntra skill destination changed and was preserved.');
|
|
951
|
+
|
|
952
|
+
try {
|
|
953
|
+
const root = createExclusiveDirectory(plan.skillPath, 0o755, platform);
|
|
954
|
+
installed.directories.push(root);
|
|
955
|
+
const referencesPath = paths.join(plan.skillPath, 'references');
|
|
956
|
+
installed.directories.push(createExclusiveDirectory(referencesPath, 0o755, platform));
|
|
957
|
+
for (const [relative, bytes] of plan.bundleFiles) {
|
|
958
|
+
const staged = stage.files.find(file => file.path === paths.join(stage.root.path, ...relative.split('/')));
|
|
959
|
+
if (!staged) fail('The staged Syntra skill is incomplete.');
|
|
960
|
+
const destination = paths.join(plan.skillPath, ...relative.split('/'));
|
|
961
|
+
fs.linkSync(staged.path, destination);
|
|
962
|
+
staged.allowHardlinks = true;
|
|
963
|
+
const stat = fs.lstatSync(destination);
|
|
964
|
+
if (stat.isSymbolicLink() || !stat.isFile() || stat.size !== bytes.length) {
|
|
965
|
+
fail('A bundled skill file changed while it was being installed.');
|
|
966
|
+
}
|
|
967
|
+
installed.files.push({
|
|
968
|
+
path: destination,
|
|
969
|
+
identity: fileObservation(stat),
|
|
970
|
+
bytes,
|
|
971
|
+
allowHardlinks: true,
|
|
972
|
+
});
|
|
973
|
+
}
|
|
974
|
+
for (const file of stage.files) {
|
|
975
|
+
if (!safeRemoveOwnedFile(file)) fail('A staged Syntra skill file could not be removed safely.');
|
|
976
|
+
}
|
|
977
|
+
if (!safeRemoveOwnedDirectory(stage.directories[0]) || !safeRemoveOwnedDirectory(stage.root)) {
|
|
978
|
+
fail('A staged Syntra skill directory could not be removed safely.');
|
|
979
|
+
}
|
|
980
|
+
stage.files = [];
|
|
981
|
+
stage.directories = [];
|
|
982
|
+
stage.root = null;
|
|
983
|
+
if (inspectExistingSkill(plan.skillPath, plan.bundleFiles, platform) !== 'matching') {
|
|
984
|
+
fail('The installed Syntra skill did not match its packaged files.');
|
|
985
|
+
}
|
|
986
|
+
return installed;
|
|
987
|
+
} catch (error) {
|
|
988
|
+
error.setupInstalledSkill = installed;
|
|
989
|
+
throw error;
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
function rollbackInstalledSkill(installed) {
|
|
994
|
+
if (!installed) return true;
|
|
995
|
+
let safe = true;
|
|
996
|
+
for (const file of [...installed.files].reverse()) {
|
|
997
|
+
if (!safeRemoveOwnedFile(file)) safe = false;
|
|
998
|
+
}
|
|
999
|
+
for (const directory of [...installed.directories].reverse()) {
|
|
1000
|
+
if (!safeRemoveOwnedDirectory(directory)) safe = false;
|
|
1001
|
+
}
|
|
1002
|
+
return safe;
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
function acquireSetupLock(lockPath, agent, platform) {
|
|
1006
|
+
try {
|
|
1007
|
+
const existing = fs.lstatSync(lockPath);
|
|
1008
|
+
if (existing.isSymbolicLink()) fail('The Syntra setup lock path is a symbolic link.');
|
|
1009
|
+
fail(`A Syntra setup lock already exists at ${lockPath}. Confirm no setup is active, then remove this stale lock manually before retrying.`);
|
|
1010
|
+
} catch (error) {
|
|
1011
|
+
if (error instanceof SetupError) throw error;
|
|
1012
|
+
if (!error || error.code !== 'ENOENT') fail('The Syntra setup lock could not be inspected safely.');
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
let fd;
|
|
1016
|
+
let identity = null;
|
|
1017
|
+
const token = randomUUID();
|
|
1018
|
+
const ownerBytes = Buffer.from(`${JSON.stringify({ version: 1, token, pid: process.pid, agent, startedAt: new Date().toISOString() })}\n`);
|
|
1019
|
+
try {
|
|
1020
|
+
const noFollow = fs.constants.O_NOFOLLOW || 0;
|
|
1021
|
+
fd = fs.openSync(
|
|
1022
|
+
lockPath,
|
|
1023
|
+
fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | noFollow,
|
|
1024
|
+
0o600,
|
|
1025
|
+
);
|
|
1026
|
+
identity = fileObservation(fs.fstatSync(fd));
|
|
1027
|
+
if (platform !== 'win32') fs.fchmodSync(fd, 0o600);
|
|
1028
|
+
writeAll(fd, ownerBytes);
|
|
1029
|
+
fs.fsyncSync(fd);
|
|
1030
|
+
identity = fileObservation(fs.fstatSync(fd));
|
|
1031
|
+
return { path: lockPath, fd, identity, token, ownerBytes };
|
|
1032
|
+
} catch (error) {
|
|
1033
|
+
if (fd !== undefined) {
|
|
1034
|
+
if (identity) safeRemoveOwnedFile({ path: lockPath, identity, bytes: ownerBytes }, true);
|
|
1035
|
+
try { fs.closeSync(fd); } catch { /* The lock creation failure is reported below. */ }
|
|
1036
|
+
}
|
|
1037
|
+
if (error instanceof SetupError) throw error;
|
|
1038
|
+
if (error && error.code === 'EEXIST') {
|
|
1039
|
+
fail(`A Syntra setup lock already exists at ${lockPath}. Confirm no setup is active, then remove this stale lock manually before retrying.`);
|
|
1040
|
+
}
|
|
1041
|
+
fail('A Syntra setup lock could not be created safely.');
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
function releaseSetupLock(lock, platform) {
|
|
1046
|
+
if (!lock) return true;
|
|
1047
|
+
let released = false;
|
|
1048
|
+
try {
|
|
1049
|
+
const current = readRegularSnapshot(lock.path);
|
|
1050
|
+
if (!current || !sameFileIdentity(lock.identity, current.identity)) return false;
|
|
1051
|
+
let owner;
|
|
1052
|
+
try { owner = JSON.parse(current.bytes.toString('utf8')); } catch { return false; }
|
|
1053
|
+
if (!owner || owner.token !== lock.token) return false;
|
|
1054
|
+
fs.unlinkSync(lock.path);
|
|
1055
|
+
released = true;
|
|
1056
|
+
syncDirectory(path.dirname(lock.path), platform);
|
|
1057
|
+
return true;
|
|
1058
|
+
} catch {
|
|
1059
|
+
return false;
|
|
1060
|
+
} finally {
|
|
1061
|
+
try { fs.closeSync(lock.fd); } catch { /* The lock path has already been handled. */ }
|
|
1062
|
+
if (!released) {
|
|
1063
|
+
// The lock is intentionally left in place if its identity or owner cannot be verified.
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
function createBackup(plan, token, platform) {
|
|
1069
|
+
if (!plan.configSnapshot.exists) return null;
|
|
1070
|
+
const paths = pathApi(platform);
|
|
1071
|
+
const targetPath = paths.join(
|
|
1072
|
+
paths.dirname(plan.configPath),
|
|
1073
|
+
`.${paths.basename(plan.configPath)}.syntra-backup-${token}`,
|
|
1074
|
+
);
|
|
1075
|
+
return createExclusiveFile(targetPath, plan.configSnapshot.bytes, 0o600, platform);
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
function configCandidate(plan) {
|
|
1079
|
+
if (!plan.registration.changed) return null;
|
|
1080
|
+
const text = plan.format === 'toml'
|
|
1081
|
+
? computeTomlCandidate(plan.configSnapshot.exists ? new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(plan.configSnapshot.bytes) : '', plan.tomlSnippet)
|
|
1082
|
+
: computeJsonCandidate(
|
|
1083
|
+
plan.configSnapshot.exists ? new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(plan.configSnapshot.bytes) : '',
|
|
1084
|
+
plan.registrationPath,
|
|
1085
|
+
plan.registration.safeDelta.value,
|
|
1086
|
+
plan.format,
|
|
1087
|
+
);
|
|
1088
|
+
return Buffer.from(text, 'utf8');
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
function assertConfigUnchanged(plan, platform) {
|
|
1092
|
+
const current = readConfig(plan.configPath, plan.format, platform).snapshot;
|
|
1093
|
+
if (!sameConfigSnapshot(plan.configSnapshot, current)) {
|
|
1094
|
+
fail('The host config changed during setup; the concurrent edit was preserved. Retry the setup command.');
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
function assertInstalledSkill(plan, platform) {
|
|
1099
|
+
inspectPath(plan.skillPath, 'directory', platform);
|
|
1100
|
+
if (inspectExistingSkill(plan.skillPath, plan.bundleFiles, platform) !== 'matching') {
|
|
1101
|
+
fail('The bundled skill changed during setup; it was preserved and the registration was not committed.');
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
function assertBackupIntact(backup, plan, platform) {
|
|
1106
|
+
if (!plan.configSnapshot.exists) {
|
|
1107
|
+
if (backup) fail('An unexpected setup backup was created.');
|
|
1108
|
+
return;
|
|
1109
|
+
}
|
|
1110
|
+
const snapshot = backup && readRegularSnapshot(backup.path);
|
|
1111
|
+
const privateMode = platform === 'win32' || (snapshot && snapshot.identity.mode === 0o600);
|
|
1112
|
+
if (!snapshot || !sameFileIdentity(backup.identity, snapshot.identity) ||
|
|
1113
|
+
!isDeepStrictEqual(backup.identity, snapshot.identity) ||
|
|
1114
|
+
!snapshot.bytes.equals(plan.configSnapshot.bytes) || !privateMode) {
|
|
1115
|
+
fail('The private config backup changed during setup; it was preserved and the registration was not committed.');
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
function publishConfig(plan, staged, platform, onValidated) {
|
|
1120
|
+
inspectPath(plan.configPath, 'file', platform);
|
|
1121
|
+
assertConfigUnchanged(plan, platform);
|
|
1122
|
+
if (typeof onValidated === 'function') onValidated();
|
|
1123
|
+
if (plan.configSnapshot.exists) {
|
|
1124
|
+
fs.renameSync(staged.path, plan.configPath);
|
|
1125
|
+
} else {
|
|
1126
|
+
fs.linkSync(staged.path, plan.configPath);
|
|
1127
|
+
staged.allowHardlinks = true;
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
function applySetup(agent, options = {}) {
|
|
1132
|
+
const env = options.env || process.env;
|
|
1133
|
+
const platform = options.platform || process.platform;
|
|
1134
|
+
const testHooks = options.testHooks || Object.create(null);
|
|
1135
|
+
const initialPlan = buildPlan(agent, env, platform);
|
|
1136
|
+
const initiallyChanged = initialPlan.registration.changed || initialPlan.skillStatus === 'absent';
|
|
1137
|
+
if (!initiallyChanged) {
|
|
1138
|
+
return { plan: initialPlan, configChanged: false, skillInstalled: false, backupPath: null, unchanged: true };
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
const paths = pathApi(platform);
|
|
1142
|
+
const createdDirectories = [];
|
|
1143
|
+
const lockPath = `${initialPlan.configPath}.syntra.lock`;
|
|
1144
|
+
let lock = null;
|
|
1145
|
+
let stagedConfig = null;
|
|
1146
|
+
let stagedSkill = null;
|
|
1147
|
+
let backup = null;
|
|
1148
|
+
let installedSkill = null;
|
|
1149
|
+
let configCommitted = false;
|
|
1150
|
+
let configVerified = false;
|
|
1151
|
+
let keepLock = false;
|
|
1152
|
+
let result = null;
|
|
1153
|
+
|
|
1154
|
+
const phase = (name, details) => {
|
|
1155
|
+
if (typeof testHooks.onPhase === 'function') testHooks.onPhase(name, details);
|
|
1156
|
+
};
|
|
1157
|
+
|
|
1158
|
+
try {
|
|
1159
|
+
ensureDirectoryChain(paths.dirname(lockPath), platform, createdDirectories);
|
|
1160
|
+
lock = acquireSetupLock(lockPath, agent, platform);
|
|
1161
|
+
syncDirectory(paths.dirname(lockPath), platform);
|
|
1162
|
+
phase('lock-acquired', { lockPath });
|
|
1163
|
+
|
|
1164
|
+
const plan = buildPlan(agent, env, platform);
|
|
1165
|
+
if (!plan.registration.changed && plan.skillStatus === 'matching') {
|
|
1166
|
+
result = { plan, configChanged: false, skillInstalled: false, backupPath: null, unchanged: true };
|
|
1167
|
+
return result;
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
if (plan.skillStatus === 'absent') {
|
|
1171
|
+
ensureDirectoryChain(paths.dirname(plan.skillPath), platform, createdDirectories);
|
|
1172
|
+
stagedSkill = createSkillStage(plan, lock.token, platform);
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
const candidate = configCandidate(plan);
|
|
1176
|
+
if (candidate) {
|
|
1177
|
+
const tempPath = paths.join(paths.dirname(plan.configPath), `.${paths.basename(plan.configPath)}.syntra-tmp-${lock.token}`);
|
|
1178
|
+
const mode = plan.configSnapshot.exists ? plan.configSnapshot.mode : 0o600;
|
|
1179
|
+
stagedConfig = createExclusiveFile(tempPath, candidate, mode, platform);
|
|
1180
|
+
}
|
|
1181
|
+
phase('staged', { configChanged: Boolean(candidate), skillInstall: Boolean(stagedSkill) });
|
|
1182
|
+
|
|
1183
|
+
if (candidate) {
|
|
1184
|
+
assertConfigUnchanged(plan, platform);
|
|
1185
|
+
backup = createBackup(plan, lock.token, platform);
|
|
1186
|
+
if (backup) syncDirectory(paths.dirname(backup.path), platform);
|
|
1187
|
+
phase('backup-created', { backupPath: backup && backup.path });
|
|
1188
|
+
assertBackupIntact(backup, plan, platform);
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
if (stagedSkill) {
|
|
1192
|
+
try {
|
|
1193
|
+
installedSkill = installStagedSkill(plan, stagedSkill, platform);
|
|
1194
|
+
} catch (error) {
|
|
1195
|
+
installedSkill = error && error.setupInstalledSkill;
|
|
1196
|
+
throw error;
|
|
1197
|
+
}
|
|
1198
|
+
phase('skill-installed', { skillPath: plan.skillPath });
|
|
1199
|
+
assertInstalledSkill(plan, platform);
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
if (candidate) {
|
|
1203
|
+
phase('before-config-publish', { configPath: plan.configPath });
|
|
1204
|
+
publishConfig(plan, stagedConfig, platform, () => {
|
|
1205
|
+
phase('config-validated', { configPath: plan.configPath });
|
|
1206
|
+
assertInstalledSkill(plan, platform);
|
|
1207
|
+
assertBackupIntact(backup, plan, platform);
|
|
1208
|
+
if (plan.configSnapshot.exists) assertConfigUnchanged(plan, platform);
|
|
1209
|
+
});
|
|
1210
|
+
configCommitted = true;
|
|
1211
|
+
const published = readRegularSnapshot(plan.configPath, !plan.configSnapshot.exists);
|
|
1212
|
+
if (!published || !published.bytes.equals(stagedConfig.bytes)) {
|
|
1213
|
+
keepLock = true;
|
|
1214
|
+
fail('The host config could not be verified after replacement; its backup was retained.');
|
|
1215
|
+
}
|
|
1216
|
+
configVerified = true;
|
|
1217
|
+
syncDirectory(paths.dirname(plan.configPath), platform);
|
|
1218
|
+
phase('config-published', { configPath: plan.configPath, backupPath: backup && backup.path });
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
result = {
|
|
1222
|
+
plan,
|
|
1223
|
+
configChanged: Boolean(candidate),
|
|
1224
|
+
skillInstalled: Boolean(installedSkill && installedSkill.directories.length),
|
|
1225
|
+
backupPath: backup && backup.path,
|
|
1226
|
+
unchanged: false,
|
|
1227
|
+
};
|
|
1228
|
+
return result;
|
|
1229
|
+
} catch (error) {
|
|
1230
|
+
let rollbackSafe = true;
|
|
1231
|
+
if (!configCommitted) {
|
|
1232
|
+
if (installedSkill && !rollbackInstalledSkill(installedSkill)) rollbackSafe = false;
|
|
1233
|
+
if (stagedSkill && !cleanupSkillStage(stagedSkill)) rollbackSafe = false;
|
|
1234
|
+
if (stagedConfig && !safeRemoveOwnedFile(stagedConfig)) rollbackSafe = false;
|
|
1235
|
+
if (rollbackSafe && backup && !safeRemoveOwnedFile(backup)) rollbackSafe = false;
|
|
1236
|
+
if (!rollbackSafe) keepLock = true;
|
|
1237
|
+
} else {
|
|
1238
|
+
keepLock = !configVerified;
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
if (!rollbackSafe) {
|
|
1242
|
+
fail(`Setup stopped after a filesystem change it could not safely roll back. The lock remains at ${lockPath}; confirm no setup is active, inspect the config, backup, and skill, then remove the lock manually before retrying.`);
|
|
1243
|
+
}
|
|
1244
|
+
if (error instanceof SetupError) throw error;
|
|
1245
|
+
fail(configCommitted
|
|
1246
|
+
? 'Setup changes were applied, but a final filesystem sync failed. The backup was retained; rerun setup to verify.'
|
|
1247
|
+
: 'Setup could not be completed safely; any concurrent user changes were preserved.');
|
|
1248
|
+
} finally {
|
|
1249
|
+
if (stagedSkill && !configCommitted) cleanupSkillStage(stagedSkill);
|
|
1250
|
+
if (stagedConfig && configCommitted) safeRemoveOwnedFile(stagedConfig);
|
|
1251
|
+
if (lock) {
|
|
1252
|
+
if (keepLock) {
|
|
1253
|
+
try { fs.closeSync(lock.fd); } catch { /* A retained stale lock needs manual recovery. */ }
|
|
1254
|
+
} else if (!releaseSetupLock(lock, platform)) {
|
|
1255
|
+
// An unverified lock is retained rather than risking another process's lock.
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
removeCreatedDirectories(createdDirectories);
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
function renderApplied(result) {
|
|
1263
|
+
const lines = [`Syntra setup complete for ${result.plan.displayName}`];
|
|
1264
|
+
if (result.unchanged) {
|
|
1265
|
+
lines.push('MCP registration and bundled skill already match the packaged files.');
|
|
1266
|
+
lines.push('No files were changed.');
|
|
1267
|
+
} else {
|
|
1268
|
+
if (result.configChanged) {
|
|
1269
|
+
lines.push(`MCP registration updated: ${result.plan.configPath}`);
|
|
1270
|
+
if (result.backupPath) lines.push(`Private config backup: ${result.backupPath}`);
|
|
1271
|
+
} else {
|
|
1272
|
+
lines.push('MCP registration already matches.');
|
|
1273
|
+
}
|
|
1274
|
+
lines.push(result.skillInstalled
|
|
1275
|
+
? `Bundled skill installed: ${result.plan.skillPath}`
|
|
1276
|
+
: `Bundled skill already matches: ${result.plan.skillPath}`);
|
|
1277
|
+
}
|
|
1278
|
+
const packagePin = `${packageManifest.name}@${packageManifest.version}`;
|
|
1279
|
+
lines.push(`First time on this machine? Run: npx -y ${packagePin} login`);
|
|
1280
|
+
lines.push('Approve the permissions you need in the browser. Agent sessions using the default Syntra profile share that login.');
|
|
1281
|
+
lines.push(`To check permissions and expiration, run: npx -y ${packagePin} status`);
|
|
1282
|
+
lines.push('Start a new agent session to load this registration.');
|
|
1283
|
+
return `${lines.join('\n')}\n`;
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
function runSetup(args, options = {}) {
|
|
1287
|
+
const parsed = parseSetupArgs(args);
|
|
1288
|
+
const env = options.env || process.env;
|
|
1289
|
+
const platform = options.platform || process.platform;
|
|
1290
|
+
if (parsed.dryRun) return renderPlan(buildPlan(parsed.agent, env, platform));
|
|
1291
|
+
return renderApplied(applySetup(parsed.agent, { ...options, env, platform }));
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
if (require.main === module) {
|
|
1295
|
+
try {
|
|
1296
|
+
process.stdout.write(runSetup(process.argv.slice(2)));
|
|
1297
|
+
} catch (error) {
|
|
1298
|
+
const message = error instanceof SetupError ? error.message : 'Setup preview could not be completed safely.';
|
|
1299
|
+
process.stderr.write(`syntra: ${message}\n`);
|
|
1300
|
+
process.exitCode = 1;
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
module.exports = {
|
|
1305
|
+
AGENT_NAMES,
|
|
1306
|
+
SetupError,
|
|
1307
|
+
applySetup,
|
|
1308
|
+
buildPlan,
|
|
1309
|
+
computeJsonCandidate,
|
|
1310
|
+
computeTomlCandidate,
|
|
1311
|
+
hostPlan,
|
|
1312
|
+
inspectPath,
|
|
1313
|
+
parseSetupArgs,
|
|
1314
|
+
renderPlan,
|
|
1315
|
+
runSetup,
|
|
1316
|
+
shellCommand,
|
|
1317
|
+
};
|