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.
package/src/clipboard.js CHANGED
@@ -7,6 +7,10 @@
7
7
  * clipboard availability. Set AEGISCODE_NO_CLIPBOARD=1 to force the file
8
8
  * fallback (used by tests and headless setups).
9
9
  *
10
+ * The tools are resolved with `resolveTrustedTool` rather than by name, and the
11
+ * fallback file is written 0600 with O_NOFOLLOW — see those functions for what
12
+ * each defends against. Set AEGISCODE_TRUST_PATH=0 to opt out of the PATH check.
13
+ *
10
14
  * Ported from the upstream engine reference (ESM → CommonJS). The data dir
11
15
  * comes from the shared `aegisDir()` helper and the force-fallback env var was
12
16
  * renamed AEGISCODEX_NO_CLIPBOARD → AEGISCODE_NO_CLIPBOARD.
@@ -16,6 +20,7 @@ const { spawnSync } = require('node:child_process');
16
20
  const fs = require('node:fs');
17
21
  const path = require('node:path');
18
22
  const { aegisDir } = require('./config.js');
23
+ const { writePrivateFile } = require('./securefs.js');
19
24
 
20
25
  const TOOLS = [
21
26
  { name: 'pbcopy', cmd: 'pbcopy', args: [], test: () => process.platform === 'darwin' },
@@ -25,13 +30,76 @@ const TOOLS = [
25
30
  { name: 'clip', cmd: 'clip', args: [], test: () => process.platform === 'win32' },
26
31
  ];
27
32
 
28
- function toolAvailable(cmd) {
29
- // `sh` doesn't exist on Windows — use `where` there, `command -v` on POSIX.
30
- const isWin = process.platform === 'win32';
31
- const r = isWin
32
- ? spawnSync('where', [cmd], { encoding: 'utf8', timeout: 3000, windowsHide: true })
33
- : spawnSync('sh', ['-c', `command -v ${cmd}`], { encoding: 'utf8', timeout: 3000 });
34
- return !r.error && r.status === 0;
33
+ /**
34
+ * Is `dir` a directory a second local account could write into?
35
+ *
36
+ * This is the whole check behind the PATH hardening below. A clipboard tool is
37
+ * handed the complete text of whatever the user copied — which in this CLI is
38
+ * usually model output, sometimes containing code, paths, or a secret the user
39
+ * was about to paste into a browser. `spawnSync('wl-copy', …)` resolves that
40
+ * name against `$PATH`, so whoever owns an earlier PATH entry than the real
41
+ * binary owns every byte the user copies: drop a `wl-copy` in a group-writable
42
+ * `~/.local/bin`, or rely on `/tmp` or `.` being in PATH, and the text arrives
43
+ * at the attacker instead of the clipboard.
44
+ *
45
+ * A directory is trusted only when it is not group- or world-writable AND is
46
+ * owned by root or by us. `/tmp` fails on the first test; `~/bin` that the user
47
+ * owns and left at 0755 passes.
48
+ */
49
+ function dirIsTrusted(dir) {
50
+ try {
51
+ const st = fs.statSync(dir);
52
+ if (!st.isDirectory()) return false;
53
+ if (st.mode & 0o022) return false;
54
+ if (typeof process.getuid === 'function' && st.uid !== 0 && st.uid !== process.getuid()) return false;
55
+ return true;
56
+ } catch {
57
+ return false;
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Resolve `cmd` to an absolute path we are willing to execute, or null.
63
+ *
64
+ * Replaces the old `sh -c 'command -v <cmd>'` availability probe: that check
65
+ * answered "is this name on PATH?" when the question that matters is "is the
66
+ * binary PATH would pick one I trust?". Answering the second subsumes the
67
+ * first, and does it without a shell in the loop.
68
+ *
69
+ * Every candidate must survive: a PATH entry that is absolute, trusted, and not
70
+ * the empty string or `.` (both of which mean the current directory); a real
71
+ * file that is executable, not group/world-writable, and owned by root or us;
72
+ * and a realpath whose own directory is trusted too, so a link in a good
73
+ * directory cannot redirect execution into a bad one.
74
+ */
75
+ function resolveTrustedTool(cmd) {
76
+ const entries = String(process.env.PATH || '').split(path.delimiter);
77
+ for (const raw of entries) {
78
+ const dir = String(raw).trim();
79
+ if (!dir || !path.isAbsolute(dir)) continue; // '' and '.' mean "the cwd"
80
+ if (!dirIsTrusted(dir)) continue;
81
+
82
+ const full = path.join(dir, cmd);
83
+ let real;
84
+ try {
85
+ real = fs.realpathSync(full); // throws on ENOENT and on a symlink loop
86
+ } catch {
87
+ continue;
88
+ }
89
+ let st;
90
+ try {
91
+ st = fs.statSync(real);
92
+ } catch {
93
+ continue;
94
+ }
95
+ if (!st.isFile()) continue;
96
+ if (!(st.mode & 0o111)) continue; // not executable
97
+ if (st.mode & 0o022) continue; // group/world-writable binary
98
+ if (typeof process.getuid === 'function' && st.uid !== 0 && st.uid !== process.getuid()) continue;
99
+ if (!dirIsTrusted(path.dirname(real))) continue; // the realpath may leave `dir`
100
+ return real;
101
+ }
102
+ return null;
35
103
  }
36
104
 
37
105
  /**
@@ -40,23 +108,31 @@ function toolAvailable(cmd) {
40
108
  */
41
109
  function copyToClipboard(text) {
42
110
  const forced = process.env.AEGISCODE_NO_CLIPBOARD === '1';
111
+ // AEGISCODE_TRUST_PATH=0 restores the old "whatever PATH resolves" behaviour
112
+ // for a user whose tool legitimately lives in a group-writable prefix (an
113
+ // unusual but real layout). Secure by default; the hatch is documented in the
114
+ // module header rather than being the default.
115
+ const trustPath = process.env.AEGISCODE_TRUST_PATH !== '0';
43
116
  if (!forced) {
44
117
  for (const t of TOOLS) {
45
118
  if (!t.test()) continue;
46
- if (!toolAvailable(t.cmd)) continue;
47
- const r = spawnSync(t.cmd, t.args, { input: String(text), encoding: 'utf8', timeout: 4000 });
119
+ const exe = trustPath ? resolveTrustedTool(t.cmd) : t.cmd;
120
+ if (!exe) continue; // not installed, or installed somewhere untrusted
121
+ const r = spawnSync(exe, t.args, { input: String(text), encoding: 'utf8', timeout: 4000 });
48
122
  if (!r.error && r.status === 0) return { ok: true, via: `tool:${t.name}` };
49
123
  }
50
124
  }
51
- // Fallback: write to the data dir and report the path.
125
+ // Fallback: write to the data dir and report the path. 0600 + O_NOFOLLOW via
126
+ // securefs — this file holds whatever the user last marked, and neither the
127
+ // mode nor a planted symlink may let it double as a way to read or overwrite
128
+ // something else.
52
129
  try {
53
- fs.mkdirSync(aegisDir(), { recursive: true });
54
130
  const p = path.join(aegisDir(), 'clipboard.txt');
55
- fs.writeFileSync(p, String(text), 'utf8');
131
+ writePrivateFile(p, String(text), { atomic: false });
56
132
  return { ok: true, via: 'file', path: p };
57
133
  } catch {
58
134
  return { ok: false, via: 'none' };
59
135
  }
60
136
  }
61
137
 
62
- module.exports = { copyToClipboard };
138
+ module.exports = { copyToClipboard, resolveTrustedTool: resolveTrustedTool };
package/src/commands.js CHANGED
@@ -52,9 +52,10 @@ const panels = require('./panels.js');
52
52
  const overlays = require('./overlays.js');
53
53
  const {
54
54
  updateConfig, loadConfig, loadPermissions, savePermissions, addPermissionRule,
55
- DEFAULT_PERMISSIONS, permissionsPath, configPath,
55
+ DEFAULT_PERMISSIONS, permissionsPath, configPath, aegisDir,
56
56
  memoryPersistState, setMemoryPersist,
57
57
  } = require('./config.js');
58
+ const { auditExposure, repairExposure } = require('./securefs.js');
58
59
  const { copyToClipboard } = require('./clipboard.js');
59
60
  const { snapshotCheckpoint, listCheckpoints, loadCheckpoint } = require('./checkpoint.js');
60
61
  const { signupUrl, goUrl } = require('./signup.js');
@@ -1251,9 +1252,15 @@ const COMMANDS = [
1251
1252
  },
1252
1253
  },
1253
1254
  {
1254
- name: 'doctor', hint: '', category: 'support',
1255
+ name: 'doctor', args: ['action'], hint: '[fix]', category: 'support',
1255
1256
  desc: 'Run diagnostic checks on this environment',
1256
- handler: async (c) => {
1257
+ handler: async (c, args) => {
1258
+ const action = ((args && args.action) || '').toLowerCase();
1259
+ if (action && action !== 'fix') {
1260
+ note(c, 'Usage: /doctor [fix] — "fix" re-tightens the data dir to 0700/0600');
1261
+ c.render();
1262
+ return true;
1263
+ }
1257
1264
  const checks = [];
1258
1265
  const ok = (label, good, detail) => checks.push([good, label, detail]);
1259
1266
  ok('Node', true, process.version);
@@ -1275,6 +1282,43 @@ const COMMANDS = [
1275
1282
  ok('plaintext key', false, `a copy also sits in ${configPath()} (another AEGIS CLI) — /key re-saves it to ${ks.path}`);
1276
1283
  }
1277
1284
  ok('config path', true, configPath());
1285
+ // The store sits at 0775/0664 on any install older than securefs.js —
1286
+ // every file that has not happened to be rewritten since. Report that
1287
+ // always, but repair only when asked: a diagnostic that silently rewrites
1288
+ // the user's directory is a surprise, not a fix.
1289
+ const dataDir = aegisDir();
1290
+ let repaired = null;
1291
+ if (action === 'fix') repaired = repairExposure(dataDir);
1292
+ const audit = auditExposure(dataDir);
1293
+ if (!audit.exists) {
1294
+ ok('data dir', true, `${dataDir} (not created yet)`);
1295
+ } else {
1296
+ const shown = audit.exposed.slice(0, 4).map((e) => `${e.rel} ${e.mode}`).join(', ');
1297
+ ok(
1298
+ 'data dir',
1299
+ audit.exposed.length === 0,
1300
+ audit.exposed.length === 0
1301
+ ? `${dataDir} (${audit.rootMode}, all private)`
1302
+ : `${dataDir} (${audit.rootMode}) — ${audit.exposed.length} path(s) group/world-accessible: ` +
1303
+ `${shown}${audit.exposed.length > 4 ? ', …' : ''} — run /doctor fix`
1304
+ );
1305
+ }
1306
+ if (repaired) {
1307
+ const sample = repaired.fixed
1308
+ .slice(0, 3)
1309
+ .map((f) => `${f.rel} ${f.from}→${f.to}`)
1310
+ .join(', ');
1311
+ ok(
1312
+ 'repair',
1313
+ repaired.remaining.length === 0,
1314
+ repaired.remaining.length === 0
1315
+ ? repaired.fixed.length
1316
+ ? `tightened ${repaired.fixed.length} path(s) — ${sample}${repaired.fixed.length > 3 ? ', …' : ''}`
1317
+ : 'already private, nothing to tighten'
1318
+ : `${repaired.remaining.length} path(s) still exposed — ` +
1319
+ repaired.failed.map((f) => `${f.rel}: ${f.reason}`).join(', ')
1320
+ );
1321
+ }
1278
1322
  const lines = [[span(C.gold + BOLD, 'Doctor'), span(BOLD_OFF, '')], [span(C.gray, '─'.repeat(30))]];
1279
1323
  for (const [good, label, detail] of checks) {
1280
1324
  lines.push([
package/src/config.js CHANGED
@@ -14,6 +14,7 @@
14
14
 
15
15
  const fs = require('node:fs');
16
16
  const path = require('node:path');
17
+ const { writePrivateFile } = require('./securefs.js');
17
18
 
18
19
  // The data dir is defined once, in the shared credential module, because the
19
20
  // desktop app and the MCP plugin now read and write the same store: a second
@@ -181,11 +182,10 @@ function loadConfig() {
181
182
  function updateConfig(patch) {
182
183
  const next = { ...loadConfig(), ...patch };
183
184
  try {
184
- fs.mkdirSync(aegisDir(), { recursive: true });
185
- // Write atomically-ish: tmp file + rename so a crash can't corrupt it.
186
- const tmp = configPath() + '.tmp';
187
- fs.writeFileSync(tmp, JSON.stringify(next, null, 2) + '\n');
188
- fs.renameSync(tmp, configPath());
185
+ // Atomic (tmp + rename) so a crash can't corrupt it, and written 0600:
186
+ // config.json carries `provider` and `baseURL`, so a group-writable copy is
187
+ // a way for another local account to repoint the session's endpoint.
188
+ writePrivateFile(configPath(), JSON.stringify(next, null, 2) + '\n');
189
189
  } catch (e) {
190
190
  if (process.env.AEGIS_HIST_DEBUG) console.error('[config] write failed:', e);
191
191
  }
@@ -229,10 +229,9 @@ function loadPermissions() {
229
229
  /** Persist permission rules. Returns the saved rules (or the input on failure). */
230
230
  function savePermissions(rules) {
231
231
  try {
232
- fs.mkdirSync(aegisDir(), { recursive: true });
233
- const tmp = permissionsPath() + '.tmp';
234
- fs.writeFileSync(tmp, JSON.stringify(rules, null, 2) + '\n');
235
- fs.renameSync(tmp, permissionsPath());
232
+ // 0600: the rules decide which tools run without a prompt, so a writable
233
+ // copy is a way to pre-approve the next session's tool calls.
234
+ writePrivateFile(permissionsPath(), JSON.stringify(rules, null, 2) + '\n');
236
235
  } catch (e) {
237
236
  if (process.env.AEGIS_HIST_DEBUG) console.error('[permissions] write failed:', e);
238
237
  }
package/src/deps.js CHANGED
@@ -63,6 +63,10 @@ const updatePath = resolveShared(path.join('client', 'update.js'));
63
63
  // must work the SAME queue with the SAME rules (scoped commits included).
64
64
  const queuePath = resolveShared(path.join('desktop', 'lib', 'local', 'queue.js'));
65
65
  const autonomousPath = resolveShared(path.join('desktop', 'lib', 'local', 'autonomous.js'));
66
+ // Auto-provision a free device key when no key is configured anywhere — same
67
+ // module the MCP plugin and the desktop app use, so all three ask aegis1 for
68
+ // the same account on the same machine, with the same timeout.
69
+ const autoProvisionPath = resolveShared(path.join('client', 'auto-provision.js'));
66
70
 
67
71
  const { createClient } = require(clientPath);
68
72
  const { createTools } = require(toolsPath);
@@ -74,6 +78,7 @@ const { buildSystemPrompt } = require(promptPath);
74
78
  const updater = require(updatePath);
75
79
  const queue = require(queuePath);
76
80
  const autonomous = require(autonomousPath);
81
+ const { autoProvisionApiKey } = require(autoProvisionPath);
77
82
 
78
83
  module.exports = {
79
84
  resolveShared,
@@ -90,6 +95,7 @@ module.exports = {
90
95
  updater,
91
96
  queue,
92
97
  autonomous,
93
- paths: { client: clientPath, tools: toolsPath, usage: usagePath, engine: enginePath, settings: settingsPath, agents: agentsPath, prompt: promptPath, update: updatePath, queue: queuePath, autonomous: autonomousPath },
98
+ autoProvisionApiKey,
99
+ paths: { client: clientPath, tools: toolsPath, usage: usagePath, engine: enginePath, settings: settingsPath, agents: agentsPath, prompt: promptPath, update: updatePath, queue: queuePath, autonomous: autonomousPath, autoProvision: autoProvisionPath },
94
100
  roots,
95
101
  };
package/src/diffview.js CHANGED
@@ -142,12 +142,14 @@ function defaultOpen(preview) {
142
142
  }
143
143
 
144
144
  /**
145
- * The summary row: ` ⎿ Update(src/diff.js) +12 -3 · click to view diff`.
145
+ * The summary row: ` ⎿ Update(src/diff.js) +12 -3 · click to view diff`.
146
146
  *
147
147
  * @param {object} preview From diff.js's editPreview().
148
148
  * @param {object} ctx App context (selects the light/dark diff palette).
149
+ * @param {{open?: boolean}} [opts] Whether the block is expanded — flips the
150
+ * hint to "click to collapse", the way the click gesture will read next.
149
151
  */
150
- function diffSummaryRow(preview, ctx) {
152
+ function diffSummaryRow(preview, ctx, opts = {}) {
151
153
  const t = themeOf(ctx);
152
154
  const D = diffOf(ctx);
153
155
  const bits = [` ${t.gray}${GLYPH.hook} ${RESET}`];
@@ -156,6 +158,11 @@ function diffSummaryRow(preview, ctx) {
156
158
  if (preview.dels) bits.push(`${D.delFg} -${preview.dels}${RESET}`);
157
159
  if (!preview.adds && !preview.dels) bits.push(`${t.gray} no line changes${RESET}`);
158
160
  if (preview.misses) bits.push(`${t.gold} ${preview.misses} edit(s) not applied${RESET}`);
161
+ // The affordance, and the only thing that tells the reader this row is
162
+ // clickable — chatflow's clickHits map keys the row painted here. It also
163
+ // mirrors aegiscodex-dev's diffSummaryRow(), which emits the same hint, so
164
+ // the two hosts advertise the same gesture in the same words.
165
+ bits.push(`${DIM} · ${opts.open ? 'click to collapse' : 'click to view diff'}${RESET}`);
159
166
  return bits.join('');
160
167
  }
161
168
 
@@ -175,7 +182,7 @@ function renderDiffBlock(preview, ctx, cols, opts = {}) {
175
182
  const width = Math.max(8, Number(cols) || 80);
176
183
  const D = diffOf(ctx);
177
184
  const t = themeOf(ctx);
178
- const out = [clipRow(diffSummaryRow(preview, ctx), width)];
185
+ const out = [clipRow(diffSummaryRow(preview, ctx, { open: opts.open }), width)];
179
186
  if (!opts.open || !preview || !preview.rows || !preview.rows.length) return out;
180
187
 
181
188
  const rows = markIntraLine(preview.rows.slice(0, MAX_BLOCK_ROWS).map((r) => Object.assign({}, r)));
package/src/events.js CHANGED
@@ -25,6 +25,14 @@ const { decodeEscSequence, decodePlain, KEY } = require('./keys.js');
25
25
 
26
26
  const queue = [];
27
27
  let waiting = [];
28
+
29
+ /**
30
+ * Handed to every parked `nextKey()` waiter when the pump is reset, so a
31
+ * consumer can tell "the stream went away" from "the user pressed nothing".
32
+ * Without it the only way to unblock a waiter is a real keypress, which means a
33
+ * session whose loop is parked on a bare `nextKey()` cannot be stopped at all.
34
+ */
35
+ const STREAM_END = Symbol('aegis.streamEnd');
28
36
  let buffer = '';
29
37
  let seq = '';
30
38
  let escTimer = null;
@@ -261,7 +269,9 @@ function nextKeyTimeout(ms) {
261
269
  }, ms);
262
270
  const wrapper = (key) => {
263
271
  clearTimeout(timer);
264
- resolve(key);
272
+ // A pump reset resolves null, exactly like the timeout path: this call's
273
+ // contract is "a key or null", and STREAM_END is not a key.
274
+ resolve(key === STREAM_END ? null : key);
265
275
  };
266
276
  waiting.push(wrapper);
267
277
  });
@@ -316,7 +326,22 @@ function resetKeyStream() {
316
326
  buffer = '';
317
327
  pasteChunks = [];
318
328
  drainQueue();
329
+ // Resolve — do NOT merely drop — the parked waiters. `waiting = []` on its own
330
+ // leaves every loop sitting on a bare nextKey() parked forever: nothing can
331
+ // ever wake it, so any consumer that leaks the pump becomes unkillable and
332
+ // keeps painting into the stdout it captured. Handing each waiter STREAM_END
333
+ // lets its loop observe the teardown and break. A leaked session's keystrokes
334
+ // also stop landing in the next session's queue, because the queue is cleared
335
+ // here and the stale waiter is gone rather than still attached to it.
336
+ const parked = waiting;
319
337
  waiting = [];
338
+ for (const w of parked) {
339
+ try {
340
+ w(STREAM_END);
341
+ } catch {
342
+ /* waiter already settled */
343
+ }
344
+ }
320
345
  attachedStdin = null;
321
346
  onData = null;
322
347
  suspended = false;
@@ -324,6 +349,7 @@ function resetKeyStream() {
324
349
 
325
350
  module.exports = {
326
351
  KEY,
352
+ STREAM_END,
327
353
  // Exported for `test/cli-marking.test.mjs`: the click/drag/release split is
328
354
  // the half of the marking gesture that is pure decoding, and it is the half
329
355
  // that regressed silently once already (only left presses were named, so a
package/src/history.js CHANGED
@@ -24,6 +24,7 @@ const fs = require('node:fs');
24
24
  const os = require('node:os');
25
25
  const path = require('node:path');
26
26
  const { aegisDir } = require('./config.js');
27
+ const { ensurePrivateDir, writePrivateFile } = require('./securefs.js');
27
28
  const { sessionStore } = require('./shared.js');
28
29
  const { estimateTokens } = require('./tokens.js');
29
30
 
@@ -36,7 +37,7 @@ function historyPath() {
36
37
  }
37
38
 
38
39
  function ensureHistoryDir() {
39
- fs.mkdirSync(path.dirname(historyPath()), { recursive: true });
40
+ ensurePrivateDir(path.dirname(historyPath()));
40
41
  }
41
42
 
42
43
  /**
@@ -95,7 +96,8 @@ function appendHistoryEntries(entries) {
95
96
  const prev = fs.existsSync(p) ? fs.readFileSync(p, 'utf8').split('\n').filter(Boolean) : [];
96
97
  const lines = [...prev, ...list.map((e) => JSON.stringify(e))];
97
98
  const trimmed = lines.slice(Math.max(0, lines.length - HISTORY_LIMIT));
98
- fs.writeFileSync(p, trimmed.join('\n') + '\n');
99
+ // 0600: this file is every prompt and reply the session has ever had.
100
+ writePrivateFile(p, trimmed.join('\n') + '\n');
99
101
  mirrorToSharedStore(list);
100
102
  return list.length;
101
103
  } catch (e) {
@@ -227,7 +229,7 @@ function pruneSessionHistory(sessionId) {
227
229
  .filter((l) => {
228
230
  try { return JSON.parse(l).sessionId !== sessionId; } catch { return true; }
229
231
  });
230
- fs.writeFileSync(p, kept.length ? kept.join('\n') + '\n' : '');
232
+ writePrivateFile(p, kept.length ? kept.join('\n') + '\n' : '');
231
233
  } catch (e) {
232
234
  if (process.env.AEGIS_HIST_DEBUG) console.error('[history] prune failed:', e);
233
235
  }
package/src/models.js CHANGED
@@ -12,16 +12,38 @@
12
12
  * would silently route somewhere else.
13
13
  *
14
14
  * The platform lists per-provider ids (`deepseek`, `anthropic`, `groq`, …) plus
15
- * the pooled-brain tiers. The desktop host collapsed all of that to a single
16
- * "Nexus" entry because its dropdown *is* the model choice and surfacing
17
- * per-provider routing invites pinning a provider that happens to be dead right
18
- * now (see desktop/lib/local/engine.js selectBrainEntry). This host keeps every
19
- * distinct id — a CLI user pinning `deepseek` explicitly is a legitimate
20
- * request — but drops the pure-alias duplicates the server itself marks
21
- * `hidden: true, alias_of: "<id>"` (`aegis-brain`, `nexus-brain-smart`, …),
22
- * which are the same model advertised under another spelling.
15
+ * the pooled-brain tiers. What this host OFFERS for the pooled class is the
16
+ * same single collapsed "Nexus" entry the desktop offers, and it is now the
17
+ * same *code* that decides it: `client/brain-catalog.js`, required through
18
+ * `src/sharedpaths.js` so a checkout and an installed package resolve it the
19
+ * same way. Offering one entry is not accepting one entry — the server's ids
20
+ * stay pinnable (`/model deepseek` still validates against the full catalog
21
+ * through `findModel`/`catalogIds`), which is why the collapse lives here in
22
+ * what we *show* rather than in what we *normalise*.
23
+ *
24
+ * This host used to keep every distinct id, on the argument that a CLI user
25
+ * pinning `deepseek` explicitly is a legitimate request. It is — but that is
26
+ * an argument about accepting ids, and it was implemented as an argument about
27
+ * displaying them, so the same account saw seven models in the terminal and one
28
+ * in the GUI. The two hosts disagreeing about one account was the actual bug.
29
+ *
30
+ * A payload with no brain tier at all (the BYOK listing, which is per-provider
31
+ * models) is not collapsed: `filterAegisCatalog` returns `[]` for it, and this
32
+ * module then offers every distinct entry exactly as before.
23
33
  */
24
34
 
35
+ const path = require('node:path');
36
+
37
+ const { resolveShared } = require('./sharedpaths.js');
38
+
39
+ /**
40
+ * The shared selection rule — required at load time and by EXISTENCE, never
41
+ * with a fallback copy here: a silently divergent local implementation is the
42
+ * precise defect this file was changed to remove. A missing module is a loud
43
+ * error naming the file, which is what `resolveShared` throws.
44
+ */
45
+ const { filterAegisCatalog } = require(resolveShared(path.join('client', 'brain-catalog.js')));
46
+
25
47
  /** A pinned id of `null` means "no pin — let the pool choose" (the server's own default). */
26
48
  const NO_PIN = null;
27
49
 
@@ -88,13 +110,25 @@ function normalizeModelCatalog(raw) {
88
110
  }
89
111
 
90
112
  /**
91
- * The entries the picker and `/models` offer: every distinct advertised model,
92
- * minus the alias duplicates — unless the catalog is *only* aliases, in which
93
- * case the aliases are all the server advertises and are offered rather than
94
- * leaving the user with an empty list.
113
+ * The entries the picker and `/models` offer.
114
+ *
115
+ * Pooled class: exactly one entry, the collapsed brain, decided by the shared
116
+ * rule (`client/brain-catalog.js`) so the terminal and the GUI cannot offer the
117
+ * same account two different lists. The collapsed entry is re-normalised here
118
+ * so renderers keep the `label`/`note` columns they already expect, and so the
119
+ * brain's cost shape ("multi-call fan-out, sized by /effort") still reaches the
120
+ * picker's right-hand column.
121
+ *
122
+ * BYOK class: no brain tier is present, `filterAegisCatalog` reports that with
123
+ * `[]`, and every distinct advertised model is offered — minus the server's own
124
+ * alias duplicates, unless the catalog is *only* aliases, in which case the
125
+ * aliases are all the server advertises and are offered rather than leaving the
126
+ * user with an empty list.
95
127
  */
96
128
  function pickerEntries(catalog) {
97
129
  const all = Array.isArray(catalog) ? catalog.filter(Boolean) : [];
130
+ const collapsed = filterAegisCatalog(all).map(normalizeModel).filter(Boolean);
131
+ if (collapsed.length) return collapsed;
98
132
  const distinct = all.filter((m) => !m.aliasOf);
99
133
  return distinct.length ? distinct : all;
100
134
  }