aegiscode 6.8.3 → 6.8.4

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.
@@ -0,0 +1,419 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * The OpenAI-compatible shim — AEGIS as a *model provider* for every coding
6
+ * program that already lets you type a base URL.
7
+ *
8
+ * There are two different questions a coding tool can ask an account, and AEGIS
9
+ * answers them through two different doors:
10
+ *
11
+ * - "what can this assistant DO?" → MCP. `./install.js` writes the config and
12
+ * the tools in `mcp/tools.js` show up in the tool picker. That covers
13
+ * Copilot agent mode, Cursor, Windsurf, Cline, Roo, Zed, Continue, Junie.
14
+ *
15
+ * - "which MODEL writes the code?" → an OpenAI-compatible endpoint. Most
16
+ * editors, and nearly every other client, let you point at a custom
17
+ * `base_url` for chat. aegis1 speaks a *different* path
18
+ * (`/api/v1/chat/completions`, AEGIS key auth, AEGIS body extensions), so
19
+ * no client can point at it directly. This file is the translation:
20
+ * loopback-only, `/v1/chat/completions` + `/v1/models`, OpenAI SSE out.
21
+ *
22
+ * It is a thin proxy on purpose. All transport, SSE reassembly, the stalled
23
+ * stream watchdog and the reasoning/tool-call accumulation live in
24
+ * `client/aegis.js`, which every other host uses — so a provider that works in
25
+ * the desktop app cannot behave differently here. This file owns one thing:
26
+ * the OpenAI wire format.
27
+ *
28
+ * Security posture:
29
+ * - binds `127.0.0.1` only, and refuses a non-loopback `--host` unless
30
+ * `--allow-remote` is passed explicitly (the endpoint spends the account's
31
+ * tokens, so exposing it is a decision, not a default);
32
+ * - never logs or echoes the AEGIS key;
33
+ * - the key is resolved by the ordinary path (env → 0600 store → .env), so
34
+ * the shim holds no credential of its own.
35
+ */
36
+
37
+ const fs = require('node:fs');
38
+ const path = require('node:path');
39
+ const http = require('node:http');
40
+
41
+ const { createClient } = require('../client/aegis.js');
42
+ const credentials = require('../client/credentials.js');
43
+
44
+ /**
45
+ * The pure model-catalog module, which lives with the CLI (`cli/src/models.js`)
46
+ * rather than in `client/`. Two layouts have to work, exactly as `deps.js`
47
+ * documents, because this file is staged into `cli/vendor/hosts/` at publish
48
+ * time and the CLI's own `src/` moves with it:
49
+ *
50
+ * in-repo <repo>/hosts/openai-shim.js -> <repo>/cli/src/models.js
51
+ * npm <pkg>/vendor/hosts/openai-shim.js -> <pkg>/src/models.js
52
+ *
53
+ * A single hard-coded `../cli/src/models.js` resolves in the repo and to
54
+ * `<pkg>/vendor/cli/src/models.js` once installed — a file no layout ever
55
+ * creates, so the shim would die at load with MODULE_NOT_FOUND in exactly the
56
+ * configuration it exists to serve. Resolution is by existence, so a source
57
+ * checkout and an installed package run the same code.
58
+ */
59
+ function resolveModelsModule() {
60
+ const candidates = [
61
+ path.join(__dirname, '..', 'cli', 'src', 'models.js'),
62
+ path.join(__dirname, '..', '..', 'src', 'models.js'),
63
+ ];
64
+ for (const candidate of candidates) {
65
+ if (fs.existsSync(candidate)) return candidate;
66
+ }
67
+ throw new Error(
68
+ 'aegis-shim: cannot find models.js. Expected cli/src/models.js beside hosts/ ' +
69
+ `(source checkout) or src/models.js in the package root (installed). Looked in: ${candidates.join(', ')}`
70
+ );
71
+ }
72
+
73
+ const { normalizeModelCatalog, pickerEntries } = require(resolveModelsModule());
74
+
75
+ const DEFAULT_PORT = 8787;
76
+ const LOOPBACK = new Set(['127.0.0.1', '::1', 'localhost']);
77
+
78
+ /** OpenAI's schema wants `owned_by` and a created timestamp; neither means
79
+ * anything for a pooled provider, so both are stable constants. */
80
+ const EPOCH = 1735689600; // 2025-01-01T00:00:00Z
81
+
82
+ function logLine(stream, msg) {
83
+ stream.write(`aegis-shim: ${msg}\n`);
84
+ }
85
+
86
+ // ---------------------------------------------------------------------------
87
+ // Body translation
88
+ // ---------------------------------------------------------------------------
89
+
90
+ /**
91
+ * Fields the pooled endpoint understands and a caller may legitimately send.
92
+ * Anything else is dropped rather than forwarded: aegis1 validates its body,
93
+ * and passing an unknown key through turns a working client into a 400.
94
+ */
95
+ function extraFromBody(body) {
96
+ const extra = {};
97
+ for (const key of ['tools', 'tool_choice', 'temperature', 'top_p', 'stop', 'presence_penalty', 'frequency_penalty']) {
98
+ if (body[key] !== undefined) extra[key] = body[key];
99
+ }
100
+ // `reasoning_effort` is OpenAI's spelling of the AEGIS effort rung; a client
101
+ // that offers the knob should get the behaviour it names, not a silent no-op.
102
+ const eff = body.reasoning_effort || body.effort;
103
+ if (typeof eff === 'string' && ['low', 'medium', 'high'].includes(eff.toLowerCase())) {
104
+ extra.effort = eff.toLowerCase();
105
+ }
106
+ if (body.workers !== undefined) extra.workers = body.workers;
107
+ return extra;
108
+ }
109
+
110
+ function sseHead(res) {
111
+ res.writeHead(200, {
112
+ 'Content-Type': 'text/event-stream; charset=utf-8',
113
+ 'Cache-Control': 'no-cache, no-transform',
114
+ Connection: 'keep-alive',
115
+ 'X-Accel-Buffering': 'no',
116
+ });
117
+ }
118
+
119
+ function sseSend(res, payload) {
120
+ res.write(`data: ${JSON.stringify(payload)}\n\n`);
121
+ }
122
+
123
+ function chunkFrame(id, model, delta, finishReason) {
124
+ return {
125
+ id,
126
+ object: 'chat.completion.chunk',
127
+ created: Math.floor(Date.now() / 1000),
128
+ model: model || 'aegis',
129
+ choices: [{ index: 0, delta, finish_reason: finishReason || null }],
130
+ };
131
+ }
132
+
133
+ // ---------------------------------------------------------------------------
134
+ // Server
135
+ // ---------------------------------------------------------------------------
136
+
137
+ /**
138
+ * @param {object} opts
139
+ * @param {object} [opts.client] Injected transport (tests pass a stub).
140
+ * @param {number} [opts.port]
141
+ * @param {string} [opts.host]
142
+ * @param {boolean} [opts.allowRemote]
143
+ * @param {boolean} [opts.requireKey] Reject callers that send no bearer token.
144
+ * @param {NodeJS.WriteStream} [opts.log]
145
+ * @param {Function} [opts.fetchModels] Override catalog fetch (tests).
146
+ */
147
+ function createShimServer(opts = {}) {
148
+ const client = opts.client || createClient(credentials.clientOptions());
149
+ const host = opts.host || '127.0.0.1';
150
+ const port = opts.port === undefined ? DEFAULT_PORT : opts.port;
151
+ const out = opts.log || process.stderr;
152
+ const requireKey = opts.requireKey !== false;
153
+ const fetchModels = opts.fetchModels || (() => client.listModels());
154
+
155
+ if (!LOOPBACK.has(host) && !opts.allowRemote) {
156
+ throw new Error(
157
+ `refusing to bind ${host}: the shim spends your account's tokens, so it is loopback-only ` +
158
+ 'unless you pass --allow-remote'
159
+ );
160
+ }
161
+
162
+ // The catalog is cached for a minute: a model picker calls /v1/models on
163
+ // every focus, and hitting aegiscloud.org each time is a visible stall in the
164
+ // one UI where latency is most obvious.
165
+ let catalog = { at: 0, models: [] };
166
+ const CATALOG_MS = 60_000;
167
+
168
+ async function models() {
169
+ if (Date.now() - catalog.at < CATALOG_MS && catalog.models.length) return catalog.models;
170
+ const raw = await fetchModels();
171
+ catalog = { at: Date.now(), models: pickerEntries(normalizeModelCatalog(raw && raw.models ? raw.models : raw)) };
172
+ return catalog.models;
173
+ }
174
+
175
+ function sendJson(res, status, payload) {
176
+ const text = JSON.stringify(payload);
177
+ res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(text) });
178
+ res.end(text);
179
+ }
180
+
181
+ function oaiError(res, status, message, type) {
182
+ sendJson(res, status, { error: { message, type: type || 'aegis_error', code: status } });
183
+ }
184
+
185
+ function authorized(req) {
186
+ if (!requireKey) return true;
187
+ const header = req.headers.authorization || '';
188
+ const m = /^Bearer\s+(.+)$/i.exec(header);
189
+ return Boolean(m && m[1].trim());
190
+ }
191
+
192
+ async function readBody(req) {
193
+ const chunks = [];
194
+ let size = 0;
195
+ for await (const c of req) {
196
+ size += c.length;
197
+ if (size > 8 * 1024 * 1024) throw new Error('request body too large');
198
+ chunks.push(c);
199
+ }
200
+ const text = Buffer.concat(chunks).toString('utf8');
201
+ if (!text.trim()) return {};
202
+ return JSON.parse(text);
203
+ }
204
+
205
+ async function handleModels(res) {
206
+ const list = await models();
207
+ sendJson(res, 200, {
208
+ object: 'list',
209
+ data: list.map((m) => ({
210
+ id: m.id,
211
+ object: 'model',
212
+ created: EPOCH,
213
+ owned_by: 'aegis',
214
+ // Non-standard, harmless, and the reason the picker in Cline/Continue
215
+ // does not show five identical rows.
216
+ ...(m.label && m.label !== m.id ? { name: m.label } : {}),
217
+ })),
218
+ });
219
+ }
220
+
221
+ async function handleChat(req, res) {
222
+ let body;
223
+ try {
224
+ body = await readBody(req);
225
+ } catch (err) {
226
+ return oaiError(res, 400, `invalid JSON body: ${err.message}`, 'invalid_request_error');
227
+ }
228
+
229
+ const messages = Array.isArray(body.messages) ? body.messages : null;
230
+ if (!messages || !messages.length) {
231
+ return oaiError(res, 400, '`messages` is required', 'invalid_request_error');
232
+ }
233
+
234
+ const stream = body.stream === true;
235
+ const id = `chatcmpl-aegis-${Date.now().toString(36)}`;
236
+ const model = body.model && body.model !== 'aegis-default' ? String(body.model) : undefined;
237
+
238
+ const args = {
239
+ messages,
240
+ model,
241
+ maxTokens: body.max_tokens || body.max_completion_tokens,
242
+ extra: extraFromBody(body),
243
+ includeUsage: stream,
244
+ };
245
+
246
+ if (!stream) {
247
+ try {
248
+ const r = await client.chatCompletion({ ...args, stream: false });
249
+ const msg = (r.choices && r.choices[0] && r.choices[0].message) || { content: '' };
250
+ return sendJson(res, 200, {
251
+ id,
252
+ object: 'chat.completion',
253
+ created: Math.floor(Date.now() / 1000),
254
+ model: r.model || model || 'aegis',
255
+ choices: [{ index: 0, message: { role: 'assistant', ...msg }, finish_reason: msg.tool_calls ? 'tool_calls' : 'stop' }],
256
+ usage: r.usage || undefined,
257
+ });
258
+ } catch (err) {
259
+ return oaiError(res, err.status && err.status >= 400 && err.status < 600 ? err.status : 502, err.message);
260
+ }
261
+ }
262
+
263
+ sseHead(res);
264
+ let closed = false;
265
+ req.on('close', () => { closed = true; });
266
+ const write = (payload) => { if (!closed) sseSend(res, payload); };
267
+
268
+ // First frame carries the role, exactly as OpenAI does — some clients
269
+ // (Continue among them) key their stream parser off it.
270
+ write(chunkFrame(id, model, { role: 'assistant', content: '' }));
271
+
272
+ try {
273
+ const r = await client.chatCompletion({
274
+ ...args,
275
+ stream: true,
276
+ onStream: (ev) => {
277
+ if (ev.delta) write(chunkFrame(id, model, { content: ev.delta }));
278
+ else if (ev.reasoning) write(chunkFrame(id, model, { reasoning_content: ev.reasoning }));
279
+ },
280
+ onReasoning: (chunk) => write(chunkFrame(id, model, { reasoning_content: chunk })),
281
+ });
282
+
283
+ const msg = (r.choices && r.choices[0] && r.choices[0].message) || {};
284
+ // Tool calls are accumulated inside the transport, not streamed
285
+ // fragment-by-fragment, so they arrive as one final frame. That is a
286
+ // legal OpenAI chunk (id + index + name + full arguments), and it is the
287
+ // only shape the shared transport can prove is complete.
288
+ if (Array.isArray(msg.tool_calls) && msg.tool_calls.length) {
289
+ write(chunkFrame(id, model, {
290
+ tool_calls: msg.tool_calls.map((tc, i) => ({
291
+ index: i,
292
+ id: tc.id,
293
+ type: 'function',
294
+ function: { name: tc.function && tc.function.name, arguments: (tc.function && tc.function.arguments) || '' },
295
+ })),
296
+ }));
297
+ }
298
+ write(chunkFrame(id, model, {}, msg.tool_calls && msg.tool_calls.length ? 'tool_calls' : 'stop'));
299
+ if (r.usage) {
300
+ write({ id, object: 'chat.completion.chunk', created: Math.floor(Date.now() / 1000), model: r.model || model || 'aegis', choices: [], usage: r.usage });
301
+ }
302
+ if (!closed) { res.write('data: [DONE]\n\n'); res.end(); }
303
+ } catch (err) {
304
+ // Headers are already sent, so the error travels as a terminal SSE frame
305
+ // plus a marker the client can surface — an editor that shows a bare
306
+ // stalled stream teaches the user nothing.
307
+ write({ error: { message: err.message, type: 'aegis_error' } });
308
+ if (!closed) { res.write('data: [DONE]\n\n'); res.end(); }
309
+ }
310
+ }
311
+
312
+ const server = http.createServer((req, res) => {
313
+ const url = new URL(req.url || '/', `http://${req.headers.host || '127.0.0.1'}`);
314
+ const path = url.pathname.replace(/\/+$/, '') || '/';
315
+
316
+ if (req.method === 'GET' && (path === '/health' || path === '/')) {
317
+ return sendJson(res, 200, { ok: true, service: 'aegis-openai-shim', endpoint: `http://${host}:${port}/v1` });
318
+ }
319
+ // `/v1` is the OpenAI convention; Cursor and a few others probe `/models`
320
+ // without the prefix, and refusing that reads as "the endpoint is wrong".
321
+ if (req.method === 'GET' && (path === '/v1/models' || path === '/models')) {
322
+ if (!authorized(req)) return oaiError(res, 401, 'missing API key — any non-empty value works locally', 'invalid_request_error');
323
+ return handleModels(res).catch((err) => oaiError(res, 502, err.message));
324
+ }
325
+ if (req.method === 'POST' && (path === '/v1/chat/completions' || path === '/chat/completions')) {
326
+ if (!authorized(req)) return oaiError(res, 401, 'missing API key — any non-empty value works locally', 'invalid_request_error');
327
+ return handleChat(req, res);
328
+ }
329
+ // Anthropic-shaped probes from editors that auto-detect the provider.
330
+ if (req.method === 'POST' && path === '/v1/messages') {
331
+ return oaiError(res, 404, 'this endpoint speaks the OpenAI schema; point the client at /v1 with the OpenAI provider', 'invalid_request_error');
332
+ }
333
+ return oaiError(res, 404, `no such route: ${req.method} ${path}`, 'invalid_request_error');
334
+ });
335
+
336
+ server.listen = ((orig) => function listen(...a) {
337
+ return orig.apply(server, a);
338
+ })(server.listen);
339
+
340
+ return {
341
+ server,
342
+ host,
343
+ port,
344
+ url: `http://${host}:${port}/v1`,
345
+ listen() {
346
+ return new Promise((resolve, reject) => {
347
+ server.once('error', reject);
348
+ server.listen(port, host, () => {
349
+ const actual = server.address();
350
+ logLine(out, `OpenAI-compatible endpoint on http://${host}:${actual.port}/v1`);
351
+ logLine(out, `point any OpenAI-compatible client at that base URL (any API key value)`);
352
+ resolve(actual);
353
+ });
354
+ });
355
+ },
356
+ close() {
357
+ return new Promise((resolve) => server.close(resolve));
358
+ },
359
+ };
360
+ }
361
+
362
+ // ---------------------------------------------------------------------------
363
+ // CLI
364
+ // ---------------------------------------------------------------------------
365
+
366
+ function parseArgv(argv) {
367
+ const opts = { log: process.stderr };
368
+ for (let i = 0; i < argv.length; i++) {
369
+ const a = argv[i];
370
+ if (a === '--port') opts.port = Number(argv[++i]);
371
+ else if (a === '--host') opts.host = argv[++i];
372
+ else if (a === '--allow-remote') opts.allowRemote = true;
373
+ else if (a === '--no-auth') opts.requireKey = false;
374
+ else if (a === '--help' || a === '-h') opts.help = true;
375
+ }
376
+ return opts;
377
+ }
378
+
379
+ async function main(argv) {
380
+ const opts = parseArgv(argv);
381
+ if (opts.help) {
382
+ process.stdout.write([
383
+ 'aegis openai shim — serve AEGIS as an OpenAI-compatible endpoint',
384
+ '',
385
+ ' node hosts/openai-shim.js [--port 8787] [--host 127.0.0.1] [--allow-remote] [--no-auth]',
386
+ '',
387
+ 'Then point a coding tool at it:',
388
+ ' base URL http://127.0.0.1:8787/v1',
389
+ ' API key anything non-empty (the AEGIS key is read from ~/.aegiscode/.env)',
390
+ '',
391
+ ].join('\n'));
392
+ return 0;
393
+ }
394
+ let shim;
395
+ try {
396
+ shim = createShimServer(opts);
397
+ await shim.listen();
398
+ } catch (err) {
399
+ logLine(process.stderr, err.message);
400
+ return 1;
401
+ }
402
+ const stop = async () => { await shim.close(); process.exit(0); };
403
+ process.on('SIGINT', stop);
404
+ process.on('SIGTERM', stop);
405
+ return null; // runs until signalled
406
+ }
407
+
408
+ if (require.main === module) {
409
+ main(process.argv.slice(2))
410
+ .then((code) => {
411
+ if (typeof code === 'number') process.exit(code);
412
+ })
413
+ .catch((err) => {
414
+ logLine(process.stderr, err && err.message ? err.message : err);
415
+ process.exit(1);
416
+ });
417
+ }
418
+
419
+ module.exports = { createShimServer, extraFromBody, DEFAULT_PORT };
@@ -0,0 +1,164 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * The canonical AEGIS server spec — one description of "run the AEGIS MCP
5
+ * server", which every host target then re-shapes into its own config dialect.
6
+ *
7
+ * There is exactly one server implementation (`mcp/server.js`, a dependency-free
8
+ * stdio JSON-RPC host) and one tool registry (`mcp/tools.js`) shared with the
9
+ * CLI. Editor integrations are therefore a CONFIGURATION problem, not a code
10
+ * problem: every host that speaks MCP gets the same process, and nothing here
11
+ * re-implements a tool.
12
+ *
13
+ * Two decisions are encoded deliberately:
14
+ *
15
+ * 1. The API key is NOT written into editor config by default. Each editor
16
+ * keeps its MCP config in a plain, often world-readable file, and several
17
+ * of them are inside project directories that get committed. The server
18
+ * already resolves a credential from the environment, then the 0600 store
19
+ * `aegiscode login` writes, then `~/.aegiscode/.env` (read at startup in
20
+ * every host). So the correct default is to write NO secret and let the
21
+ * existing resolution do its job. `--with-key` exists for the user who
22
+ * insists, and `--prompt-key` emits VS Code's own `inputs` password prompt
23
+ * for the one host that supports not storing the value at all.
24
+ *
25
+ * 2. `command` is `node` + an absolute path to `mcp/server.js`, because that
26
+ * is true on every platform and needs no shebang, no chmod, and no PATH
27
+ * entry. `npx aegiscode-mcp` style launchers are deliberately not used: a
28
+ * cold `npx` resolution inside an editor's MCP host is a startup failure
29
+ * the user cannot see.
30
+ */
31
+
32
+ const fs = require('node:fs');
33
+ const path = require('node:path');
34
+
35
+ const SERVER_NAME = 'aegis';
36
+ const DEFAULT_API_BASE = 'https://aegiscloud.org';
37
+
38
+ /**
39
+ * Every place `mcp/server.js` legitimately lives, most-specific first.
40
+ *
41
+ * - inside this repo / this checkout: `<root>/mcp/server.js`
42
+ * - installed as the `aegiscode` npm package: `<pkg>/vendor/mcp/server.js`
43
+ * (the CLI vendors `mcp/` and `client/` at publish time — see
44
+ * `cli/scripts/predist.mjs`)
45
+ * - an explicit override, for a user who keeps the tree somewhere unusual.
46
+ *
47
+ * A missing target is a real, reportable condition: an editor config that
48
+ * points at a path that does not exist fails silently inside the editor, which
49
+ * is the worst possible failure mode. `resolveServer()` therefore returns the
50
+ * first candidate that exists and `serverCandidates()` exposes all of them so
51
+ * `aegiscode mcp status` can explain what it looked for.
52
+ */
53
+ function serverCandidates(env = process.env) {
54
+ const out = [];
55
+ const push = (p) => {
56
+ if (!p) return;
57
+ const abs = path.resolve(p);
58
+ if (!out.includes(abs)) out.push(abs);
59
+ };
60
+
61
+ push(env.AEGIS_MCP_SERVER);
62
+ push(path.resolve(__dirname, '..', 'mcp', 'server.js'));
63
+ push(path.resolve(__dirname, '..', 'cli', 'vendor', 'mcp', 'server.js'));
64
+ push(path.resolve(__dirname, '..', 'vendor', 'mcp', 'server.js'));
65
+ push(path.resolve(__dirname, '..', '..', 'mcp', 'server.js'));
66
+
67
+ // A globally installed CLI (`npm i -g aegiscode`) keeps its vendor tree in
68
+ // the global root, which is not on any path relative to this file.
69
+ for (const root of globalRoots(env)) {
70
+ push(path.join(root, 'aegiscode', 'vendor', 'mcp', 'server.js'));
71
+ }
72
+ return out;
73
+ }
74
+
75
+ function globalRoots(env = process.env) {
76
+ const roots = [];
77
+ if (env.npm_config_prefix) roots.push(path.join(env.npm_config_prefix, 'lib', 'node_modules'));
78
+ roots.push('/usr/local/lib/node_modules', '/usr/lib/node_modules');
79
+ const node = process.execPath || '';
80
+ if (node.includes(`${path.sep}bin${path.sep}`)) {
81
+ roots.push(path.resolve(node, '..', '..', 'lib', 'node_modules'));
82
+ }
83
+ return roots;
84
+ }
85
+
86
+ /**
87
+ * @returns {{path: string, exists: boolean, candidates: string[]}}
88
+ */
89
+ function resolveServer(env = process.env) {
90
+ const candidates = serverCandidates(env);
91
+ const found = candidates.find((p) => {
92
+ try { return fs.statSync(p).isFile(); } catch { return false; }
93
+ });
94
+ return { path: found || candidates[0], exists: Boolean(found), candidates };
95
+ }
96
+
97
+ /**
98
+ * The API base is part of the spec because a self-hosted `aegis1` is a
99
+ * supported configuration (`AEGIS_API_BASE`), and an editor config that
100
+ * silently points at the public cloud when the user meant their own box is a
101
+ * leak, not a bug.
102
+ */
103
+ function resolveApiBase(env = process.env, override) {
104
+ return override || env.AEGIS_API_BASE || DEFAULT_API_BASE;
105
+ }
106
+
107
+ /**
108
+ * Build the server spec for one target.
109
+ *
110
+ * @param {object} [opts]
111
+ * @param {string} [opts.apiKey] Only set when the user asked for it.
112
+ * @param {string} [opts.apiBase]
113
+ * @param {string} [opts.serverPath]
114
+ * @param {boolean} [opts.promptKey] Reference a host-supplied secret instead of
115
+ * embedding one (VS Code `inputs`).
116
+ * @param {NodeJS.ProcessEnv} [opts.env]
117
+ * @returns {{name: string, command: string, args: string[], env: object,
118
+ * keyRef: string|null, server: object}}
119
+ */
120
+ function buildSpec(opts = {}) {
121
+ const env = opts.env || process.env;
122
+ const server = resolveServer(env);
123
+ const path_ = opts.serverPath || server.path;
124
+ const apiBase = resolveApiBase(env, opts.apiBase);
125
+
126
+ const vars = {};
127
+ if (opts.promptKey) {
128
+ vars.AEGIS_API_KEY = '${input:aegis-api-key}';
129
+ } else if (opts.apiKey) {
130
+ vars.AEGIS_API_KEY = opts.apiKey;
131
+ }
132
+ // Always record the base: it is not a secret and a wrong base is the single
133
+ // most confusing misconfiguration to debug from inside an editor.
134
+ vars.AEGIS_API_BASE = apiBase;
135
+
136
+ return {
137
+ name: SERVER_NAME,
138
+ command: 'node',
139
+ args: [path_],
140
+ env: vars,
141
+ keyRef: opts.promptKey ? '${input:aegis-api-key}' : (opts.apiKey || null),
142
+ server,
143
+ };
144
+ }
145
+
146
+ /** The VS Code `inputs` block that makes `promptKey` above resolve. */
147
+ function vscodeKeyInput() {
148
+ return {
149
+ type: 'promptString',
150
+ id: 'aegis-api-key',
151
+ description: 'AEGIS API key (aegiscloud.org → Account → API keys)',
152
+ password: true,
153
+ };
154
+ }
155
+
156
+ module.exports = {
157
+ SERVER_NAME,
158
+ DEFAULT_API_BASE,
159
+ buildSpec,
160
+ resolveServer,
161
+ serverCandidates,
162
+ resolveApiBase,
163
+ vscodeKeyInput,
164
+ };