@yasaswy.nagavolu/agents 0.8.0
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/README.md +349 -0
- package/bin/cli.js +721 -0
- package/lib/agentsEnv.js +82 -0
- package/lib/components.js +256 -0
- package/lib/diff.js +157 -0
- package/lib/fsutil.js +99 -0
- package/lib/install.js +188 -0
- package/lib/ledger.js +116 -0
- package/lib/manifest.js +100 -0
- package/lib/mcpWiring.js +328 -0
- package/lib/menu.js +138 -0
- package/lib/secretsPrompt.js +319 -0
- package/lib/secretsStore.js +115 -0
- package/lib/selfProfile.js +173 -0
- package/lib/semver.js +11 -0
- package/lib/tty-menu.js +132 -0
- package/lib/uninstall.js +94 -0
- package/lib/update.js +363 -0
- package/lib/wiring.js +379 -0
- package/package.json +39 -0
- package/templates/litellm-config.yaml +95 -0
- package/templates/start-litellm.ps1 +47 -0
- package/templates/start-litellm.sh +51 -0
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const readline = require('node:readline');
|
|
4
|
+
const https = require('node:https');
|
|
5
|
+
const { readEnvFile } = require('./agentsEnv');
|
|
6
|
+
const { writeSecrets } = require('./secretsStore');
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Dedupe a set of selected bundles' declared secrets by name (first bundle
|
|
10
|
+
* to declare a name wins its prompt/hint text) — several bundles share e.g.
|
|
11
|
+
* LITELLM_MASTER_KEY, and we only want to ask once.
|
|
12
|
+
*/
|
|
13
|
+
function collectBundleSecrets(bundles) {
|
|
14
|
+
const seen = new Map();
|
|
15
|
+
for (const bundle of bundles || []) {
|
|
16
|
+
for (const secret of bundle.secrets || []) {
|
|
17
|
+
if (!seen.has(secret.name)) {
|
|
18
|
+
seen.set(secret.name, secret);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return [...seen.values()];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Secrets declared by the components any of `bundles` depend on (via
|
|
27
|
+
* `bundle.deps` -> `manifest.components[dep].secrets`), deduped by name the
|
|
28
|
+
* same way collectBundleSecrets is — first dep encountered (in bundle/deps
|
|
29
|
+
* array order) wins its prompt/hint text. Two dep-bundles sharing the same
|
|
30
|
+
* component (e.g. Councils and Web Search both depending on "litellm") only
|
|
31
|
+
* get its secrets collected once here. Requires `manifest` to resolve dep
|
|
32
|
+
* keys into component definitions; returns [] without one.
|
|
33
|
+
*/
|
|
34
|
+
function collectComponentSecrets(bundles, manifest) {
|
|
35
|
+
if (!manifest || !manifest.components) return [];
|
|
36
|
+
const seen = new Map();
|
|
37
|
+
for (const bundle of bundles || []) {
|
|
38
|
+
for (const depKey of bundle.deps || []) {
|
|
39
|
+
const component = manifest.components[depKey];
|
|
40
|
+
for (const secret of (component && component.secrets) || []) {
|
|
41
|
+
if (!seen.has(secret.name)) {
|
|
42
|
+
seen.set(secret.name, secret);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return [...seen.values()];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Is `name` already resolvable via the shared loader's resolution order
|
|
52
|
+
* (real env var, or non-empty value in targetBase/agents.env)? Prompting
|
|
53
|
+
* only asks for secrets that would NOT already resolve at hook runtime —
|
|
54
|
+
* asking again for a value already exported in the shell would be noise.
|
|
55
|
+
*/
|
|
56
|
+
function isResolved(name, targetBase) {
|
|
57
|
+
if (process.env[name]) return true;
|
|
58
|
+
const values = readEnvFile(targetBase);
|
|
59
|
+
return !!(values[name] && values[name].length > 0);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Read one line from `input`, terminated by '\n'. No echo/masking. */
|
|
63
|
+
function readPlainLine({ input }) {
|
|
64
|
+
return new Promise((resolve) => {
|
|
65
|
+
let buf = '';
|
|
66
|
+
function onData(chunk) {
|
|
67
|
+
buf += chunk.toString();
|
|
68
|
+
const idx = buf.indexOf('\n');
|
|
69
|
+
if (idx !== -1) {
|
|
70
|
+
input.removeListener('data', onData);
|
|
71
|
+
resolve(buf.slice(0, idx).replace(/\r$/, ''));
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
input.on('data', onData);
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Masked secret entry: raw-mode keypress echo of `*` per character when
|
|
80
|
+
* `input` is a real TTY (or a test double exposing isTTY + setRawMode).
|
|
81
|
+
* Falls back to plain (unmasked, explicitly warned) line entry otherwise —
|
|
82
|
+
* e.g. input piped from a file, or a minimal test double. Enter on an empty
|
|
83
|
+
* value resolves to '' (the caller treats that as "skip").
|
|
84
|
+
*/
|
|
85
|
+
function readMaskedSecret({ input, output, promptText }) {
|
|
86
|
+
return new Promise((resolve) => {
|
|
87
|
+
output.write(promptText);
|
|
88
|
+
const canMask = !!(input && input.isTTY && typeof input.setRawMode === 'function');
|
|
89
|
+
if (!canMask) {
|
|
90
|
+
output.write('\n(input is not a terminal — value will be entered without masking)\n');
|
|
91
|
+
readPlainLine({ input, output }).then(resolve);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
input.setRawMode(true);
|
|
96
|
+
if (typeof readline.emitKeypressEvents === 'function') {
|
|
97
|
+
readline.emitKeypressEvents(input);
|
|
98
|
+
}
|
|
99
|
+
let value = '';
|
|
100
|
+
const onKeypress = (str, key) => {
|
|
101
|
+
const k = key || {};
|
|
102
|
+
if (k.ctrl && k.name === 'c') {
|
|
103
|
+
cleanup();
|
|
104
|
+
output.write('\n');
|
|
105
|
+
process.exit(130);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (k.name === 'return' || k.name === 'enter') {
|
|
109
|
+
cleanup();
|
|
110
|
+
output.write('\n');
|
|
111
|
+
resolve(value);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
if (k.name === 'backspace') {
|
|
115
|
+
if (value.length > 0) {
|
|
116
|
+
value = value.slice(0, -1);
|
|
117
|
+
output.write('\b \b');
|
|
118
|
+
}
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
if (str) {
|
|
122
|
+
value += str;
|
|
123
|
+
output.write('*'.repeat(str.length));
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
function cleanup() {
|
|
127
|
+
try {
|
|
128
|
+
input.setRawMode(false);
|
|
129
|
+
} catch {
|
|
130
|
+
// best-effort — nothing more to do if the platform refuses
|
|
131
|
+
}
|
|
132
|
+
input.removeListener('keypress', onKeypress);
|
|
133
|
+
}
|
|
134
|
+
input.on('keypress', onKeypress);
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function askChoice({ input, output, promptText, choices, defaultChoice }) {
|
|
139
|
+
output.write(promptText);
|
|
140
|
+
const answer = (await readPlainLine({ input, output })).trim().toLowerCase();
|
|
141
|
+
if (!answer) return defaultChoice;
|
|
142
|
+
const match = choices.find((c) => c === answer || c.startsWith(answer));
|
|
143
|
+
return match || defaultChoice;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Live-validate a GitLab personal access token against GET
|
|
148
|
+
* https://gitlab.com/api/v4/user. 200 -> 'ok', 401 -> 'invalid', anything
|
|
149
|
+
* else (including a timeout or network error) -> 'network-error' (treated
|
|
150
|
+
* by the caller as warn-and-accept, never a hard failure).
|
|
151
|
+
*/
|
|
152
|
+
function validateGitlabToken(token) {
|
|
153
|
+
return new Promise((resolve) => {
|
|
154
|
+
let settled = false;
|
|
155
|
+
const finish = (status) => {
|
|
156
|
+
if (settled) return;
|
|
157
|
+
settled = true;
|
|
158
|
+
resolve({ status });
|
|
159
|
+
};
|
|
160
|
+
const req = https.get(
|
|
161
|
+
'https://gitlab.com/api/v4/user',
|
|
162
|
+
{ headers: { 'PRIVATE-TOKEN': token }, timeout: 5000 },
|
|
163
|
+
(res) => {
|
|
164
|
+
res.resume();
|
|
165
|
+
if (res.statusCode === 200) finish('ok');
|
|
166
|
+
else if (res.statusCode === 401) finish('invalid');
|
|
167
|
+
else finish('network-error');
|
|
168
|
+
}
|
|
169
|
+
);
|
|
170
|
+
req.on('timeout', () => {
|
|
171
|
+
req.destroy();
|
|
172
|
+
finish('network-error');
|
|
173
|
+
});
|
|
174
|
+
req.on('error', () => finish('network-error'));
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const DEFAULT_VALIDATORS = { GITLAB_TOKEN: validateGitlabToken };
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Prompt for, validate (where a validator is registered), and return the
|
|
182
|
+
* outcome for one secret. Loops on a failed live validation until the user
|
|
183
|
+
* picks retry / skip / keep.
|
|
184
|
+
*/
|
|
185
|
+
async function promptOneSecret({ secret, io, validator }) {
|
|
186
|
+
for (;;) {
|
|
187
|
+
// eslint-disable-next-line no-await-in-loop
|
|
188
|
+
const value = await readMaskedSecret({
|
|
189
|
+
input: io.input,
|
|
190
|
+
output: io.output,
|
|
191
|
+
promptText: `Enter ${secret.name} (Enter to skip): `,
|
|
192
|
+
});
|
|
193
|
+
if (!value) {
|
|
194
|
+
return { status: 'skipped' };
|
|
195
|
+
}
|
|
196
|
+
if (!validator) {
|
|
197
|
+
return { status: 'accepted', value };
|
|
198
|
+
}
|
|
199
|
+
// eslint-disable-next-line no-await-in-loop
|
|
200
|
+
const validation = await validator(value);
|
|
201
|
+
if (validation.status === 'ok') {
|
|
202
|
+
return { status: 'accepted', value };
|
|
203
|
+
}
|
|
204
|
+
if (validation.status === 'network-error') {
|
|
205
|
+
io.output.write(' Could not validate (network error) — accepting the value as entered.\n');
|
|
206
|
+
return { status: 'accepted', value };
|
|
207
|
+
}
|
|
208
|
+
io.output.write(' That value was rejected by validation (401 Unauthorized).\n');
|
|
209
|
+
// eslint-disable-next-line no-await-in-loop
|
|
210
|
+
const choice = await askChoice({
|
|
211
|
+
input: io.input,
|
|
212
|
+
output: io.output,
|
|
213
|
+
promptText: ' Retry, skip, or keep it anyway? [r/s/k] ',
|
|
214
|
+
choices: ['retry', 'skip', 'keep'],
|
|
215
|
+
defaultChoice: 'retry',
|
|
216
|
+
});
|
|
217
|
+
if (choice === 'skip') return { status: 'skipped' };
|
|
218
|
+
if (choice === 'keep') return { status: 'accepted', value };
|
|
219
|
+
// 'retry' falls through to loop again
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Prompt for every secret declared by `bundles` that is currently missing
|
|
225
|
+
* (per isResolved), skip entirely in a non-TTY environment (pointing the
|
|
226
|
+
* user at `agents-cli secrets`), and write every accepted value to
|
|
227
|
+
* targetBase/agents.env in a single batched write.
|
|
228
|
+
*
|
|
229
|
+
* `io` (test seam): { input, output } — defaults to process.stdin/stdout.
|
|
230
|
+
* `validators` (test seam): name -> async (value) => {status}; defaults to
|
|
231
|
+
* DEFAULT_VALIDATORS (GITLAB_TOKEN only; everything else is hint-only, no
|
|
232
|
+
* live check).
|
|
233
|
+
* `manifest` (optional): when given, secrets declared by any component a
|
|
234
|
+
* selected bundle depends on (manifest.components[dep].secrets — e.g.
|
|
235
|
+
* LITELLM_MASTER_KEY and the provider keys) are folded into the prompt list
|
|
236
|
+
* alongside each bundle's own `secrets`, deduped by name across both sources
|
|
237
|
+
* (bundle-level wins on a name collision) — see collectComponentSecrets.
|
|
238
|
+
*/
|
|
239
|
+
async function promptForMissingSecrets({ bundles, targetBase, io, validators, noSecrets, manifest, log = console.log }) {
|
|
240
|
+
const result = { written: [], skipped: [], alreadySet: [] };
|
|
241
|
+
if (noSecrets) {
|
|
242
|
+
return result;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const dedupedByName = new Map();
|
|
246
|
+
for (const secret of [...collectBundleSecrets(bundles), ...collectComponentSecrets(bundles, manifest)]) {
|
|
247
|
+
if (!dedupedByName.has(secret.name)) {
|
|
248
|
+
dedupedByName.set(secret.name, secret);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
const declared = [...dedupedByName.values()];
|
|
252
|
+
if (declared.length === 0) {
|
|
253
|
+
return result;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const resolvedIo = io || { input: process.stdin, output: process.stdout };
|
|
257
|
+
const isTTY = !!(resolvedIo.input && resolvedIo.input.isTTY && resolvedIo.output && resolvedIo.output.isTTY);
|
|
258
|
+
const activeValidators = validators || DEFAULT_VALIDATORS;
|
|
259
|
+
|
|
260
|
+
const missing = [];
|
|
261
|
+
for (const secret of declared) {
|
|
262
|
+
if (isResolved(secret.name, targetBase)) {
|
|
263
|
+
result.alreadySet.push(secret.name);
|
|
264
|
+
} else {
|
|
265
|
+
missing.push(secret);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
if (missing.length === 0) {
|
|
269
|
+
return result;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
if (!isTTY) {
|
|
273
|
+
log(
|
|
274
|
+
`\n${missing.length} secret(s) not yet configured (${missing.map((s) => s.name).join(', ')}). ` +
|
|
275
|
+
'Not running in a terminal — run "agents-cli secrets" to set them.'
|
|
276
|
+
);
|
|
277
|
+
result.skipped.push(...missing.map((s) => s.name));
|
|
278
|
+
return result;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const updates = {};
|
|
282
|
+
for (const secret of missing) {
|
|
283
|
+
log(`\n${secret.name} — ${secret.prompt}`);
|
|
284
|
+
if (secret.validationHint) {
|
|
285
|
+
log(` (${secret.validationHint})`);
|
|
286
|
+
}
|
|
287
|
+
// eslint-disable-next-line no-await-in-loop
|
|
288
|
+
const outcome = await promptOneSecret({ secret, io: resolvedIo, validator: activeValidators[secret.name] });
|
|
289
|
+
if (outcome.status === 'skipped') {
|
|
290
|
+
log(` Skipped ${secret.name}.`);
|
|
291
|
+
result.skipped.push(secret.name);
|
|
292
|
+
} else {
|
|
293
|
+
updates[secret.name] = outcome.value;
|
|
294
|
+
result.written.push(secret.name);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
if (Object.keys(updates).length > 0) {
|
|
299
|
+
const writeResult = writeSecrets(targetBase, updates);
|
|
300
|
+
if (writeResult.warning) {
|
|
301
|
+
log(` Warning: ${writeResult.warning}`);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
return result;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
module.exports = {
|
|
309
|
+
collectBundleSecrets,
|
|
310
|
+
collectComponentSecrets,
|
|
311
|
+
isResolved,
|
|
312
|
+
readMaskedSecret,
|
|
313
|
+
readPlainLine,
|
|
314
|
+
askChoice,
|
|
315
|
+
promptOneSecret,
|
|
316
|
+
promptForMissingSecrets,
|
|
317
|
+
validateGitlabToken,
|
|
318
|
+
DEFAULT_VALIDATORS,
|
|
319
|
+
};
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const os = require('node:os');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
const { spawnSync } = require('node:child_process');
|
|
7
|
+
const { writeFileAtomic } = require('./fsutil');
|
|
8
|
+
const { ENV_FILE_NAME, parseEnvFile } = require('./agentsEnv');
|
|
9
|
+
|
|
10
|
+
function envPath(targetBase) {
|
|
11
|
+
return path.join(targetBase, ENV_FILE_NAME);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Read targetBase/agents.env, returning both the parsed `values` (name ->
|
|
16
|
+
* value) and the raw `lines` (comments/blanks preserved, no trailing empty
|
|
17
|
+
* element from a final newline) so a caller can rewrite the file in place.
|
|
18
|
+
*/
|
|
19
|
+
function readSecrets(targetBase) {
|
|
20
|
+
const file = envPath(targetBase);
|
|
21
|
+
if (!fs.existsSync(file)) {
|
|
22
|
+
return { values: {}, lines: [] };
|
|
23
|
+
}
|
|
24
|
+
const raw = fs.readFileSync(file, 'utf8');
|
|
25
|
+
const lines = raw.split(/\r?\n/);
|
|
26
|
+
if (lines.length && lines[lines.length - 1] === '') {
|
|
27
|
+
lines.pop();
|
|
28
|
+
}
|
|
29
|
+
return { values: parseEnvFile(raw), lines };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Best-effort user-only permissions on `file`: `icacls ... /grant:r
|
|
34
|
+
* "%USERNAME%":F` on Windows, `chmod 0600` on POSIX. Never throws — a
|
|
35
|
+
* failure is returned as a `warning` string for the caller to surface, since
|
|
36
|
+
* losing the secrets file to a permissions error is worse than losing the
|
|
37
|
+
* (defense-in-depth) permission restriction itself.
|
|
38
|
+
*
|
|
39
|
+
* `spawnRunner`/`chmod` (test seams, same convention as wiring.js's
|
|
40
|
+
* `pythonChecker`): override the icacls invocation / chmod call so tests can
|
|
41
|
+
* assert the permissions step ran without depending on the real OS ACL
|
|
42
|
+
* layer. Both default to the real node:child_process.spawnSync / fs.chmodSync.
|
|
43
|
+
*/
|
|
44
|
+
function applyOwnerOnlyPermissions(file, { spawnRunner = spawnSync, chmod = fs.chmodSync } = {}) {
|
|
45
|
+
if (process.platform === 'win32') {
|
|
46
|
+
const user = process.env.USERNAME || (os.userInfo().username || '');
|
|
47
|
+
if (!user) {
|
|
48
|
+
return { ok: false, warning: `Could not determine the current user to restrict permissions on ${file}.` };
|
|
49
|
+
}
|
|
50
|
+
let result;
|
|
51
|
+
try {
|
|
52
|
+
result = spawnRunner('icacls', [file, '/inheritance:r', '/grant:r', `${user}:F`], { stdio: 'ignore' });
|
|
53
|
+
} catch (err) {
|
|
54
|
+
return { ok: false, warning: `Could not restrict permissions on ${file} (icacls failed: ${err.message}).` };
|
|
55
|
+
}
|
|
56
|
+
if (!result || result.error || result.status !== 0) {
|
|
57
|
+
return {
|
|
58
|
+
ok: false,
|
|
59
|
+
warning: `Could not restrict permissions on ${file} via icacls — it may be readable by other Windows accounts on this machine.`,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
return { ok: true, ran: 'icacls' };
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
chmod(file, 0o600);
|
|
66
|
+
return { ok: true, ran: 'chmod' };
|
|
67
|
+
} catch (err) {
|
|
68
|
+
return { ok: false, warning: `Could not chmod 0600 ${file}: ${err.message}` };
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Merge `updates` (name -> non-empty value) into targetBase/agents.env.
|
|
74
|
+
* Every existing line — including comments and blank lines — is preserved
|
|
75
|
+
* verbatim except a key being updated, which is rewritten in place at its
|
|
76
|
+
* existing line position; brand-new keys are appended at the end. Write is
|
|
77
|
+
* atomic (fsutil.writeFileAtomic); owner-only permissions are (re-)applied
|
|
78
|
+
* after every write. Values are never included in the return value or
|
|
79
|
+
* logged by this function.
|
|
80
|
+
*/
|
|
81
|
+
function writeSecrets(targetBase, updates, { spawnRunner, chmod } = {}) {
|
|
82
|
+
const entries = Object.entries(updates || {});
|
|
83
|
+
if (entries.length === 0) {
|
|
84
|
+
return { ok: true, wrote: false };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const file = envPath(targetBase);
|
|
88
|
+
const { lines } = readSecrets(targetBase);
|
|
89
|
+
const remaining = new Map(entries);
|
|
90
|
+
const outLines = [];
|
|
91
|
+
|
|
92
|
+
for (const line of lines) {
|
|
93
|
+
const trimmed = line.trim();
|
|
94
|
+
let key = null;
|
|
95
|
+
if (trimmed && !trimmed.startsWith('#')) {
|
|
96
|
+
const eq = trimmed.indexOf('=');
|
|
97
|
+
if (eq !== -1) key = trimmed.slice(0, eq).trim();
|
|
98
|
+
}
|
|
99
|
+
if (key && remaining.has(key)) {
|
|
100
|
+
outLines.push(`${key}=${remaining.get(key)}`);
|
|
101
|
+
remaining.delete(key);
|
|
102
|
+
} else {
|
|
103
|
+
outLines.push(line);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
for (const [key, value] of remaining) {
|
|
107
|
+
outLines.push(`${key}=${value}`);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
writeFileAtomic(file, `${outLines.join('\n')}\n`);
|
|
111
|
+
const perm = applyOwnerOnlyPermissions(file, { spawnRunner, chmod });
|
|
112
|
+
return { ok: perm.ok, wrote: true, warning: perm.warning, permissionsApplied: perm.ran || null };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
module.exports = { envPath, readSecrets, writeSecrets, applyOwnerOnlyPermissions };
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const { spawnSync } = require('node:child_process');
|
|
6
|
+
const { writeFileAtomic } = require('./fsutil');
|
|
7
|
+
|
|
8
|
+
class SelfProfileError extends Error {}
|
|
9
|
+
|
|
10
|
+
// Stale flat agent files from older installs — ported verbatim from
|
|
11
|
+
// install.ps1's $STALE_AGENTS list. Relative to <targetBase>/agents/.
|
|
12
|
+
const STALE_AGENT_FILES = [
|
|
13
|
+
'idea-council-subagent.md',
|
|
14
|
+
'gemini-idea-panel-subagent.agent.md',
|
|
15
|
+
'deepseek-idea-panel-subagent.agent.md',
|
|
16
|
+
'qwen-idea-panel-subagent.agent.md',
|
|
17
|
+
'claude-idea-panel-subagent.agent.md',
|
|
18
|
+
'opensource-idea-panel-subagent.agent.md',
|
|
19
|
+
'orchestrator.agent.md',
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Write <targetBase>/proxy/.repo_root = repoRoot. Lets the deployed
|
|
24
|
+
* claude_router.py / litellm/start.ps1 / managed_files_guard.py find the
|
|
25
|
+
* real repo .env / source files regardless of where they physically live —
|
|
26
|
+
* see install.ps1's identical marker (ported verbatim, same rationale: a
|
|
27
|
+
* fixed relative-path guess only resolves correctly for the repo copy, not
|
|
28
|
+
* the deployed one). Only meaningful for a local (cloned-repo) self install;
|
|
29
|
+
* omit `repoRoot` for a remote/no-clone install and this is a no-op.
|
|
30
|
+
*/
|
|
31
|
+
function writeRepoRootMarker({ targetBase, repoRoot, fsOps = fs }) {
|
|
32
|
+
if (!repoRoot) {
|
|
33
|
+
return { written: false, path: null };
|
|
34
|
+
}
|
|
35
|
+
const proxyDir = path.join(targetBase, 'proxy');
|
|
36
|
+
fsOps.mkdirSync(proxyDir, { recursive: true });
|
|
37
|
+
const markerPath = path.join(proxyDir, '.repo_root');
|
|
38
|
+
writeFileAtomic(markerPath, repoRoot);
|
|
39
|
+
return { written: true, path: markerPath };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function defaultProcessRunner(cmd, args, opts) {
|
|
43
|
+
return spawnSync(cmd, args, { encoding: 'utf8', ...opts });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Fail loud if any deployed agent .md declares an unrecognized
|
|
48
|
+
* dispatch_tier value — shells to proxy/validate_dispatch_tiers.py (the same
|
|
49
|
+
* install-time check install.ps1 runs inline) rather than reimplementing the
|
|
50
|
+
* frontmatter/VALID_DISPATCH_TIERS logic a second time in JS. Read-only
|
|
51
|
+
* (never mutates), so unlike registerScheduledTasks this always runs for
|
|
52
|
+
* real — `runner` is still injectable purely for test determinism/speed.
|
|
53
|
+
*/
|
|
54
|
+
function lintDispatchTiers({ targetBase, repoRoot, runner = defaultProcessRunner }) {
|
|
55
|
+
const validator = path.join(repoRoot, 'proxy', 'validate_dispatch_tiers.py');
|
|
56
|
+
if (!fs.existsSync(validator)) {
|
|
57
|
+
return { ran: false, ok: true, message: `validate_dispatch_tiers.py not found at ${validator} — skipped.` };
|
|
58
|
+
}
|
|
59
|
+
const agentsDir = path.join(targetBase, 'agents');
|
|
60
|
+
if (!fs.existsSync(agentsDir)) {
|
|
61
|
+
return { ran: false, ok: true, message: `${agentsDir} does not exist — nothing to lint.` };
|
|
62
|
+
}
|
|
63
|
+
const result = runner('python', [validator, agentsDir]);
|
|
64
|
+
const ok = !!result && !result.error && result.status === 0;
|
|
65
|
+
return {
|
|
66
|
+
ran: true,
|
|
67
|
+
ok,
|
|
68
|
+
status: result ? result.status : null,
|
|
69
|
+
stdout: (result && result.stdout) || '',
|
|
70
|
+
stderr: (result && result.stderr) || '',
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Remove any of STALE_AGENT_FILES that are present under
|
|
76
|
+
* <targetBase>/agents — ported verbatim from install.ps1's inline
|
|
77
|
+
* Remove-Item loop. Pure fs, safe to run repeatedly (no-op once clean).
|
|
78
|
+
*/
|
|
79
|
+
function cleanupStaleFiles({ targetBase, staleFiles = STALE_AGENT_FILES, fsOps = fs }) {
|
|
80
|
+
const agentsDir = path.join(targetBase, 'agents');
|
|
81
|
+
const removed = [];
|
|
82
|
+
for (const name of staleFiles) {
|
|
83
|
+
const file = path.join(agentsDir, name);
|
|
84
|
+
if (fsOps.existsSync(file)) {
|
|
85
|
+
fsOps.rmSync(file, { force: true });
|
|
86
|
+
removed.push(name);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return { removed };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Register the ClaudeRouter Windows Task Scheduler tasks by shelling to
|
|
94
|
+
* proxy/register_task.ps1 (COM Schedule.Service, no elevation) — see that
|
|
95
|
+
* script's own header for the two-task self-healing design.
|
|
96
|
+
*
|
|
97
|
+
* SAFETY: this mutates real machine state (Task Scheduler) outside the
|
|
98
|
+
* install target entirely, so `runner` is the one part of this module that
|
|
99
|
+
* refuses to run for real under NODE_ENV=test even without an injected fake
|
|
100
|
+
* — same belt-and-suspenders pattern as components.js's defaultRunner for
|
|
101
|
+
* its mutating installer invocations. A caller wanting a real registration
|
|
102
|
+
* in a test MUST inject its own fake runner explicitly.
|
|
103
|
+
*/
|
|
104
|
+
function defaultTaskRunner(cmd, args, opts) {
|
|
105
|
+
if (process.env.NODE_ENV === 'test') {
|
|
106
|
+
return { status: 1, error: null, blocked: true, stdout: '', stderr: 'blocked under NODE_ENV=test' };
|
|
107
|
+
}
|
|
108
|
+
return spawnSync(cmd, args, { encoding: 'utf8', ...opts });
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function registerScheduledTasks({ targetBase, platform = process.platform, runner = defaultTaskRunner }) {
|
|
112
|
+
if (platform !== 'win32') {
|
|
113
|
+
return { ran: false, ok: true, message: `Scheduled-task registration is Windows-only (platform: ${platform}) — skipped.` };
|
|
114
|
+
}
|
|
115
|
+
const script = path.join(targetBase, 'proxy', 'register_task.ps1');
|
|
116
|
+
if (!fs.existsSync(script)) {
|
|
117
|
+
return { ran: false, ok: true, message: `${script} not found — self-infra bundle not installed yet? Skipped.` };
|
|
118
|
+
}
|
|
119
|
+
const result = runner('pwsh', ['-ExecutionPolicy', 'Bypass', '-File', script]);
|
|
120
|
+
const ok = !!result && !result.error && result.status === 0;
|
|
121
|
+
return {
|
|
122
|
+
ran: true,
|
|
123
|
+
ok,
|
|
124
|
+
blocked: !!(result && result.blocked),
|
|
125
|
+
status: result ? result.status : null,
|
|
126
|
+
stdout: (result && result.stdout) || '',
|
|
127
|
+
stderr: (result && result.stderr) || '',
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Run every --profile self post-install step, in the same order install.ps1
|
|
133
|
+
* runs its equivalents: repo-root marker, stale-file cleanup, dispatch-tier
|
|
134
|
+
* lint, scheduled-task registration. Each step is independently injectable
|
|
135
|
+
* (fsOps/runner/taskRunner) and independently reported — one step failing
|
|
136
|
+
* does not skip the rest, matching install.ps1's own "warn and continue"
|
|
137
|
+
* posture for everything except the dispatch-tier lint (which install.ps1
|
|
138
|
+
* treats as install-aborting; this orchestrator surfaces `ok: false` on the
|
|
139
|
+
* summary instead of throwing, leaving the abort decision to the caller).
|
|
140
|
+
*/
|
|
141
|
+
function runSelfProfilePostInstall({
|
|
142
|
+
targetBase,
|
|
143
|
+
repoRoot,
|
|
144
|
+
platform = process.platform,
|
|
145
|
+
fsOps = fs,
|
|
146
|
+
lintRunner = defaultProcessRunner,
|
|
147
|
+
taskRunner = defaultTaskRunner,
|
|
148
|
+
}) {
|
|
149
|
+
const repoRootMarker = writeRepoRootMarker({ targetBase, repoRoot, fsOps });
|
|
150
|
+
const staleCleanup = cleanupStaleFiles({ targetBase, fsOps });
|
|
151
|
+
const dispatchTierLint = repoRoot
|
|
152
|
+
? lintDispatchTiers({ targetBase, repoRoot, runner: lintRunner })
|
|
153
|
+
: { ran: false, ok: true, message: 'No repoRoot known (remote/no-clone install) — dispatch-tier lint skipped.' };
|
|
154
|
+
const scheduledTasks = registerScheduledTasks({ targetBase, platform, runner: taskRunner });
|
|
155
|
+
|
|
156
|
+
return {
|
|
157
|
+
repoRootMarker,
|
|
158
|
+
staleCleanup,
|
|
159
|
+
dispatchTierLint,
|
|
160
|
+
scheduledTasks,
|
|
161
|
+
ok: dispatchTierLint.ok,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
module.exports = {
|
|
166
|
+
SelfProfileError,
|
|
167
|
+
STALE_AGENT_FILES,
|
|
168
|
+
writeRepoRootMarker,
|
|
169
|
+
lintDispatchTiers,
|
|
170
|
+
cleanupStaleFiles,
|
|
171
|
+
registerScheduledTasks,
|
|
172
|
+
runSelfProfilePostInstall,
|
|
173
|
+
};
|