aegiscode 7.0.26 → 7.0.28

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.
Files changed (118) hide show
  1. package/SOURCE-OFFER.txt +9 -0
  2. package/package.json +4 -7
  3. package/scripts/check.mjs +1 -52
  4. package/scripts/demo.mjs +1 -94
  5. package/scripts/predist.mjs +1 -75
  6. package/scripts/runtests.mjs +1 -56
  7. package/scripts/seal-gate.mjs +1 -74
  8. package/src/agents.js +1 -139
  9. package/src/app.js +1 -2957
  10. package/src/art.js +1 -289
  11. package/src/chatflow.js +1 -3023
  12. package/src/checkpoint.js +1 -90
  13. package/src/clipboard.js +1 -424
  14. package/src/cloudsync.js +1 -528
  15. package/src/commands.js +1 -4089
  16. package/src/config.js +1 -581
  17. package/src/connect.js +1 -349
  18. package/src/credentials.js +1 -33
  19. package/src/deps.js +1 -232
  20. package/src/devrun.js +1 -187
  21. package/src/diff.js +1 -333
  22. package/src/diffview.js +1 -296
  23. package/src/engine.js +1 -297
  24. package/src/entitlement.js +1 -355
  25. package/src/events.js +1 -707
  26. package/src/export.js +1 -67
  27. package/src/filepreview.js +1 -153
  28. package/src/fingerprint.js +1 -592
  29. package/src/format.js +1 -259
  30. package/src/fuzzy.js +1 -119
  31. package/src/history.js +1 -423
  32. package/src/init.js +1 -175
  33. package/src/input.js +1 -139
  34. package/src/keys.js +1 -183
  35. package/src/markdown.js +1 -306
  36. package/src/models.js +1 -507
  37. package/src/naming.js +1 -57
  38. package/src/overlays.js +1 -462
  39. package/src/panels.js +1 -1418
  40. package/src/ping.js +1 -226
  41. package/src/presence.js +1 -238
  42. package/src/render.js +1 -516
  43. package/src/screen.js +1 -518
  44. package/src/screens.js +1 -896
  45. package/src/secret.js +1 -59
  46. package/src/securefs.js +1 -359
  47. package/src/settings.js +1 -155
  48. package/src/shared.js +1 -52
  49. package/src/sharedpaths.js +1 -53
  50. package/src/signup.js +1 -156
  51. package/src/summarize.js +1 -95
  52. package/src/sysdiag.js +1 -585
  53. package/src/system.js +1 -40
  54. package/src/theme.js +1 -570
  55. package/src/title.js +1 -220
  56. package/src/todos.js +1 -115
  57. package/src/tokens.js +1 -263
  58. package/src/topup.js +1 -210
  59. package/src/update.js +1 -191
  60. package/vendor/client/aegis.js +1 -2441
  61. package/vendor/client/attest.js +1 -518
  62. package/vendor/client/authorship-key.js +1 -410
  63. package/vendor/client/auto-provision.js +1 -134
  64. package/vendor/client/brain-catalog.js +1 -268
  65. package/vendor/client/byok-catalog.js +1 -199
  66. package/vendor/client/catalog-client.js +1 -487
  67. package/vendor/client/conversation-export.js +1 -177
  68. package/vendor/client/credentials.js +1 -494
  69. package/vendor/client/device-fingerprint.js +1 -141
  70. package/vendor/client/drive-connect.js +1 -110
  71. package/vendor/client/drive-upload.js +1 -234
  72. package/vendor/client/env-file.js +1 -1273
  73. package/vendor/client/fingerprint.js +1 -1064
  74. package/vendor/client/foreign-memory.js +1 -669
  75. package/vendor/client/google-signin.js +1 -133
  76. package/vendor/client/hooks.js +1 -430
  77. package/vendor/client/model-discovery.js +1 -373
  78. package/vendor/client/naming.js +1 -283
  79. package/vendor/client/platform.js +1 -937
  80. package/vendor/client/prefs.js +1 -351
  81. package/vendor/client/presence-constants.js +1 -107
  82. package/vendor/client/presence.js +1 -438
  83. package/vendor/client/record-vault.js +3 -1055
  84. package/vendor/client/session-store.js +1 -575
  85. package/vendor/client/topup.js +1 -297
  86. package/vendor/client/touch.js +1 -458
  87. package/vendor/client/update.js +1 -763
  88. package/vendor/client/user-models.js +1 -381
  89. package/vendor/desktop/lib/local/agents.js +1 -105
  90. package/vendor/desktop/lib/local/attachments.js +1 -276
  91. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  92. package/vendor/desktop/lib/local/claude-pro.js +1 -1028
  93. package/vendor/desktop/lib/local/context.js +1 -125
  94. package/vendor/desktop/lib/local/engine.js +1 -3666
  95. package/vendor/desktop/lib/local/entitlement.js +1 -660
  96. package/vendor/desktop/lib/local/exec-plan.js +1 -269
  97. package/vendor/desktop/lib/local/git-scope.js +1 -228
  98. package/vendor/desktop/lib/local/integrity.js +1 -163
  99. package/vendor/desktop/lib/local/local.js +1 -2145
  100. package/vendor/desktop/lib/local/prompt.js +1 -280
  101. package/vendor/desktop/lib/local/queue.js +1 -560
  102. package/vendor/desktop/lib/local/session-rounds.js +1 -238
  103. package/vendor/desktop/lib/local/shell.js +1 -712
  104. package/vendor/desktop/lib/local/spill.js +1 -75
  105. package/vendor/desktop/lib/local/tools.js +1 -1328
  106. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  107. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  108. package/vendor/desktop/lib/settings.js +1 -890
  109. package/vendor/desktop/main.js +1 -4890
  110. package/vendor/desktop/renderer/usage.js +1 -1239
  111. package/vendor/hosts/install.js +1 -638
  112. package/vendor/hosts/openai-shim.js +1 -515
  113. package/vendor/hosts/spec.js +1 -164
  114. package/vendor/hosts/targets.js +1 -346
  115. package/vendor/mcp/server.js +1 -221
  116. package/vendor/mcp/tools.js +1 -408
  117. package/vendor/one/src/child.js +1 -285
  118. package/vendor/one/src/permissions.js +1 -383
