aegiscode 6.8.6 → 6.8.8

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,319 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Private files in the data dir (~/.aegiscode) — hardening against a local
5
+ * info-stealer, which is the threat the CLI's own store actually invites.
6
+ *
7
+ * What was wrong: every writer in this CLI used `fs.writeFileSync(p, data)`
8
+ * with no `mode`, and `fs.mkdirSync(dir, { recursive: true })` with no `mode`.
9
+ * Both therefore inherited the process umask, which on a default desktop Linux
10
+ * is 0002 — so the data dir landed at 0775 and every file in it at 0664. On a
11
+ * single-user box that looks harmless. It is not:
12
+ *
13
+ * - 0664 is world-READABLE. history.jsonl is every prompt and every reply the
14
+ * user has ever sent, checkpoints/ is the same in full, and clipboard.txt is
15
+ * verbatim whatever the user last marked and copied. Any other local account
16
+ * — or any process running as one — reads all of it with plain `cat`.
17
+ * - 0664 is group-WRITABLE, and so was the 0775 directory. config.json holds
18
+ * `provider` and `baseURL`, so a second account in the group could repoint
19
+ * the CLI's endpoint at a host it controls and collect the prompts, the
20
+ * completions, and the credentials relayed through it. A writable data dir
21
+ * also lets anyone drop a `permissions.json` that pre-approves the tools
22
+ * they want the next session to run unprompted.
23
+ *
24
+ * Two properties matter beyond the mode bits:
25
+ *
26
+ * - `O_NOFOLLOW` on create. `writeFileSync` follows symlinks, so a symlink
27
+ * planted at `~/.aegiscode/clipboard.txt` pointing at `~/.bashrc` turned a
28
+ * copy gesture into an arbitrary file overwrite. Creating with
29
+ * `O_CREAT|O_EXCL|O_NOFOLLOW` — after unlinking any leftover — fails instead
30
+ * of following, and `O_EXCL` closes the window between the unlink and the
31
+ * open: a symlink raced into place makes the open fail with EEXIST rather
32
+ * than being followed.
33
+ * - `rename`, not truncate, for the atomic path. `renameSync` replaces a
34
+ * planted symlink instead of writing through it, so the atomic writers
35
+ * (config, permissions) are safe even without the O_EXCL dance.
36
+ *
37
+ * Ownership is checked before every chmod and never chmod'ed through a symlink,
38
+ * so a data dir that is deliberately shared (or root-owned) is left alone rather
39
+ * than having its permissions silently rewritten by us. Every helper is
40
+ * best-effort in the same spirit as the rest of this CLI: a hardening step that
41
+ * cannot be applied must not be the reason a session cannot save.
42
+ *
43
+ * Deliberately dependency-free — no `shared.js`, no engine — so it can be
44
+ * required from anything without a cycle, and unit-tested in isolation.
45
+ */
46
+
47
+ const fs = require('node:fs');
48
+ const path = require('node:path');
49
+
50
+ // O_NOFOLLOW is POSIX; on Windows the constant is absent, leaving the mode and
51
+ // rename protections (which do not depend on it) in place.
52
+ const NOFOLLOW = fs.constants.O_NOFOLLOW || 0;
53
+
54
+ /** True when `st` is owned by the current user (always true where getuid is absent). */
55
+ function ownedByUs(st) {
56
+ if (typeof process.getuid !== 'function') return true;
57
+ try { return st.uid === process.getuid(); } catch { return false; }
58
+ }
59
+
60
+ /**
61
+ * Force `p` to `mode`, but only when it is a real file we own.
62
+ * Never follows a symlink (chmod through a link would modify its target) and
63
+ * never returns false for a file that is already correct.
64
+ */
65
+ function chmodPrivate(p, mode = 0o600) {
66
+ try {
67
+ const st = fs.lstatSync(p);
68
+ if (st.isSymbolicLink()) return false;
69
+ if (!ownedByUs(st)) return false;
70
+ if ((st.mode & 0o777) === mode) return true;
71
+ fs.chmodSync(p, mode);
72
+ return true;
73
+ } catch {
74
+ return false;
75
+ }
76
+ }
77
+
78
+ /**
79
+ * `mkdir -p` at 0700, and tighten a directory that already exists.
80
+ * `mkdirSync` ignores `mode` for a directory that is already there, so an
81
+ * install that predates this module keeps its 0775 without the explicit chmod.
82
+ */
83
+ function ensurePrivateDir(dir) {
84
+ try {
85
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
86
+ } catch {
87
+ return false;
88
+ }
89
+ try {
90
+ const st = fs.lstatSync(dir);
91
+ if (st.isSymbolicLink() || !st.isDirectory()) return false;
92
+ if (ownedByUs(st) && (st.mode & 0o077) !== 0) fs.chmodSync(dir, 0o700);
93
+ return true;
94
+ } catch {
95
+ return false;
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Write `data` to `file` with mode 0600, creating the parent dir at 0700.
101
+ *
102
+ * atomic (default) writes `file.tmp` and renames over the target, so a crash
103
+ * cannot truncate a live config and a planted symlink is replaced rather than
104
+ * followed. `{ atomic: false }` truncates in place instead, which is the right
105
+ * shape for a scratch file that is never read concurrently — it still refuses
106
+ * to follow a symlink at `file`.
107
+ *
108
+ * Throws on failure; callers already treat a failed save as non-fatal.
109
+ */
110
+ function writePrivateFile(file, data, opts = {}) {
111
+ const dir = path.dirname(file);
112
+ ensurePrivateDir(dir);
113
+
114
+ const common = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | NOFOLLOW;
115
+
116
+ if (opts.atomic === false) {
117
+ try { fs.unlinkSync(file); } catch {} // drop a leftover or a planted symlink
118
+ const fd = fs.openSync(file, common, 0o600);
119
+ try {
120
+ fs.fchmodSync(fd, 0o600);
121
+ fs.writeFileSync(fd, data);
122
+ } finally {
123
+ fs.closeSync(fd);
124
+ }
125
+ return true;
126
+ }
127
+
128
+ const tmp = file + '.tmp';
129
+ try { fs.unlinkSync(tmp); } catch {}
130
+ const fd = fs.openSync(tmp, common, 0o600);
131
+ try {
132
+ fs.fchmodSync(fd, 0o600);
133
+ fs.writeFileSync(fd, data);
134
+ } finally {
135
+ fs.closeSync(fd);
136
+ }
137
+ fs.renameSync(tmp, file); // replaces a planted symlink instead of writing through it
138
+ chmodPrivate(file, 0o600);
139
+ return true;
140
+ }
141
+
142
+ /**
143
+ * ---------------------------------------------------------------------------
144
+ * Retroactive repair.
145
+ * ---------------------------------------------------------------------------
146
+ *
147
+ * `writePrivateFile` hardens a path only at the moment it is written, so an
148
+ * install that predates this module keeps its 0664/0775 indefinitely: each
149
+ * writer fixes a file the next time that file happens to change, and nothing
150
+ * ever revisits the rest. On the real store that left `~/.aegiscode` at 0775
151
+ * with config.json, permissions.json, history.jsonl, clipboard.txt and every
152
+ * file under checkpoints/ and indexes/ at 0664 — months of transcripts, plus a
153
+ * group-writable endpoint — readable by any other local account.
154
+ *
155
+ * `repairExposure` walks the data dir once and forces it private. Three details
156
+ * are load-bearing rather than incidental:
157
+ *
158
+ * - The exec bit is PRESERVED, not stripped. This directory is not purely
159
+ * data: `oauth-proxy.js` (0775) and `bin/aegis-cli` (0755) are run from
160
+ * here, so the obvious implementation — a blanket `chmod 0600` — would
161
+ * silently break both. The rule is therefore mode-relative: a directory, or
162
+ * a file the owner may execute, becomes 0700; anything else becomes 0600.
163
+ * Nothing loses a permission it needed; everything loses the ones it did
164
+ * not.
165
+ * - Symlinks are never entered and never chmod'ed through, for the same reason
166
+ * `chmodPrivate` refuses them: a planted link would otherwise make the
167
+ * repair itself the write primitive.
168
+ * - The root directory is the high-value step. At 0700 no other account can
169
+ * traverse into it at all, which covers every file inside — including the
170
+ * executables above whose own modes stay permissive. The per-file pass is
171
+ * defence in depth for the case where the directory is later re-shared,
172
+ * restored from a backup, or a file is copied out of it.
173
+ *
174
+ * The read-only (`auditExposure`) and writing (`repairExposure`) entry points
175
+ * are deliberately separate so `/doctor` can report exposure without changing
176
+ * anything, and only act on an explicit `/doctor fix`.
177
+ */
178
+
179
+ /** Longest path (below the data dir) the repair walk will descend. */
180
+ const MAX_WALK_DEPTH = 4;
181
+
182
+ /** `0775`-style rendering of the permission bits of a `stat`. */
183
+ function fmtMode(mode) {
184
+ return '0' + (mode & 0o777).toString(8).padStart(3, '0');
185
+ }
186
+
187
+ /**
188
+ * The mode a path should hold: 0700 when the owner needs to traverse or execute
189
+ * it (a directory, or a file carrying an owner-exec bit), 0600 otherwise.
190
+ */
191
+ function targetMode(st) {
192
+ if (st.isDirectory()) return 0o700;
193
+ return st.mode & 0o100 ? 0o700 : 0o600;
194
+ }
195
+
196
+ /**
197
+ * Every non-symlink entry under `root`, depth-first, with its lstat.
198
+ * Unreadable directories are skipped rather than thrown on: a repair that
199
+ * cannot see a subtree must still fix the rest of it.
200
+ */
201
+ function scanTree(root) {
202
+ const out = [];
203
+ const walk = (dir, rel, depth) => {
204
+ if (depth > MAX_WALK_DEPTH) return;
205
+ let entries;
206
+ try {
207
+ entries = fs.readdirSync(dir, { withFileTypes: true });
208
+ } catch {
209
+ return;
210
+ }
211
+ for (const e of entries) {
212
+ if (e.isSymbolicLink()) continue; // never followed, never chmod'ed through
213
+ const full = path.join(dir, e.name);
214
+ const childRel = rel ? `${rel}/${e.name}` : e.name;
215
+ let st;
216
+ try {
217
+ st = fs.lstatSync(full);
218
+ } catch {
219
+ continue;
220
+ }
221
+ out.push({ rel: childRel, full, st });
222
+ if (st.isDirectory()) walk(full, childRel, depth + 1);
223
+ }
224
+ };
225
+ walk(root, '', 0);
226
+ return out;
227
+ }
228
+
229
+ /** Does `mode` grant anything to group or other? */
230
+ function exposedBits(mode) {
231
+ return (mode & 0o077) !== 0;
232
+ }
233
+
234
+ /**
235
+ * Report every path in the data dir that is reachable by group or other.
236
+ *
237
+ * Read-only. Returns `{ root, exists, rootMode, exposed, total }` where each
238
+ * entry of `exposed` is `{ rel, mode, kind }` — `rel` is `.` for the root
239
+ * itself, and `kind` is `'dir'` or `'file'`.
240
+ */
241
+ function auditExposure(root) {
242
+ const report = { root, exists: false, rootMode: null, exposed: [], total: 0 };
243
+ let rst;
244
+ try {
245
+ rst = fs.lstatSync(root);
246
+ } catch {
247
+ return report;
248
+ }
249
+ if (rst.isSymbolicLink() || !rst.isDirectory()) return report;
250
+ report.exists = true;
251
+ report.rootMode = fmtMode(rst.mode);
252
+ if (exposedBits(rst.mode)) report.exposed.push({ rel: '.', mode: report.rootMode, kind: 'dir' });
253
+
254
+ const items = scanTree(root);
255
+ report.total = items.length;
256
+ for (const it of items) {
257
+ if (!exposedBits(it.st.mode)) continue;
258
+ report.exposed.push({
259
+ rel: it.rel,
260
+ mode: fmtMode(it.st.mode),
261
+ kind: it.st.isDirectory() ? 'dir' : 'file',
262
+ });
263
+ }
264
+ return report;
265
+ }
266
+
267
+ /**
268
+ * Force every group/world-accessible path in the data dir back to 0700/0600,
269
+ * preserving the owner-exec bit (see the block comment above).
270
+ *
271
+ * Best-effort and idempotent: a path that is already private is left untouched,
272
+ * a path we do not own is reported rather than fought over, and a second run
273
+ * fixes nothing. Returns `{ root, exists, fixed, failed, remaining }`, where
274
+ * `remaining` is the exposure audit taken after the pass — non-empty only when
275
+ * something could not be repaired.
276
+ */
277
+ function repairExposure(root) {
278
+ const report = { root, exists: false, fixed: [], failed: [], remaining: [] };
279
+ let rst;
280
+ try {
281
+ rst = fs.lstatSync(root);
282
+ } catch {
283
+ return report;
284
+ }
285
+ if (rst.isSymbolicLink() || !rst.isDirectory()) return report;
286
+ report.exists = true;
287
+
288
+ const tighten = (full, st, rel) => {
289
+ if (!ownedByUs(st)) {
290
+ report.failed.push({ rel, reason: 'not owned by this user' });
291
+ return;
292
+ }
293
+ const want = targetMode(st);
294
+ try {
295
+ fs.chmodSync(full, want);
296
+ report.fixed.push({ rel, from: fmtMode(st.mode), to: fmtMode(want) });
297
+ } catch (err) {
298
+ report.failed.push({ rel, reason: err.code || String(err) });
299
+ }
300
+ };
301
+
302
+ if (exposedBits(rst.mode)) tighten(root, rst, '.');
303
+ for (const it of scanTree(root)) {
304
+ if (!exposedBits(it.st.mode)) continue;
305
+ tighten(it.full, it.st, it.rel);
306
+ }
307
+
308
+ report.remaining = auditExposure(root).exposed;
309
+ return report;
310
+ }
311
+
312
+ module.exports = {
313
+ ensurePrivateDir,
314
+ writePrivateFile,
315
+ chmodPrivate,
316
+ auditExposure,
317
+ repairExposure,
318
+ fmtMode,
319
+ };
package/src/theme.js CHANGED
@@ -15,14 +15,15 @@
15
15
  * What DOES change per terminal is how those triples reach the screen:
16
16
  *
17
17
  * · `RGB()`/`BG()` go through `caps.rgb()/caps.bg()`, which emit 24-bit SGR,
18
- * the 256-colour cube, the 16 ANSI slots, or nothing at all — decided by the
19
- * terminal, not by us. On a legacy Windows console or `TERM=linux` the UI
20
- * now paints in colours that console can actually show, instead of emitting
21
- * truecolor escapes it renders as literal text or dithers unpredictably.
22
- * · `glyphsFor()` is a function of the resolved capabilities, so PowerShell in
23
- * Windows Terminal gets the same ❯ ⎿ ✻ ✦ set as zsh, and only a terminal
24
- * that genuinely cannot draw them (legacy console, `TERM=dumb`, a non-UTF-8
25
- * locale, `AEGIS_ART=ascii`) gets the ASCII stand-ins.
18
+ * the 256-colour cube, the 16 ANSI slots, or nothing at all. Truecolor is
19
+ * the default on every platform, because the terminals we ship to all pass
20
+ * 24-bit SGR through and a terminal that cannot downsamples it itself —
21
+ * which is the correct authority for the decision. Narrowing the palette is
22
+ * an explicit request (`AEGIS_COLOR=1|2`, `FORCE_COLOR`, `NO_COLOR`,
23
+ * `AEGIS_FORCE_TRUECOLOR=0`), never an inference from `TERM` or the OS.
24
+ * · `glyphsFor()` is a function of the resolved capabilities, so every host
25
+ * gets the same ❯ ⎿ ✻ ✦ set; the ASCII stand-ins appear only when the user
26
+ * asks for them (`AEGIS_ART=ascii`, `--ascii`).
26
27
  *
27
28
  * Both are re-materialised when the capabilities change (`onCapsChange`), so
28
29
  * `aegiscode --ascii`, `--no-color` and the `/terminal` command take effect on
@@ -284,25 +285,26 @@ function diffOf(ctx) {
284
285
  * A few of the reference's glyphs are missing from some terminal fonts
285
286
  * (⎿ U+23BF, ⏸ U+23F8, ✔ U+2714, ▸ U+25B8) or render as double-width emoji
286
287
  * (✦ U+2726, ✻/✢/✽/✶), which breaks row alignment exactly like the welcome art.
287
- * The three capability classes in `caps.js` decide the set:
288
+ * The capability classes in `caps.js` decide the set, and the host is not one of
289
+ * them — see the policy at the top of that file:
288
290
  *
289
- * · `glyphs: 'ascii'` — no Unicode claim at all: legacy Windows console,
290
- * `TERM=dumb`, a non-UTF-8 locale, `AEGIS_ART=ascii`. Every mark becomes a
291
- * single-column ASCII stand-in, so the layout is identical but nothing is
292
- * mis-rendered by a font that lacks the glyph.
293
- * · `face: 'edges'` — the block palette survives but the quartile edges
294
- * and the typographic marks (⎿, ⏸, ✔) do not (Apple fonts, older Windows
295
- * fonts). Only those are swapped.
296
- * · native — the reference's own set, on any terminal that can
297
- * draw it: Windows Terminal, VS Code, iTerm2, WezTerm, kitty, Ghostty,
298
- * Alacritty, GNOME Terminal, xterm, zsh on Linux/macOS.
291
+ * · `glyphs: 'ascii'` — no Unicode claim at all, requested with
292
+ * `AEGIS_ART=ascii` / `--ascii`. Every mark becomes a single-column ASCII
293
+ * stand-in, so the layout is identical but nothing is mis-rendered by a font
294
+ * that lacks the glyph.
295
+ * · `face: 'edges'` — the quartile edges and the typographic marks (⎿, ⏸,
296
+ * ✔) are swapped; reachable today only through the ASCII pass, and kept
297
+ * because `AEGIS_ART=unicode` on a font without the edges must be
298
+ * expressible.
299
+ * · native — the default everywhere: the reference's own set.
299
300
  *
300
301
  * `star` is NOT restated here: it is resolved through `art.js`'s stencil, the
301
302
  * single source of truth for the mark's runes, so the glyph table and the art
302
303
  * can never disagree about the same character.
303
304
  *
304
- * @param {string|object} [target] a `process.platform` name, or a caps object,
305
- * or nothing at all for the live process's resolved capabilities.
305
+ * @param {string|object} [target] a `process.platform` name (accepted for
306
+ * tests, ignored by the policy), or a caps object, or nothing at all for the
307
+ * live process's resolved capabilities.
306
308
  */
307
309
  function glyphsFor(target = null) {
308
310
  const c = !target
@@ -189,11 +189,12 @@ function createClient(opts = {}) {
189
189
  return headers;
190
190
  }
191
191
 
192
- async function apiPost(path, body, headers) {
192
+ async function apiPost(path, body, headers, opts) {
193
193
  const res = await fetch(`${apiBase}${path}`, {
194
194
  method: 'POST',
195
195
  headers: headers || authHeaders(),
196
196
  body: JSON.stringify(body || {}),
197
+ signal: opts && opts.signal,
197
198
  });
198
199
  return parseResponse(res);
199
200
  }
@@ -371,6 +372,19 @@ function createClient(opts = {}) {
371
372
  return apiPost('/api/verify-api-key', { api_key: apiKey });
372
373
  }
373
374
 
375
+ /**
376
+ * Ask aegis1 for a free device key when the caller has none configured yet
377
+ * (`POST /api/v1/auth/register-device`). Idempotent server-side on
378
+ * `fingerprint` — the same fingerprint always returns the same account's
379
+ * key rather than minting a new one. The account starts at zero token-bank
380
+ * balance: this hands out an account, not free inference, so the existing
381
+ * balance=0 gate on `/api/v1/chat/completions` still applies unchanged.
382
+ * Sends no API key of its own — there isn't one yet.
383
+ */
384
+ async function registerDevice(fingerprint, opts) {
385
+ return apiPost('/api/v1/auth/register-device', { fingerprint }, undefined, opts);
386
+ }
387
+
374
388
  /** Build the OpenAI-style messages array from either a full history or the
375
389
  * single-shot { system, prompt } shorthand.
376
390
  *
@@ -994,6 +1008,7 @@ function createClient(opts = {}) {
994
1008
  },
995
1009
  promptUrl,
996
1010
  verifyApiKey,
1011
+ registerDevice,
997
1012
  chatCompletion,
998
1013
  byokChatCompletion,
999
1014
  listModels,
@@ -0,0 +1,52 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Auto-provision a free aegis1 device key when a host finds no key configured
5
+ * anywhere (env, the shared 0600 store, legacy config.json). One
6
+ * implementation shared by every host (MCP plugin, desktop, CLI) — see
7
+ * client/credentials.js's own header for why that matters here: three copies
8
+ * of the same timeout/endpoint/save logic is how they drift.
9
+ *
10
+ * Calls aegis1's `POST /api/v1/auth/register-device` (see client/aegis.js's
11
+ * `registerDevice`), idempotent per machine fingerprint (client/
12
+ * device-fingerprint.js) so a wiped credential store still resolves back to
13
+ * the same account rather than minting a new, unfunded one.
14
+ *
15
+ * The provisioned account starts at ZERO token-bank balance server-side, and
16
+ * aegis1 additionally requires an upgraded (paid, active) plan to use pooled
17
+ * aegiscloud models at all (nexus_chat_completions' is_pro() gate) — this
18
+ * only unblocks BYOK and account status/settings until the account is funded
19
+ * and/or upgraded. It is account creation, not a grant of free inference.
20
+ */
21
+ const { machineFingerprint } = require('./device-fingerprint.js');
22
+
23
+ const DEVICE_REGISTER_TIMEOUT_MS = 8000;
24
+
25
+ /**
26
+ * @param {object} aegisClient A client from client/aegis.js (createClient()).
27
+ * @param {object} credentials client/credentials.js (or a compatible double).
28
+ * @returns {Promise<{ok: boolean, key: string, error?: Error}>}
29
+ * `ok` is true only when a usable key was obtained AND persisted to the
30
+ * shared store; `aegisClient.setApiKey()` has already been called on
31
+ * success, so the caller's client is immediately usable either way it
32
+ * inspects `ok`.
33
+ */
34
+ async function autoProvisionApiKey(aegisClient, credentials) {
35
+ if (aegisClient.apiKey) return { ok: true, key: aegisClient.apiKey };
36
+ const controller = new AbortController();
37
+ const timer = setTimeout(() => controller.abort(), DEVICE_REGISTER_TIMEOUT_MS);
38
+ try {
39
+ const data = await aegisClient.registerDevice(machineFingerprint(), { signal: controller.signal });
40
+ const key = data && typeof data.api_key === 'string' ? data.api_key.trim() : '';
41
+ if (!key) return { ok: false, key: '' };
42
+ const saved = credentials.saveApiKey(key);
43
+ aegisClient.setApiKey(key);
44
+ return { ok: !!saved.ok, key };
45
+ } catch (err) {
46
+ return { ok: false, key: '', error: err };
47
+ } finally {
48
+ clearTimeout(timer);
49
+ }
50
+ }
51
+
52
+ module.exports = { autoProvisionApiKey, DEVICE_REGISTER_TIMEOUT_MS };
@@ -0,0 +1,113 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * The pooled-brain entry, defined ONCE for every host.
5
+ *
6
+ * The platform's `/api/v1/models` payload lists the brain tier under five
7
+ * spellings (`nexus-brain` canonical; `aegis-brain`, `nexus-brain-smart`,
8
+ * `aegis-brain-smart`, `nexus-brain-neo` each sent as `hidden: true,
9
+ * alias_of: "nexus-brain"`). A host that showed all five painted five models
10
+ * where the server routes one, and a host that showed none (or a different one
11
+ * per release) left users comparing two clients that disagree about the same
12
+ * account.
13
+ *
14
+ * This module exists because that disagreement was real: the desktop collapsed
15
+ * the class to a single "Nexus" entry (desktop/lib/local/engine.js) while the
16
+ * CLI kept every distinct id, so the same account saw a different model list in
17
+ * each host. Two copies of the selection rule is the drift; one shared function
18
+ * is the fix, which is why both hosts require THIS file — the desktop from
19
+ * `desktop/lib/local/engine.js` (repo-relative `client/brain-catalog.js`, or
20
+ * `desktop/vendor/brain-catalog.js` in the packaged app) and the CLI from
21
+ * `cli/src/models.js` (through `src/sharedpaths.js`: repo-relative
22
+ * `client/brain-catalog.js`, or `vendor/client/brain-catalog.js` installed).
23
+ *
24
+ * The two hosts do NOT hand this module the same entry shape and must not have
25
+ * to: the desktop passes the relay's raw payload (`hidden`, `alias_of`), the
26
+ * CLI passes its own normalised entries (`hidden`, `aliasOf`). So the readers
27
+ * below accept either spelling — one rule, two shapes — instead of each host
28
+ * keeping a private copy of the rule to match its own shape, which is the drift
29
+ * this module exists to end.
30
+ *
31
+ * Pure: no I/O, no node builtins, no dependencies — safe to require from a
32
+ * renderer, a CLI start-up path, or an MCP host.
33
+ */
34
+
35
+ /** Every id the server uses for the pooled brain, canonical spelling first. */
36
+ const NEXUS_BRAIN_IDS = Object.freeze(['nexus-brain', 'aegis-brain']);
37
+
38
+ /** The name users see for the collapsed entry. */
39
+ const NEXUS_LABEL = 'Nexus';
40
+
41
+ /**
42
+ * The id this entry is an alias OF, or `null`. Reads the relay's `alias_of` and
43
+ * the CLI's normalised `aliasOf`, so callers may pass either shape.
44
+ */
45
+ function aliasOfEntry(m) {
46
+ if (!m || typeof m !== 'object') return null;
47
+ for (const value of [m.alias_of, m.aliasOf]) {
48
+ if (typeof value === 'string' && value.trim()) return value.trim();
49
+ }
50
+ return null;
51
+ }
52
+
53
+ /** Whether the entry is marked display-hidden, in either shape. */
54
+ function isHiddenEntry(m) {
55
+ return Boolean(m) && m.hidden === true;
56
+ }
57
+
58
+ /**
59
+ * Pick the one entry standing in for the pooled brain. The server serves
60
+ * `nexus-brain` as the canonical tier (`hidden: false`, no `alias_of`) and
61
+ * marks every other spelling — `aegis-brain` and the `-smart`/`-neo` tiers —
62
+ * as `hidden: true, alias_of: "nexus-brain"`. Prefer the canonical id so the
63
+ * request travels on the name the server owns; fall back to the alias, then to
64
+ * any tier whose `alias_of` names the brain, so a renamed or trimmed catalog
65
+ * still resolves to something selectable instead of silently emptying the
66
+ * dropdown (the previous fixed-id lookup returned [] if `aegis-brain` was ever
67
+ * retired, leaving the class with no model to choose).
68
+ *
69
+ * @param {Array<object>} models normalized or raw catalog entries.
70
+ * @returns {object|null}
71
+ */
72
+ function selectBrainEntry(models) {
73
+ const list = Array.isArray(models) ? models.filter(Boolean) : [];
74
+ return (
75
+ list.find((m) => NEXUS_BRAIN_IDS.includes(m.id) && !isHiddenEntry(m) && aliasOfEntry(m) === null)
76
+ || list.find((m) => NEXUS_BRAIN_IDS.includes(m.id))
77
+ || list.find((m) => NEXUS_BRAIN_IDS.includes(aliasOfEntry(m)))
78
+ || null
79
+ );
80
+ }
81
+
82
+ /**
83
+ * The Aegis-class catalog as a host must OFFER it: exactly one entry, the
84
+ * collapsed brain — never the raw provider list, and never the alias tiers.
85
+ *
86
+ * Offering this shape is not the same as accepting only this shape: the ids the
87
+ * server advertises still route (a pin on `deepseek` still runs), so callers
88
+ * keep the full catalog for validation and use this for what they show.
89
+ *
90
+ * Returns `[]` when the payload names no brain tier at all — which is the
91
+ * caller's signal that this is not a pooled-brain catalog (the BYOK listing is
92
+ * per-provider models and must be offered in full, not collapsed to nothing).
93
+ *
94
+ * @param {Array<object>} models the server's catalog (any shape).
95
+ * @returns {Array<object>} `[]` when the payload names no brain tier at all.
96
+ */
97
+ function filterAegisCatalog(models) {
98
+ const nexus = selectBrainEntry(models);
99
+ if (!nexus) return [];
100
+ // Drop the alias bookkeeping in BOTH spellings: this entry *is* the
101
+ // selection, so a renderer must never treat it as a hidden alias and filter
102
+ // it back out — which is exactly what happens if `aliasOf` survives here and
103
+ // the consumer re-runs its own "drop aliases" pass over the result.
104
+ const { hidden, alias_of, aliasOf, ...rest } = nexus;
105
+ return [{ ...rest, label: NEXUS_LABEL }];
106
+ }
107
+
108
+ module.exports = {
109
+ NEXUS_BRAIN_IDS,
110
+ NEXUS_LABEL,
111
+ selectBrainEntry,
112
+ filterAegisCatalog,
113
+ };
@@ -0,0 +1,63 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * A stable per-machine identifier, used ONLY to ask aegis1 for a free device
5
+ * key (`POST /api/v1/auth/register-device`) when no key is configured yet. It
6
+ * is not a credential itself — the endpoint treats it as an idempotency key,
7
+ * so a wiped `~/.aegiscode` still resolves back to the same aegis1 account
8
+ * (and whatever balance it holds) instead of minting a fresh, unfunded one.
9
+ *
10
+ * Derivation mirrors ae-guix's `getMachineFingerprint()` (main.js) so the two
11
+ * hosts don't invent divergent conventions for the same idea: the OS's own
12
+ * machine identity where one exists, hashed with a purpose-specific prefix so
13
+ * it can never collide with a fingerprint minted for another purpose.
14
+ */
15
+ const crypto = require('node:crypto');
16
+ const os = require('node:os');
17
+
18
+ /** Best-effort OS machine identity. Empty string, never throws, if none is reachable. */
19
+ function readMachineId() {
20
+ try {
21
+ if (process.platform === 'linux') {
22
+ const fs = require('node:fs');
23
+ try {
24
+ return fs.readFileSync('/etc/machine-id', 'utf8').trim();
25
+ } catch {
26
+ return fs.readFileSync('/var/lib/dbus/machine-id', 'utf8').trim();
27
+ }
28
+ }
29
+ if (process.platform === 'darwin') {
30
+ const { execSync } = require('node:child_process');
31
+ const out = execSync('ioreg -rd1 -c IOPlatformExpertDevice', {
32
+ encoding: 'utf8',
33
+ timeout: 3000,
34
+ });
35
+ const m = out.match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);
36
+ if (m) return m[1];
37
+ }
38
+ if (process.platform === 'win32') {
39
+ const { execSync } = require('node:child_process');
40
+ const out = execSync('reg query HKLM\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid', {
41
+ encoding: 'utf8',
42
+ timeout: 3000,
43
+ });
44
+ const m = out.match(/MachineGuid\s+REG_SZ\s+(\S+)/);
45
+ if (m) return m[1];
46
+ }
47
+ } catch {
48
+ /* no reachable machine id on this host — the caller falls back below */
49
+ }
50
+ return '';
51
+ }
52
+
53
+ /**
54
+ * sha256("aegiscode-plugin-device-v1:" + machine identity), hex.
55
+ *
56
+ * @param {string} [overrideId] - test-only override for the raw machine identity.
57
+ */
58
+ function machineFingerprint(overrideId) {
59
+ const id = overrideId || readMachineId() || `${os.hostname()}:${os.platform()}:${os.arch()}`;
60
+ return crypto.createHash('sha256').update(`aegiscode-plugin-device-v1:${id}`).digest('hex');
61
+ }
62
+
63
+ module.exports = { machineFingerprint, readMachineId };