aegiscode 7.0.25 → 7.0.26
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/package.json +7 -3
- package/scripts/check.mjs +52 -1
- package/scripts/demo.mjs +94 -1
- package/scripts/predist.mjs +75 -1
- package/scripts/runtests.mjs +56 -1
- package/scripts/seal-gate.mjs +74 -1
- package/src/agents.js +139 -1
- package/src/app.js +2957 -1
- package/src/art.js +289 -1
- package/src/chatflow.js +3023 -1
- package/src/checkpoint.js +90 -1
- package/src/clipboard.js +424 -1
- package/src/cloudsync.js +528 -1
- package/src/commands.js +4089 -1
- package/src/config.js +581 -1
- package/src/connect.js +349 -1
- package/src/credentials.js +33 -1
- package/src/deps.js +232 -1
- package/src/devrun.js +187 -1
- package/src/diff.js +333 -1
- package/src/diffview.js +296 -1
- package/src/engine.js +297 -1
- package/src/entitlement.js +355 -1
- package/src/events.js +707 -1
- package/src/export.js +67 -1
- package/src/filepreview.js +153 -1
- package/src/fingerprint.js +592 -1
- package/src/format.js +259 -1
- package/src/fuzzy.js +119 -1
- package/src/history.js +423 -1
- package/src/init.js +175 -1
- package/src/input.js +139 -1
- package/src/keys.js +183 -1
- package/src/markdown.js +306 -1
- package/src/models.js +507 -1
- package/src/naming.js +57 -1
- package/src/overlays.js +462 -1
- package/src/panels.js +1418 -1
- package/src/ping.js +226 -1
- package/src/presence.js +238 -1
- package/src/render.js +516 -1
- package/src/screen.js +518 -1
- package/src/screens.js +896 -1
- package/src/secret.js +59 -1
- package/src/securefs.js +359 -1
- package/src/settings.js +155 -1
- package/src/shared.js +52 -1
- package/src/sharedpaths.js +53 -1
- package/src/signup.js +156 -1
- package/src/summarize.js +95 -1
- package/src/sysdiag.js +585 -1
- package/src/system.js +40 -1
- package/src/theme.js +570 -1
- package/src/title.js +220 -1
- package/src/todos.js +115 -1
- package/src/tokens.js +263 -1
- package/src/topup.js +210 -1
- package/src/update.js +191 -1
- package/vendor/client/aegis.js +2441 -1
- package/vendor/client/attest.js +518 -1
- package/vendor/client/authorship-key.js +410 -1
- package/vendor/client/auto-provision.js +134 -1
- package/vendor/client/brain-catalog.js +268 -1
- package/vendor/client/byok-catalog.js +199 -1
- package/vendor/client/catalog-client.js +487 -1
- package/vendor/client/conversation-export.js +177 -1
- package/vendor/client/credentials.js +494 -1
- package/vendor/client/device-fingerprint.js +141 -1
- package/vendor/client/drive-connect.js +110 -1
- package/vendor/client/drive-upload.js +234 -1
- package/vendor/client/env-file.js +1273 -1
- package/vendor/client/fingerprint.js +1064 -1
- package/vendor/client/foreign-memory.js +669 -1
- package/vendor/client/google-signin.js +133 -1
- package/vendor/client/hooks.js +430 -1
- package/vendor/client/model-discovery.js +373 -1
- package/vendor/client/naming.js +283 -1
- package/vendor/client/platform.js +937 -1
- package/vendor/client/prefs.js +351 -1
- package/vendor/client/presence-constants.js +107 -1
- package/vendor/client/presence.js +438 -1
- package/vendor/client/record-vault.js +1055 -3
- package/vendor/client/session-store.js +575 -1
- package/vendor/client/topup.js +297 -1
- package/vendor/client/touch.js +458 -1
- package/vendor/client/update.js +763 -1
- package/vendor/client/user-models.js +381 -1
- package/vendor/desktop/lib/local/agents.js +105 -1
- package/vendor/desktop/lib/local/attachments.js +276 -1
- package/vendor/desktop/lib/local/autonomous.js +1045 -1
- package/vendor/desktop/lib/local/claude-pro.js +1028 -1
- package/vendor/desktop/lib/local/context.js +125 -1
- package/vendor/desktop/lib/local/engine.js +3666 -1
- package/vendor/desktop/lib/local/entitlement.js +660 -1
- package/vendor/desktop/lib/local/git-scope.js +228 -1
- package/vendor/desktop/lib/local/local.js +2145 -1
- package/vendor/desktop/lib/local/prompt.js +280 -1
- package/vendor/desktop/lib/local/queue.js +560 -1
- package/vendor/desktop/lib/local/session-rounds.js +238 -1
- package/vendor/desktop/lib/local/spill.js +75 -1
- package/vendor/desktop/lib/local/turn-guard.js +300 -1
- package/vendor/desktop/lib/local/worktree-lock.js +235 -1
- package/vendor/desktop/lib/settings.js +890 -1
- package/vendor/desktop/renderer/usage.js +1239 -1
- package/vendor/hosts/install.js +638 -1
- package/vendor/hosts/openai-shim.js +515 -1
- package/vendor/hosts/spec.js +164 -1
- package/vendor/hosts/targets.js +346 -1
- package/vendor/mcp/server.js +221 -1
- package/vendor/mcp/tools.js +408 -1
- package/vendor/one/src/child.js +285 -1
- package/vendor/one/src/permissions.js +383 -1
- package/SOURCE-OFFER.txt +0 -9
|
@@ -1,2 +1,516 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
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 };
|