@@ -1,516 +1,2 @@
1
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 → legacy
34
- * config.json), so the shim holds no credential of its own.
35
- *
36
- * THE SHARED ENV FILE — and why `run()` below reads it before anything else.
37
- *
38
- * `credentials.resolveApiKey()` reads the *environment*, then its own stores;
39
- * it has never opened `~/.aegiscode/.env` (that is `client/env-file.js`'s job,
40
- * deliberately: one reader, one contract). Every other host in this repo calls
41
- * that reader at start-up — `cli/bin/aegiscode.js` before caps and a session,
42
- * `desktop/main.js` before `createClient`, `mcp/server.js` at load. This file
43
- * did not, so it was the one host where the documented setup
44
- *
45
- * AEGIS_API_KEY=aegis_… # in ~/.aegiscode/.env
46
- *
47
- * silently did nothing: the shim started, the editor got a 401 on the first
48
- * message, and the key instruction printed in this file's own `--help` named a
49
- * file the shim never read. In a shell that had also exported the variable the
50
- * bug was invisible, which is exactly how it survived — a GUI-launched editor
51
- * has no such export, and that is the normal way this shim is used.
52
- *
53
- * So `run()` loads the file, then *checks* the key and refuses to serve without
54
- * one, naming where a key can come from. A shim that starts keyless is worse
55
- * than one that exits: the failure surfaces later, in another program's error
56
- * dialog, as an unexplained 401.
57
- */
58
-
59
- const fs = require('node:fs');
60
- const path = require('node:path');
61
- const http = require('node:http');
62
-
63
- const { createClient } = require('../client/aegis.js');
64
- const credentials = require('../client/credentials.js');
65
-
66
- /**
67
- * The pure model-catalog module, which lives with the CLI (`cli/src/models.js`)
68
- * rather than in `client/`. Two layouts have to work, exactly as `deps.js`
69
- * documents, because this file is staged into `cli/vendor/hosts/` at publish
70
- * time and the CLI's own `src/` moves with it:
71
- *
72
- * in-repo <repo>/hosts/openai-shim.js -> <repo>/cli/src/models.js
73
- * npm <pkg>/vendor/hosts/openai-shim.js -> <pkg>/src/models.js
74
- *
75
- * A single hard-coded `../cli/src/models.js` resolves in the repo and to
76
- * `<pkg>/vendor/cli/src/models.js` once installed — a file no layout ever
77
- * creates, so the shim would die at load with MODULE_NOT_FOUND in exactly the
78
- * configuration it exists to serve. Resolution is by existence, so a source
79
- * checkout and an installed package run the same code.
80
- */
81
- function resolveModelsModule() {
82
- const candidates = [
83
- path.join(__dirname, '..', 'cli', 'src', 'models.js'),
84
- path.join(__dirname, '..', '..', 'src', 'models.js'),
85
- ];
86
- for (const candidate of candidates) {
87
- if (fs.existsSync(candidate)) return candidate;
88
- }
89
- throw new Error(
90
- 'aegis-shim: cannot find models.js. Expected cli/src/models.js beside hosts/ ' +
91
- `(source checkout) or src/models.js in the package root (installed). Looked in: ${candidates.join(', ')}`
92
- );
93
- }
94
-
95
- const { normalizeModelCatalog, pickerEntries } = require(resolveModelsModule());
96
-
97
- const DEFAULT_PORT = 8787;
98
- const DEFAULT_HOST = '127.0.0.1';
99
- const LOOPBACK = new Set(['127.0.0.1', '::1', 'localhost']);
100
-
101
- /**
102
- * Refuse to bind anything but loopback unless the operator asked for it.
103
- *
104
- * Hoisted out of `createShimServer` because `main()` must apply it *first*:
105
- * it is an argument refusal, and a keyless shim still cannot leak anything
106
- * while a public one can. See the call site in `main()` for the ordering bug
107
- * this caused when it lived only inside the server factory.
108
- */
109
- function assertBindAllowed(host, allowRemote) {
110
- if (!LOOPBACK.has(host) && !allowRemote) {
111
- throw new Error(
112
- `refusing to bind ${host}: the shim spends your account's tokens, so it is loopback-only ` +
113
- 'unless you pass --allow-remote'
114
- );
115
- }
116
- }
117
-
118
- /** OpenAI's schema wants `owned_by` and a created timestamp; neither means
119
- * anything for a pooled provider, so both are stable constants. */
120
- const EPOCH = 1735689600; // 2025-01-01T00:00:00Z
121
-
122
- function logLine(stream, msg) {
123
- stream.write(`aegis-shim: ${msg}\n`);
124
- }
125
-
126
- // ---------------------------------------------------------------------------
127
- // Body translation
128
- // ---------------------------------------------------------------------------
129
-
130
- /**
131
- * Fields the pooled endpoint understands and a caller may legitimately send.
132
- * Anything else is dropped rather than forwarded: aegis1 validates its body,
133
- * and passing an unknown key through turns a working client into a 400.
134
- */
135
- function extraFromBody(body) {
136
- const extra = {};
137
- for (const key of ['tools', 'tool_choice', 'temperature', 'top_p', 'stop', 'presence_penalty', 'frequency_penalty']) {
138
- if (body[key] !== undefined) extra[key] = body[key];
139
- }
140
- // `reasoning_effort` is OpenAI's spelling of the AEGIS effort rung; a client
141
- // that offers the knob should get the behaviour it names, not a silent no-op.
142
- const eff = body.reasoning_effort || body.effort;
143
- if (typeof eff === 'string' && ['low', 'medium', 'high'].includes(eff.toLowerCase())) {
144
- extra.effort = eff.toLowerCase();
145
- }
146
- if (body.workers !== undefined) extra.workers = body.workers;
147
- return extra;
148
- }
149
-
150
- function sseHead(res) {
151
- res.writeHead(200, {
152
- 'Content-Type': 'text/event-stream; charset=utf-8',
153
- 'Cache-Control': 'no-cache, no-transform',
154
- Connection: 'keep-alive',
155
- 'X-Accel-Buffering': 'no',
156
- });
157
- }
158
-
159
- function sseSend(res, payload) {
160
- res.write(`data: ${JSON.stringify(payload)}\n\n`);
161
- }
162
-
163
- function chunkFrame(id, model, delta, finishReason) {
164
- return {
165
- id,
166
- object: 'chat.completion.chunk',
167
- created: Math.floor(Date.now() / 1000),
168
- model: model || 'aegis',
169
- choices: [{ index: 0, delta, finish_reason: finishReason || null }],
170
- };
171
- }
172
-
173
- // ---------------------------------------------------------------------------
174
- // Server
175
- // ---------------------------------------------------------------------------
176
-
177
- /**
178
- * @param {object} opts
179
- * @param {object} [opts.client] Injected transport (tests pass a stub).
180
- * @param {number} [opts.port]
181
- * @param {string} [opts.host]
182
- * @param {boolean} [opts.allowRemote]
183
- * @param {boolean} [opts.requireKey] Reject callers that send no bearer token.
184
- * @param {NodeJS.WriteStream} [opts.log]
185
- * @param {Function} [opts.fetchModels] Override catalog fetch (tests).
186
- */
187
- function createShimServer(opts = {}) {
188
- const client = opts.client || createClient(credentials.clientOptions());
189
- const host = opts.host || DEFAULT_HOST;
190
- const port = opts.port === undefined ? DEFAULT_PORT : opts.port;
191
- const out = opts.log || process.stderr;
192
- const requireKey = opts.requireKey !== false;
193
- const fetchModels = opts.fetchModels || (() => client.listModels());
194
-
195
- assertBindAllowed(host, opts.allowRemote);
196
-
197
- // The catalog is cached for a minute: a model picker calls /v1/models on
198
- // every focus, and hitting aegiscloud.org each time is a visible stall in the
199
- // one UI where latency is most obvious.
200
- let catalog = { at: 0, models: [] };
201
- const CATALOG_MS = 60_000;
202
-
203
- async function models() {
204
- if (Date.now() - catalog.at < CATALOG_MS && catalog.models.length) return catalog.models;
205
- const raw = await fetchModels();
206
- catalog = { at: Date.now(), models: pickerEntries(normalizeModelCatalog(raw && raw.models ? raw.models : raw)) };
207
- return catalog.models;
208
- }
209
-
210
- function sendJson(res, status, payload) {
211
- const text = JSON.stringify(payload);
212
- res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(text) });
213
- res.end(text);
214
- }
215
-
216
- function oaiError(res, status, message, type) {
217
- sendJson(res, status, { error: { message, type: type || 'aegis_error', code: status } });
218
- }
219
-
220
- function authorized(req) {
221
- if (!requireKey) return true;
222
- const header = req.headers.authorization || '';
223
- const m = /^Bearer\s+(.+)$/i.exec(header);
224
- return Boolean(m && m[1].trim());
225
- }
226
-
227
- async function readBody(req) {
228
- const chunks = [];
229
- let size = 0;
230
- for await (const c of req) {
231
- size += c.length;
232
- if (size > 8 * 1024 * 1024) throw new Error('request body too large');
233
- chunks.push(c);
234
- }
235
- const text = Buffer.concat(chunks).toString('utf8');
236
- if (!text.trim()) return {};
237
- return JSON.parse(text);
238
- }
239
-
240
- async function handleModels(res) {
241
- const list = await models();
242
- sendJson(res, 200, {
243
- object: 'list',
244
- data: list.map((m) => ({
245
- id: m.id,
246
- object: 'model',
247
- created: EPOCH,
248
- owned_by: 'aegis',
249
- // Non-standard, harmless, and the reason the picker in Cline/Continue
250
- // does not show five identical rows.
251
- ...(m.label && m.label !== m.id ? { name: m.label } : {}),
252
- })),
253
- });
254
- }
255
-
256
- async function handleChat(req, res) {
257
- let body;
258
- try {
259
- body = await readBody(req);
260
- } catch (err) {
261
- return oaiError(res, 400, `invalid JSON body: ${err.message}`, 'invalid_request_error');
262
- }
263
-
264
- const messages = Array.isArray(body.messages) ? body.messages : null;
265
- if (!messages || !messages.length) {
266
- return oaiError(res, 400, '`messages` is required', 'invalid_request_error');
267
- }
268
-
269
- const stream = body.stream === true;
270
- const id = `chatcmpl-aegis-${Date.now().toString(36)}`;
271
- const model = body.model && body.model !== 'aegis-default' ? String(body.model) : undefined;
272
-
273
- const args = {
274
- messages,
275
- model,
276
- maxTokens: body.max_tokens || body.max_completion_tokens,
277
- extra: extraFromBody(body),
278
- includeUsage: stream,
279
- };
280
-
281
- if (!stream) {
282
- try {
283
- const r = await client.chatCompletion({ ...args, stream: false });
284
- const msg = (r.choices && r.choices[0] && r.choices[0].message) || { content: '' };
285
- return sendJson(res, 200, {
286
- id,
287
- object: 'chat.completion',
288
- created: Math.floor(Date.now() / 1000),
289
- model: r.model || model || 'aegis',
290
- choices: [{ index: 0, message: { role: 'assistant', ...msg }, finish_reason: msg.tool_calls ? 'tool_calls' : 'stop' }],
291
- usage: r.usage || undefined,
292
- });
293
- } catch (err) {
294
- return oaiError(res, err.status && err.status >= 400 && err.status < 600 ? err.status : 502, err.message);
295
- }
296
- }
297
-
298
- sseHead(res);
299
- let closed = false;
300
- req.on('close', () => { closed = true; });
301
- const write = (payload) => { if (!closed) sseSend(res, payload); };
302
-
303
- // First frame carries the role, exactly as OpenAI does — some clients
304
- // (Continue among them) key their stream parser off it.
305
- write(chunkFrame(id, model, { role: 'assistant', content: '' }));
306
-
307
- try {
308
- const r = await client.chatCompletion({
309
- ...args,
310
- stream: true,
311
- onStream: (ev) => {
312
- if (ev.delta) write(chunkFrame(id, model, { content: ev.delta }));
313
- else if (ev.reasoning) write(chunkFrame(id, model, { reasoning_content: ev.reasoning }));
314
- },
315
- onReasoning: (chunk) => write(chunkFrame(id, model, { reasoning_content: chunk })),
316
- });
317
-
318
- const msg = (r.choices && r.choices[0] && r.choices[0].message) || {};
319
- // Tool calls are accumulated inside the transport, not streamed
320
- // fragment-by-fragment, so they arrive as one final frame. That is a
321
- // legal OpenAI chunk (id + index + name + full arguments), and it is the
322
- // only shape the shared transport can prove is complete.
323
- if (Array.isArray(msg.tool_calls) && msg.tool_calls.length) {
324
- write(chunkFrame(id, model, {
325
- tool_calls: msg.tool_calls.map((tc, i) => ({
326
- index: i,
327
- id: tc.id,
328
- type: 'function',
329
- function: { name: tc.function && tc.function.name, arguments: (tc.function && tc.function.arguments) || '' },
330
- })),
331
- }));
332
- }
333
- write(chunkFrame(id, model, {}, msg.tool_calls && msg.tool_calls.length ? 'tool_calls' : 'stop'));
334
- if (r.usage) {
335
- write({ id, object: 'chat.completion.chunk', created: Math.floor(Date.now() / 1000), model: r.model || model || 'aegis', choices: [], usage: r.usage });
336
- }
337
- if (!closed) { res.write('data: [DONE]\n\n'); res.end(); }
338
- } catch (err) {
339
- // Headers are already sent, so the error travels as a terminal SSE frame
340
- // plus a marker the client can surface — an editor that shows a bare
341
- // stalled stream teaches the user nothing.
342
- write({ error: { message: err.message, type: 'aegis_error' } });
343
- if (!closed) { res.write('data: [DONE]\n\n'); res.end(); }
344
- }
345
- }
346
-
347
- const server = http.createServer((req, res) => {
348
- const url = new URL(req.url || '/', `http://${req.headers.host || '127.0.0.1'}`);
349
- const path = url.pathname.replace(/\/+$/, '') || '/';
350
-
351
- if (req.method === 'GET' && (path === '/health' || path === '/')) {
352
- return sendJson(res, 200, { ok: true, service: 'aegis-openai-shim', endpoint: `http://${host}:${port}/v1` });
353
- }
354
- // `/v1` is the OpenAI convention; Cursor and a few others probe `/models`
355
- // without the prefix, and refusing that reads as "the endpoint is wrong".
356
- if (req.method === 'GET' && (path === '/v1/models' || path === '/models')) {
357
- if (!authorized(req)) return oaiError(res, 401, 'missing API key — any non-empty value works locally', 'invalid_request_error');
358
- return handleModels(res).catch((err) => oaiError(res, 502, err.message));
359
- }
360
- if (req.method === 'POST' && (path === '/v1/chat/completions' || path === '/chat/completions')) {
361
- if (!authorized(req)) return oaiError(res, 401, 'missing API key — any non-empty value works locally', 'invalid_request_error');
362
- return handleChat(req, res);
363
- }
364
- // Anthropic-shaped probes from editors that auto-detect the provider.
365
- if (req.method === 'POST' && path === '/v1/messages') {
366
- return oaiError(res, 404, 'this endpoint speaks the OpenAI schema; point the client at /v1 with the OpenAI provider', 'invalid_request_error');
367
- }
368
- return oaiError(res, 404, `no such route: ${req.method} ${path}`, 'invalid_request_error');
369
- });
370
-
371
- server.listen = ((orig) => function listen(...a) {
372
- return orig.apply(server, a);
373
- })(server.listen);
374
-
375
- return {
376
- server,
377
- host,
378
- port,
379
- url: `http://${host}:${port}/v1`,
380
- listen() {
381
- return new Promise((resolve, reject) => {
382
- server.once('error', reject);
383
- server.listen(port, host, () => {
384
- const actual = server.address();
385
- logLine(out, `OpenAI-compatible endpoint on http://${host}:${actual.port}/v1`);
386
- logLine(out, `point any OpenAI-compatible client at that base URL (any API key value)`);
387
- resolve(actual);
388
- });
389
- });
390
- },
391
- close() {
392
- return new Promise((resolve) => server.close(resolve));
393
- },
394
- };
395
- }
396
-
397
- // ---------------------------------------------------------------------------
398
- // CLI
399
- // ---------------------------------------------------------------------------
400
-
401
- function parseArgv(argv) {
402
- const opts = { log: process.stderr };
403
- for (let i = 0; i < argv.length; i++) {
404
- const a = argv[i];
405
- if (a === '--port') opts.port = Number(argv[++i]);
406
- else if (a === '--host') opts.host = argv[++i];
407
- else if (a === '--allow-remote') opts.allowRemote = true;
408
- else if (a === '--no-auth') opts.requireKey = false;
409
- else if (a === '--help' || a === '-h') opts.help = true;
410
- }
411
- return opts;
412
- }
413
-
414
- async function main(argv) {
415
- const opts = parseArgv(argv);
416
- if (opts.help) {
417
- process.stdout.write([
418
- 'aegis openai shim — serve AEGIS as an OpenAI-compatible endpoint',
419
- '',
420
- ' node hosts/openai-shim.js [--port 8787] [--host 127.0.0.1] [--allow-remote] [--no-auth]',
421
- '',
422
- 'Then point a coding tool at it:',
423
- ' base URL http://127.0.0.1:8787/v1',
424
- ' API key anything non-empty (the AEGIS key is read from ~/.aegiscode/.env)',
425
- '',
426
- ].join('\n'));
427
- return 0;
428
- }
429
-
430
- const out = opts.log || process.stderr;
431
-
432
- // ── argument refusal, before the credential precondition ─────────────────
433
- //
434
- // The loopback guard runs FIRST. It is an argument refusal — the operator
435
- // asked for something the shim does not do — and every CLI convention
436
- // validates arguments before resolving credentials. Ordering it the other
437
- // way cost a real regression: `--host 0.0.0.0` without a key answered with
438
- // the no-key line, so the one invocation that would expose the account to
439
- // the network never printed the sentence that explains why it will not.
440
- try {
441
- assertBindAllowed(opts.host || DEFAULT_HOST, opts.allowRemote);
442
- } catch (err) {
443
- logLine(out, err.message);
444
- return 1;
445
- }
446
-
447
- // ── the shared env file, before any credential is resolved ───────────────
448
- //
449
- // Placed after the `--help` early-return so help stays instant, and before
450
- // `createShimServer` — which is where `createClient(credentials.clientOptions())`
451
- // runs and therefore the last point at which process.env can still decide the
452
- // key. An exported `AEGIS_API_KEY` always wins: loadEnvFile() fills only names
453
- // the environment does not already have. Failure is never fatal here — an
454
- // absent file is the pre-existing state — because the check right below turns
455
- // "no key at all" into one sentence instead of a 401 from another program.
456
- // Same call, same contract as cli/bin/aegiscode.js, desktop/main.js and
457
- // mcp/server.js; see this file's header for what its absence cost.
458
- try {
459
- const envFile = require('../client/env-file.js');
460
- const envResult = envFile.loadEnvFile();
461
- if (envResult.loose) {
462
- logLine(
463
- out,
464
- `${envResult.file} is readable by other accounts (mode ${envResult.mode.toString(8)}) — ` +
465
- 'consider `chmod 600` on it'
466
- );
467
- }
468
- } catch (e) {
469
- logLine(out, `could not read the shared env file: ${e && e.message}`);
470
- }
471
-
472
- // Refuse to serve with no account key. The shim cannot answer a single
473
- // request without one, and a keyless endpoint reports that failure to the
474
- // *editor*, hours later, as an opaque 401 — the exact confusion this check
475
- // removes. `--no-auth` is about the caller's bearer token, not this
476
- // credential, so it does not relax this.
477
- const resolved = credentials.resolveApiKey();
478
- if (!resolved.key) {
479
- logLine(
480
- out,
481
- `no AEGIS account key — ${credentials.HOW_TO_SET}, ` +
482
- `or set ${credentials.KEY_ENV} in ~/.aegiscode/.env`
483
- );
484
- return 1;
485
- }
486
- // Where the key came from, never the key itself: "did it pick up my .env or
487
- // the file an older sign-in wrote?" is the question a user actually has, and
488
- // it is unanswerable from a masked key alone.
489
- logLine(out, `AEGIS key: ${credentials.sourceLabel(resolved.source)}`);
490
-
491
- let shim;
492
- try {
493
- shim = createShimServer(opts);
494
- await shim.listen();
495
- } catch (err) {
496
- logLine(process.stderr, err.message);
497
- return 1;
498
- }
499
- const stop = async () => { await shim.close(); process.exit(0); };
500
- process.on('SIGINT', stop);
501
- process.on('SIGTERM', stop);
502
- return null; // runs until signalled
503
- }
504
-
505
- if (require.main === module) {
506
- main(process.argv.slice(2))
507
- .then((code) => {
508
- if (typeof code === 'number') process.exit(code);
509
- })
510
- .catch((err) => {
511
- logLine(process.stderr, err && err.message ? err.message : err);
512
- process.exit(1);
513
- });
514
- }
515
-
516
- module.exports = { createShimServer, extraFromBody, DEFAULT_PORT };
2
+ const e=require("node:fs"),t=require("node:path"),o=require("node:http"),{createClient:n}=require("../client/aegis.js"),s=require("../client/credentials.js"),{normalizeModelCatalog:r,pickerEntries:a}=require(function(){const o=[t.join(__dirname,"..","cli","src","models.js"),t.join(__dirname,"..","..","src","models.js")];for(const t of o)if(e.existsSync(t))return t;throw new Error(`aegis-shim: cannot find models.js. Expected cli/src/models.js beside hosts/ (source checkout) or src/models.js in the package root (installed). Looked in: ${o.join(", ")}`)}()),i="127.0.0.1",c=new Set(["127.0.0.1","::1","localhost"]);function l(e,t){if(!c.has(e)&&!t)throw new Error(`refusing to bind ${e}: the shim spends your account's tokens, so it is loopback-only unless you pass --allow-remote`)}function d(e,t){e.write(`aegis-shim: ${t}\n`)}function u(e){const t={};for(const o of["tools","tool_choice","temperature","top_p","stop","presence_penalty","frequency_penalty"])void 0!==e[o]&&(t[o]=e[o]);const o=e.reasoning_effort||e.effort;return"string"==typeof o&&["low","medium","high"].includes(o.toLowerCase())&&(t.effort=o.toLowerCase()),void 0!==e.workers&&(t.workers=e.workers),t}function m(e,t,o,n){return{id:e,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:t||"aegis",choices:[{index:0,delta:o,finish_reason:n||null}]}}function h(e={}){const t=e.client||n(s.clientOptions()),c=e.host||i,h=void 0===e.port?8787:e.port,p=e.log||process.stderr,g=!1!==e.requireKey,f=e.fetchModels||(()=>t.listModels());l(c,e.allowRemote);let y={at:0,models:[]};function w(e,t,o){const n=JSON.stringify(o);e.writeHead(t,{"Content-Type":"application/json; charset=utf-8","Content-Length":Buffer.byteLength(n)}),e.end(n)}function _(e,t,o,n){w(e,t,{error:{message:o,type:n||"aegis_error",code:t}})}function v(e){if(!g)return!0;const t=e.headers.authorization||"",o=/^Bearer\s+(.+)$/i.exec(t);return Boolean(o&&o[1].trim())}const k=o.createServer(((e,o)=>{const n=new URL(e.url||"/",`http://${e.headers.host||"127.0.0.1"}`).pathname.replace(/\/+$/,"")||"/";return"GET"!==e.method||"/health"!==n&&"/"!==n?"GET"!==e.method||"/v1/models"!==n&&"/models"!==n?"POST"!==e.method||"/v1/chat/completions"!==n&&"/chat/completions"!==n?"POST"===e.method&&"/v1/messages"===n?_(o,404,"this endpoint speaks the OpenAI schema; point the client at /v1 with the OpenAI provider","invalid_request_error"):_(o,404,`no such route: ${e.method} ${n}`,"invalid_request_error"):v(e)?async function(e,o){let n;try{n=await async function(e){const t=[];let o=0;for await(const n of e){if(o+=n.length,o>8388608)throw new Error("request body too large");t.push(n)}const n=Buffer.concat(t).toString("utf8");return n.trim()?JSON.parse(n):{}}(e)}catch(e){return _(o,400,`invalid JSON body: ${e.message}`,"invalid_request_error")}const s=Array.isArray(n.messages)?n.messages:null;if(!s||!s.length)return _(o,400,"`messages` is required","invalid_request_error");const r=!0===n.stream,a=`chatcmpl-aegis-${Date.now().toString(36)}`,i=n.model&&"aegis-default"!==n.model?String(n.model):void 0,c={messages:s,model:i,maxTokens:n.max_tokens||n.max_completion_tokens,extra:u(n),includeUsage:r};if(!r)try{const e=await t.chatCompletion({...c,stream:!1}),n=e.choices&&e.choices[0]&&e.choices[0].message||{content:""};return w(o,200,{id:a,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:e.model||i||"aegis",choices:[{index:0,message:{role:"assistant",...n},finish_reason:n.tool_calls?"tool_calls":"stop"}],usage:e.usage||void 0})}catch(e){return _(o,e.status&&e.status>=400&&e.status<600?e.status:502,e.message)}!function(e){e.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"})}(o);let l=!1;e.on("close",(()=>{l=!0}));const d=e=>{l||function(e,t){e.write(`data: ${JSON.stringify(t)}\n\n`)}(o,e)};d(m(a,i,{role:"assistant",content:""}));try{const e=await t.chatCompletion({...c,stream:!0,onStream:e=>{e.delta?d(m(a,i,{content:e.delta})):e.reasoning&&d(m(a,i,{reasoning_content:e.reasoning}))},onReasoning:e=>d(m(a,i,{reasoning_content:e}))}),n=e.choices&&e.choices[0]&&e.choices[0].message||{};Array.isArray(n.tool_calls)&&n.tool_calls.length&&d(m(a,i,{tool_calls:n.tool_calls.map(((e,t)=>({index:t,id:e.id,type:"function",function:{name:e.function&&e.function.name,arguments:e.function&&e.function.arguments||""}})))})),d(m(a,i,{},n.tool_calls&&n.tool_calls.length?"tool_calls":"stop")),e.usage&&d({id:a,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.model||i||"aegis",choices:[],usage:e.usage}),l||(o.write("data: [DONE]\n\n"),o.end())}catch(e){d({error:{message:e.message,type:"aegis_error"}}),l||(o.write("data: [DONE]\n\n"),o.end())}}(e,o):_(o,401,"missing API key — any non-empty value works locally","invalid_request_error"):v(e)?async function(e){w(e,200,{object:"list",data:(await async function(){if(Date.now()-y.at<6e4&&y.models.length)return y.models;const e=await f();return y={at:Date.now(),models:a(r(e&&e.models?e.models:e))},y.models}()).map((e=>({id:e.id,object:"model",created:1735689600,owned_by:"aegis",...e.label&&e.label!==e.id?{name:e.label}:{}})))})}(o).catch((e=>_(o,502,e.message))):_(o,401,"missing API key — any non-empty value works locally","invalid_request_error"):w(o,200,{ok:!0,service:"aegis-openai-shim",endpoint:`http://${c}:${h}/v1`})}));var b;return k.listen=(b=k.listen,function(...e){return b.apply(k,e)}),{server:k,host:c,port:h,url:`http://${c}:${h}/v1`,listen:()=>new Promise(((e,t)=>{k.once("error",t),k.listen(h,c,(()=>{const t=k.address();d(p,`OpenAI-compatible endpoint on http://${c}:${t.port}/v1`),d(p,"point any OpenAI-compatible client at that base URL (any API key value)"),e(t)}))})),close:()=>new Promise((e=>k.close(e)))}}require.main===module&&async function(e){const t=function(e){const t={log:process.stderr};for(let o=0;o<e.length;o++){const n=e[o];"--port"===n?t.port=Number(e[++o]):"--host"===n?t.host=e[++o]:"--allow-remote"===n?t.allowRemote=!0:"--no-auth"===n?t.requireKey=!1:"--help"!==n&&"-h"!==n||(t.help=!0)}return t}(process.argv.slice(2));if(t.help)return process.stdout.write(["aegis openai shim — serve AEGIS as an OpenAI-compatible endpoint",""," node hosts/openai-shim.js [--port 8787] [--host 127.0.0.1] [--allow-remote] [--no-auth]","","Then point a coding tool at it:"," base URL http://127.0.0.1:8787/v1"," API key anything non-empty (the AEGIS key is read from ~/.aegiscode/.env)",""].join("\n")),0;const o=t.log||process.stderr;try{l(t.host||i,t.allowRemote)}catch(e){return d(o,e.message),1}try{const e=require("../client/env-file.js").loadEnvFile();e.loose&&d(o,`${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it`)}catch(e){d(o,`could not read the shared env file: ${e&&e.message}`)}const n=s.resolveApiKey();if(!n.key)return d(o,`no AEGIS account key — ${s.HOW_TO_SET}, or set ${s.KEY_ENV} in ~/.aegiscode/.env`),1;let r;d(o,`AEGIS key: ${s.sourceLabel(n.source)}`);try{r=h(t),await r.listen()}catch(e){return d(process.stderr,e.message),1}const a=async()=>{await r.close(),process.exit(0)};return process.on("SIGINT",a),process.on("SIGTERM",a),null}().then((e=>{"number"==typeof e&&process.exit(e)})).catch((e=>{d(process.stderr,e&&e.message?e.message:e),process.exit(1)})),module.exports={createShimServer:h,extraFromBody:u,DEFAULT_PORT:8787};