aegiscode 6.8.36 → 7.0.0

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/screens.js CHANGED
@@ -91,7 +91,15 @@ const WHATS_NEW = [
91
91
  * the Tips/What's-new pair already come to 21 of the 23 usable rows, so a
92
92
  * boxed third panel (three rows minimum, two of them rules) would push the
93
93
  * footer hint off the bottom of the commonest terminal there is. Two rows fit
94
- * exactly, one route each, and the desktop line shares the second.
94
+ * exactly: one route row, and the desktop line under it.
95
+ *
96
+ * WHICH route row is the part that matters, and it is composed by
97
+ * `connectRows()` below rather than being a constant, because the two routes
98
+ * have separate gates. They used to share a single one that short-circuited on
99
+ * the account key, so the `/byok-key` row disappeared the moment a user
100
+ * redeemed an AEGIS key — see `byokRouteNeeded()`. Holding the block to two
101
+ * rows is why the both-owed case merges the routes into one row again: at
102
+ * 80×24 a third row is the footer hint.
95
103
  *
96
104
  * Both commands named here are real registry entries — `/byok-key` saves a
97
105
  * provider key, `/key` saves the AEGIS account key — and the URL is the shared
@@ -100,20 +108,65 @@ const WHATS_NEW = [
100
108
  * which the bare `aegiscloud.org` this row used to print did not. Nothing here
101
109
  * is a URL or a command that only exists in this comment.
102
110
  */
103
- const CONNECT = [
111
+ const CONNECT_BYOK = [
112
+ 'Your own provider key: /byok-key <provider> — works with your AEGIS key',
113
+ ];
114
+
115
+ // The AEGIS Cloud route. The URL in the desktop row below is the shared signup
116
+ // deep link from signup.js, not a hand-written one: it lands on the register
117
+ // panel with the key page queued behind it and the channel attached, which the
118
+ // bare `aegiscloud.org` that row used to print did not.
119
+ //
120
+ // The scheme-less form, and this is the only link in the CLI that uses it. The
121
+ // row's copy spends 45 of the 75 cells `wrapped()` allows at 80 columns
122
+ // (cols - 4 - indent), so `https://aegiscloud.org/key?s=cli` makes the row 77
123
+ // and wraps — a line the 80x24 screen does not have, because the connect
124
+ // block sits on row 21 of 23 and the row it pushes out is the footer hint.
125
+ // `s=cli` is the parameter that files the signup, so it is the scheme that
126
+ // goes, not the channel: see signup.js `signupDisplayUrl()`. Editing this copy
127
+ // means re-measuring; test/cli-onboarding.test.mjs fails on the row count if
128
+ // the row grows past the budget, and names the row that caused it.
129
+ const CONNECT_CLOUD = [
130
+ 'AEGIS Cloud, one account key: /key — no provider signup',
131
+ ];
132
+
133
+ // Both routes still owed (a fresh install): one row naming both, the original
134
+ // copy. Two rows is the whole budget, so this is not a third line — see the
135
+ // block comment above.
136
+ const CONNECT_BOTH = [
104
137
  'Your key, your bill: /byok-key <provider> — or AEGIS Cloud, /key',
105
- // The scheme-less form, and this is the only link in the CLI that uses it.
106
- // The row's copy spends 45 of the 75 cells `wrapped()` allows at 80 columns
107
- // (cols - 4 - indent), so `https://aegiscloud.org/key?s=cli` makes the row 77
108
- // and wraps — a line the 80x24 screen does not have, because the connect
109
- // block sits on row 21 of 23 and the row it pushes out is the footer hint.
110
- // `s=cli` is the parameter that files the signup, so it is the scheme that
111
- // goes, not the channel: see signup.js `signupDisplayUrl()`. Editing this copy
112
- // means re-measuring; test/cli-onboarding.test.mjs fails on the row count if
113
- // the row grows past the budget, and names the row that caused it.
138
+ ];
139
+
140
+ const CONNECT_DESKTOP = [
114
141
  `AEGIS Desktop: same engine on your machine — ${signupDisplayUrl()}`,
115
142
  ];
116
143
 
144
+ /**
145
+ * The connect rows to draw, in order, for the machine as it stands now.
146
+ *
147
+ * `[]` means nothing to say — both routes are configured — and the caller then
148
+ * draws no block at all. Otherwise: one route row (both-owed merges into a
149
+ * single row, the 80×24 budget above, and the desktop pointer always shares
150
+ * the block with it).
151
+ *
152
+ * The gates are independent on purpose. An AEGIS key does not cancel the
153
+ * `/byok-key` row and a provider route does not cancel the `/key` row: the two
154
+ * are not alternatives, they are two ways in, and the row a user has already
155
+ * taken is the only one that may be dropped.
156
+ */
157
+ function connectRows() {
158
+ const rows = [];
159
+ const byok = byokRouteNeeded();
160
+ const cloud = cloudRouteNeeded();
161
+ if (byok && cloud) rows.push(...CONNECT_BOTH);
162
+ else if (byok) rows.push(...CONNECT_BYOK);
163
+ else if (cloud) rows.push(...CONNECT_CLOUD);
164
+ // The desktop pointer is not a route, so it is not gated on one: whenever the
165
+ // block is drawn at all, the "why would I want the app" answer is in it.
166
+ if (rows.length) rows.push(...CONNECT_DESKTOP);
167
+ return rows;
168
+ }
169
+
117
170
  /** Centre a plain string, returning one span line. Clip first, or a string
118
171
  * wider than the terminal produces a row that wraps and shears the frame. */
119
172
  function centered(text, cols, style) {
@@ -354,13 +407,14 @@ function welcomeLines(ctx, cols, rows, firstRun = true) {
354
407
 
355
408
  lines.push(...boxes(t, cols, rows - lines.length - 4));
356
409
  lines.push([span('', '')]);
357
- // The connect block, before the footer hint and only while the machine
358
- // holds no account key. `wrapped` splits rather than clips, so a narrow
359
- // terminal gets four short rows instead of two sheared ones; the height
360
- // budget is unaffected at 80×24, where each line still fits on one row.
361
- if (connectNeeded()) {
362
- for (const text of CONNECT) lines.push(...wrapped(text, cols, t.white, 1));
363
- }
410
+ // The connect block, before the footer hint. The rows are composed by
411
+ // `connectRows()` — the two routes gate SEPARATELY, so an AEGIS-key holder
412
+ // with no provider route of their own is still told `/byok-key` exists,
413
+ // which is the whole point: holding an account key is not a reason to hide
414
+ // the bring-your-own-key route. `wrapped` splits rather than clips, so a
415
+ // narrow terminal gets short rows instead of sheared ones; the height budget
416
+ // is unaffected at 80×24, where each row still fits on one line.
417
+ for (const text of connectRows()) lines.push(...wrapped(text, cols, t.white, 1));
364
418
  lines.push([span(t.gray, GLYPH.hint), span(t.white, ' Try "write a test for <filepath>"')]);
365
419
  while (lines.length < rows - 1) lines.push([span('', '')]);
366
420
  return lines;
@@ -492,12 +546,14 @@ function providerRouteConfigured() {
492
546
  }
493
547
 
494
548
  /**
495
- * Whether the welcome screen should still pitch the two connect routes.
549
+ * Whether ANY part of the connect block is still owed to this machine.
496
550
  *
497
- * Once an AEGIS account key is on this machine, or a BYOK provider route is
498
- * configured, the user has already taken one of them, and two rows repeating
499
- * what they just did is nagging, not onboarding — the same rule the desktop
500
- * host applies to its welcome panel.
551
+ * It is the OR of the two route gates, and it is deliberately not the thing
552
+ * `welcomeLines` branches on any more: the rows are composed one at a time by
553
+ * `connectRows()`, so a machine that holds an AEGIS account key and no
554
+ * provider route still gets the `/byok-key` row. This helper is the coarse
555
+ * question ("is there anything left to say") — a caller that wants the rows
556
+ * should ask `connectRows()` instead.
501
557
  *
502
558
  * A read that fails (no credentials file, an unreadable one) resolves to
503
559
  * "show it": the block is exactly what a user with no key needs, and a
@@ -506,7 +562,38 @@ function providerRouteConfigured() {
506
562
  */
507
563
  function connectNeeded() {
508
564
  try {
509
- if (providerRouteConfigured()) return false;
565
+ return byokRouteNeeded() || cloudRouteNeeded();
566
+ } catch {
567
+ return true;
568
+ }
569
+ }
570
+
571
+ /**
572
+ * The two halves of the connect block, gated SEPARATELY — this is the fix.
573
+ *
574
+ * They used to share one gate that short-circuited on the account key, so a
575
+ * user who redeemed an AEGIS key was never told BYOK exists at all: the row
576
+ * naming `/byok-key` was retired at the exact moment they had an account and
577
+ * were most likely to want a provider route of their own (unlimited/no relay
578
+ * billing, a model the pool does not carry). An account key and a provider
579
+ * route are not alternatives — `/byok-key` works alongside one — so the BYOK
580
+ * row is now gated on the BYOK route alone and an AEGIS-key holder still
581
+ * reads it. The Cloud row keeps the old account-key gate, because that is the
582
+ * thing it pitches.
583
+ *
584
+ * Both reads fail toward SHOWING the row: a failed status read must never be
585
+ * the reason a new install is told nothing about how to start.
586
+ */
587
+ function byokRouteNeeded() {
588
+ try {
589
+ return !providerRouteConfigured();
590
+ } catch {
591
+ return true;
592
+ }
593
+ }
594
+
595
+ function cloudRouteNeeded() {
596
+ try {
510
597
  return !credentials.keyStatus().configured;
511
598
  } catch {
512
599
  return true;
@@ -754,8 +841,14 @@ module.exports = {
754
841
  PRODUCT,
755
842
  TIPS,
756
843
  WHATS_NEW,
757
- CONNECT,
844
+ CONNECT_BYOK,
845
+ CONNECT_CLOUD,
846
+ CONNECT_BOTH,
847
+ CONNECT_DESKTOP,
848
+ connectRows,
758
849
  connectNeeded,
850
+ byokRouteNeeded,
851
+ cloudRouteNeeded,
759
852
  providerRouteConfigured,
760
853
  trustLines,
761
854
  themePickerLines,
@@ -1440,7 +1440,29 @@ function createClient(opts = {}) {
1440
1440
  .sort((a, b) => a[0] - b[0])
1441
1441
  .map(([idx, c]) => ({ ...c, id: c.id || `call_${idx}` }));
1442
1442
 
1443
+ // The hidden chain-of-thought belongs on the RESULT, not only on the live
1444
+ // stream. `reasoningText` above is accumulated and forwarded to the caller's
1445
+ // `onReasoning`/`onStream` so the thinking can be shown while it happens —
1446
+ // but the resolved result carried only `content`, so every down-stream
1447
+ // diagnosis of "the model spent the whole budget thinking and never wrote a
1448
+ // word" read an empty reasoning channel on THIS lane and concluded there had
1449
+ // been no thinking at all.
1450
+ //
1451
+ // That is not a cosmetic loss. desktop/lib/local/engine.js decides its
1452
+ // reasoning-only recovery from exactly this field (`reasonedButSilent` →
1453
+ // `reasoningTextOf(res)`), so on byok the gate was dead code: DeepSeek
1454
+ // returns `finish_reason: 'stop'` with empty content and a full
1455
+ // `reasoning_content`, which matched neither `isTruncated` (the reason says
1456
+ // 'stop', not 'length') nor the reasoning retry (nothing to detect), and the
1457
+ // turn fell straight through to emptyTurnError — the "backend error: the
1458
+ // model returned no answer … max_tokens 16384" the user sees. Measured live
1459
+ // on byok/deepseek-v4-flash 2026-10-11.
1460
+ //
1461
+ // Kept out of `content` on purpose: deliberation is not an answer, and
1462
+ // folding it in would make a no-answer turn look answered to every caller's
1463
+ // empty-check (see the note at the `reasoningText` accumulation above).
1443
1464
  const message = { content: cleanText };
1465
+ if (reasoningText) message.reasoning_content = reasoningText;
1444
1466
  if (toolCalls.length) message.tool_calls = toolCalls;
1445
1467
  const result = {
1446
1468
  model: resultModel,
@@ -95,14 +95,49 @@ const BYOK_MODEL_ADDITIONS = Object.freeze({
95
95
  // catalog.py) pins exactly one default_model, `claude-sonnet-5`, and
96
96
  // `anthropic-haiku` pins `claude-haiku-4-5` as its own provider row — so
97
97
  // between them an Anthropic BYOK key could pin Sonnet or Haiku but never
98
- // Opus or Fable, the other two members of the current Claude 5 lineup the
99
- // vendor already serves. Both ids already have a priced rate row
100
- // (desktop/renderer/usage.js `opus`/`fable`, matched by family substring),
101
- // so the picker just had no way to offer them, not an unpriced gap. Listed
102
- // under the `anthropic` provider id because that is the row the server
103
- // advertises a configured Anthropic key against — the relay forwards
104
- // whichever of the two names the caller actually pins.
105
- anthropic: Object.freeze(['claude-opus-5', 'claude-fable-5']),
98
+ // Opus or Fable, the other two members of the Claude 5 lineup the vendor
99
+ // already serves. Listed under the `anthropic` provider id because that is
100
+ // the row the server advertises a configured Anthropic key against — the
101
+ // relay forwards whichever of these names the caller actually pins.
102
+ //
103
+ // Verified live 2026-10-11 against `GET https://api.anthropic.com/v1/models`
104
+ // (14 ids, `has_more: false`), which is where every id below is copied from
105
+ // rather than from memory:
106
+ //
107
+ // claude-haiku-5-5, claude-sonnet-5-5, claude-opus-5-5, claude-fable-5-1,
108
+ // claude-opus-5, claude-sonnet-5, claude-fable-5, claude-opus-4-8,
109
+ // claude-opus-4-7, claude-sonnet-4-6, claude-opus-4-6,
110
+ // claude-opus-4-5-20251101, claude-haiku-4-5-20251001,
111
+ // claude-sonnet-4-5-20250929
112
+ //
113
+ // The server's two defaults cover `claude-sonnet-5` and `claude-haiku-4-5`;
114
+ // the five below are the CURRENT members of the lineup it does not name —
115
+ // the 5.5 generation (Haiku, Sonnet, Opus) plus Fable 5.1, and the older
116
+ // Opus 5 / Fable 5 that were already listed. Every one has a priced rate row
117
+ // (desktop/renderer/usage.js, the Claude 5 block), so the picker was missing
118
+ // the ability to OFFER them, not a rate.
119
+ //
120
+ // What is deliberately NOT here, and why it matters more than what is:
121
+ // `claude-opus-4-1` (and its dated form `claude-opus-4-1-20250805`) is
122
+ // RETIRED upstream. Probed live 2026-10-11, `POST /v1/messages` with that
123
+ // model answers HTTP 404 `not_found_error` — the same probe answers
124
+ // `rate_limit_error` (i.e. the model resolved) for every id listed above,
125
+ // which is what makes 404 mean "no such model" rather than "no credit".
126
+ // The engine's own MODELS table still carries a legacy `claude-opus-4-1`
127
+ // row for saved configs, and that is fine — it is a local label that
128
+ // RESOLVES; a client-side catalog addition is a promise the picker will pin
129
+ // and the relay will forward, and this module's whole reason for existing is
130
+ // that a fabricated id "would pin, look accepted, and 404 on the first
131
+ // turn". So Opus 4.1 stays out of the offered list until Anthropic serves
132
+ // it again.
133
+ anthropic: Object.freeze([
134
+ 'claude-opus-5',
135
+ 'claude-fable-5',
136
+ 'claude-opus-5-5',
137
+ 'claude-sonnet-5-5',
138
+ 'claude-haiku-5-5',
139
+ 'claude-fable-5-1',
140
+ ]),
106
141
  // xAI's `grok` descriptor still pins `grok-4.5` as default_model — current
107
142
  // when that descriptor was written, but xAI has since shipped grok-4.6 and
108
143
  // grok-4.7 (flagship, Sept 2026) on the same `grok-4.5`-shaped id
@@ -0,0 +1,378 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * user-models.js — the models the USER declares, in one file every host reads.
5
+ *
6
+ * ── the problem this module removes ────────────────────────────────────────
7
+ *
8
+ * `client/byok-catalog.js` is the list of vendor ids the server's catalog does
9
+ * not name but the relay forwards. It is a *shipping* artifact: every entry is
10
+ * a code change, a review, a release, and a desktop rebuild — and the file's own
11
+ * doc says so ("the durable fix for any of them is the server's MODEL_CATALOG").
12
+ * That is the right shape for the ids AEGIS should be offering everybody. It is
13
+ * the wrong shape for an id one user can call today: a freshly shipped model, a
14
+ * fine-tune, a preview id behind their own vendor key, a Together/Groq/OpenRouter
15
+ * route the relay forwards and the catalog simply has not caught up with.
16
+ *
17
+ * The BYOK relay is a stateless pass-through (`services/byok_service.py`): the
18
+ * caller's own vendor key authenticates upstream and AEGIS forwards the model
19
+ * string it was handed. So for a provider the account holds a key for, an id the
20
+ * VENDOR serves is callable whether or not this repo has ever heard of it. The
21
+ * only thing missing was a way for the user to say so without waiting for us.
22
+ *
23
+ * ── what a user does now ───────────────────────────────────────────────────
24
+ *
25
+ * CLI `/model-add <provider> <model-id>` (and `/model-rm …`)
26
+ * Desktop Settings → "Add a model" → provider + id
27
+ * Either hand-edit `$AEGISCODE_HOME/models.json` (default `~/.aegiscode`)
28
+ *
29
+ * All three end up in the same file, and the file is the whole state:
30
+ * `{ "deepseek": ["deepseek-v4.2-preview"], "anthropic": ["claude-opus-9-1"] }`.
31
+ * Because the CLI and the desktop both read it at the moment they build the
32
+ * picker, a model added in the terminal is in the window's list on its next
33
+ * refresh, with no restart and no release. That is the whole point of putting
34
+ * it in the shared data dir rather than in each host's own config.
35
+ *
36
+ * ── the rules this module keeps (the same ones byok-catalog.js keeps) ──────
37
+ *
38
+ * - NEVER invent a provider. User models are applied only to a provider row
39
+ * the server's catalog already lists. A row this file fabricated would
40
+ * invite a key for a slug the relay may not accept, and the failure would
41
+ * land on the user's first turn — so a declaration naming an unknown
42
+ * provider is preserved in the file and REPORTED (`unmatchedUserProviders`),
43
+ * never rendered as a picker row.
44
+ * - ONE spelling per route. Declarations are de-duplicated on add and again
45
+ * when they are applied, so the same id added twice — or added while the
46
+ * server has started listing it itself — paints one row, not two.
47
+ * - Idempotent and non-mutating. `withUserModels` returns a NEW array, shares
48
+ * the provider objects that gained nothing, and appends after the server's
49
+ * own models so the server's `default_model` keeps its first position (the
50
+ * default is what a bare provider id runs).
51
+ * - Validated, not trusted. A model id is a string the relay forwards to a
52
+ * vendor: a typo does not error here, it 404s upstream on the user's first
53
+ * turn. So ids and provider slugs are shape-checked on write (and re-checked
54
+ * on read, because the file is hand-editable), and a bad row is dropped with
55
+ * a reason rather than silently stored.
56
+ * - Never secret. Only provider slugs and model ids belong here — the file is
57
+ * written 0600 anyway, next to the credential store, because provider/model
58
+ * choice is not the kind of thing another local account should be able to
59
+ * rewrite.
60
+ */
61
+
62
+ const fs = require('node:fs');
63
+ const path = require('node:path');
64
+
65
+ const credentials = require('./credentials.js');
66
+
67
+ /** The file the CLI, the desktop and the MCP host all read. */
68
+ const USER_MODELS_FILE = 'models.json';
69
+ const FILE_MODE = 0o600;
70
+ /** A ceiling, not a policy: enough for a real vendor lineup, small enough that
71
+ * a runaway script cannot turn the picker into a wall of rows. */
72
+ const MAX_MODELS_PER_PROVIDER = 32;
73
+ const MAX_PROVIDERS = 64;
74
+
75
+ /**
76
+ * The provider slug shape the relay addresses (`deepseek`, `together-ai`,
77
+ * `openai-gpt4o-mini`). Lowercase on purpose: `/byok-key OpenAI` resolves to
78
+ * `openai` through the server's catalog, and two spellings of one provider id
79
+ * is exactly how a stored user model comes to never match the row it was meant
80
+ * for.
81
+ */
82
+ const PROVIDER_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
83
+ /**
84
+ * The model id shape. Deliberately permissive across vendors (dots for Claude,
85
+ * dashes for DeepSeek, slashes for the org-prefixed routes OpenRouter and
86
+ * Together use) and deliberately exclusive of two things: whitespace, because a
87
+ * model id with a space in it is a paste accident, and `:`, because
88
+ * `provider:model` is the id the picker and the engine already speak — a model
89
+ * id containing a colon would make that split ambiguous.
90
+ */
91
+ const MODEL_RE = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,95}$/;
92
+
93
+ /** The data dir (`$AEGISCODE_HOME` or `~/.aegiscode`), from the ONE definition. */
94
+ function userModelsDir(opts) {
95
+ return (opts && opts.dir) || credentials.aegisHome(opts && opts.env);
96
+ }
97
+
98
+ /** The absolute path of the shared user-model file. */
99
+ function userModelsPath(opts) {
100
+ return path.join(userModelsDir(opts), USER_MODELS_FILE);
101
+ }
102
+
103
+ /** Throw a message that says what to type instead. */
104
+ function badValue(what, raw, why) {
105
+ return new Error(
106
+ `aegiscode: ${what} ${JSON.stringify(String(raw))} is not usable — ${why}`
107
+ );
108
+ }
109
+
110
+ /** One provider slug, validated. Accepts the server's own spelling idempotently. */
111
+ function sanitizeProvider(raw) {
112
+ const s = String(raw == null ? '' : raw).trim().toLowerCase();
113
+ if (!s) throw badValue('provider', raw, 'the provider id is empty');
114
+ if (!PROVIDER_RE.test(s)) {
115
+ throw badValue(
116
+ 'provider',
117
+ raw,
118
+ 'a provider id is lowercase letters, digits, dot, dash or underscore ' +
119
+ '(the id `/byok` prints)'
120
+ );
121
+ }
122
+ return s;
123
+ }
124
+
125
+ /** One model id, validated. Ids are compared verbatim — never case-folded. */
126
+ function sanitizeModel(raw) {
127
+ const s = String(raw == null ? '' : raw).trim();
128
+ if (!s) throw badValue('model id', raw, 'the model id is empty');
129
+ if (/:/.test(s)) {
130
+ throw badValue(
131
+ 'model id',
132
+ raw,
133
+ "'provider:model' is how a picked model is addressed, so a model id cannot contain a colon"
134
+ );
135
+ }
136
+ if (!MODEL_RE.test(s)) {
137
+ throw badValue(
138
+ 'model id',
139
+ raw,
140
+ 'a model id has no spaces — it is the string sent to the vendor ' +
141
+ '(e.g. deepseek-v4.2-preview, claude-opus-9-1)'
142
+ );
143
+ }
144
+ return s;
145
+ }
146
+
147
+ /** True when `value` is a plain object (never an array, never null). */
148
+ function isPlainObject(value) {
149
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
150
+ }
151
+
152
+ /**
153
+ * Read the file and return BOTH the usable map and what was dropped.
154
+ *
155
+ * Never throws: a corrupt, unreadable or hand-mangled file reads as "no user
156
+ * models", because a declaration store must not be able to take the model
157
+ * picker down. But it does not lie about it either — `invalid` carries one
158
+ * `{ provider, model, reason }` per row that was skipped, which is what the
159
+ * hosts surface so a hand-edited typo is visible instead of looking like "the
160
+ * feature did nothing".
161
+ */
162
+ function load(opts) {
163
+ const file = userModelsPath(opts);
164
+ const invalid = [];
165
+ let raw;
166
+ try {
167
+ raw = JSON.parse(fs.readFileSync(file, 'utf8'));
168
+ } catch (err) {
169
+ // ENOENT is the normal state of a fresh install, not a problem to report.
170
+ if (err && err.code === 'ENOENT') return { dir: userModelsDir(opts), file, map: {}, invalid };
171
+ invalid.push({ provider: null, model: null, reason: `unreadable: ${(err && err.message) || err}` });
172
+ return { dir: userModelsDir(opts), file, map: {}, invalid };
173
+ }
174
+ const map = {};
175
+ if (!isPlainObject(raw)) {
176
+ invalid.push({ provider: null, model: null, reason: 'the file must be an object of provider → [model ids]' });
177
+ return { dir: userModelsDir(opts), file, map, invalid };
178
+ }
179
+ for (const [providerRaw, modelsRaw] of Object.entries(raw)) {
180
+ if (providerRaw === 'version' || providerRaw === '$schema') continue;
181
+ let provider;
182
+ try {
183
+ provider = sanitizeProvider(providerRaw);
184
+ } catch (err) {
185
+ invalid.push({ provider: providerRaw, model: null, reason: err.message });
186
+ continue;
187
+ }
188
+ const list = Array.isArray(modelsRaw) ? modelsRaw : [modelsRaw];
189
+ const seen = new Set();
190
+ const keep = [];
191
+ for (const m of list) {
192
+ let model;
193
+ try {
194
+ model = sanitizeModel(m);
195
+ } catch (err) {
196
+ invalid.push({ provider, model: m, reason: err.message });
197
+ continue;
198
+ }
199
+ if (seen.has(model)) continue; // one spelling per route, in the file too
200
+ seen.add(model);
201
+ keep.push(model);
202
+ }
203
+ if (keep.length) map[provider] = keep;
204
+ }
205
+ return { dir: userModelsDir(opts), file, map, invalid };
206
+ }
207
+
208
+ /** Just the usable provider → [ids] map (`load()` without the report). */
209
+ function readUserModels(opts) {
210
+ return load(opts).map;
211
+ }
212
+
213
+ /** The ids declared for one provider (an empty array when there are none). */
214
+ function userModelIdsFor(provider, opts) {
215
+ let id;
216
+ try {
217
+ id = sanitizeProvider(provider);
218
+ } catch {
219
+ return [];
220
+ }
221
+ const map = readUserModels(opts);
222
+ return Array.isArray(map[id]) ? map[id].slice() : [];
223
+ }
224
+
225
+ /** Write the map atomically, 0600, pretty-printed so it stays hand-editable. */
226
+ function writeMap(map, opts) {
227
+ const file = userModelsPath(opts);
228
+ fs.mkdirSync(path.dirname(file), { recursive: true });
229
+ const tmp = `${file}.tmp-${process.pid}`;
230
+ fs.writeFileSync(tmp, JSON.stringify(map, null, 2) + '\n', { mode: FILE_MODE });
231
+ fs.renameSync(tmp, file);
232
+ try {
233
+ fs.chmodSync(file, FILE_MODE);
234
+ } catch {
235
+ /* Windows: POSIX modes are a no-op and ACLs are the OS's business */
236
+ }
237
+ return map;
238
+ }
239
+
240
+ /**
241
+ * Declare one model id for one provider.
242
+ *
243
+ * Returns `{ file, provider, model, added, models }` — `added: false` when the
244
+ * id was already declared, so the caller can say "already there" instead of
245
+ * claiming a change it did not make. Rejects a provider or id that fails the
246
+ * shape checks above, and refuses to grow a single provider past the ceiling.
247
+ */
248
+ function addUserModel(provider, model, opts) {
249
+ const id = sanitizeProvider(provider);
250
+ const modelId = sanitizeModel(model);
251
+ const map = readUserModels(opts);
252
+ const have = Array.isArray(map[id]) ? map[id].slice() : [];
253
+ if (have.includes(modelId)) {
254
+ return { file: userModelsPath(opts), provider: id, model: modelId, added: false, models: have };
255
+ }
256
+ if (have.length >= MAX_MODELS_PER_PROVIDER) {
257
+ throw new Error(
258
+ `aegiscode: ${id} already carries ${have.length} user models (the cap) — ` +
259
+ 'remove one with /model-rm before adding another.'
260
+ );
261
+ }
262
+ if (!map[id] && Object.keys(map).length >= MAX_PROVIDERS) {
263
+ throw new Error(
264
+ `aegiscode: ${Object.keys(map).length} providers already carry user models (the cap).`
265
+ );
266
+ }
267
+ const models = [...have, modelId];
268
+ const next = { ...map, [id]: models };
269
+ writeMap(next, opts);
270
+ return { file: userModelsPath(opts), provider: id, model: modelId, added: true, models };
271
+ }
272
+
273
+ /**
274
+ * Retire one declaration. Returns `{ …, removed }`; `removed: false` means it
275
+ * was not declared, which is a report and not an error (the file is shared, so
276
+ * another host may have removed it a moment ago).
277
+ */
278
+ function removeUserModel(provider, model, opts) {
279
+ const id = sanitizeProvider(provider);
280
+ const modelId = sanitizeModel(model);
281
+ const map = readUserModels(opts);
282
+ const have = Array.isArray(map[id]) ? map[id].slice() : [];
283
+ if (!have.includes(modelId)) {
284
+ return { file: userModelsPath(opts), provider: id, model: modelId, removed: false, models: have };
285
+ }
286
+ const models = have.filter((m) => m !== modelId);
287
+ const next = { ...map };
288
+ if (models.length) next[id] = models;
289
+ else delete next[id];
290
+ writeMap(next, opts);
291
+ return { file: userModelsPath(opts), provider: id, model: modelId, removed: true, models };
292
+ }
293
+
294
+ /** The model ids an entry names, tolerating the server's two shapes. */
295
+ function modelIdsOf(provider) {
296
+ return (Array.isArray(provider && provider.models) ? provider.models : [])
297
+ .map((m) => (typeof m === 'string' ? m : m && m.id))
298
+ .map((m) => (typeof m === 'string' ? m.trim() : ''))
299
+ .filter(Boolean);
300
+ }
301
+
302
+ /** The provider array out of either shape the server sends (or `[]`). */
303
+ function providerArray(providers) {
304
+ if (Array.isArray(providers)) return providers;
305
+ if (Array.isArray(providers && providers.providers)) return providers.providers;
306
+ return null;
307
+ }
308
+
309
+ /**
310
+ * The server's BYOK catalog with the USER's declared models applied.
311
+ *
312
+ * @param {Array<object>|object} providers the payload (array, or `{providers}`)
313
+ * @param {object} [extra] an explicit provider → [ids] map. Omitted by every
314
+ * host (they want the file); passing it is what makes this function pure and
315
+ * therefore testable without touching a real data dir.
316
+ * @returns {Array<object>} a NEW array. Providers that gained nothing come back
317
+ * as the SAME objects, an unknown provider is never fabricated, and an
318
+ * empty/absent payload returns `[]` rather than a list invented from the file.
319
+ */
320
+ function withUserModels(providers, extra) {
321
+ const raw = providerArray(providers);
322
+ if (!raw) return [];
323
+ const map = extra === undefined ? readUserModels() : isPlainObject(extra) ? extra : {};
324
+ const out = [];
325
+ for (const p of raw) {
326
+ if (!p || typeof p !== 'object') continue;
327
+ const id = typeof p.id === 'string' ? p.id.trim() : '';
328
+ const declared = id && Array.isArray(map[id]) ? map[id] : null;
329
+ if (!declared || !declared.length) {
330
+ out.push(p);
331
+ continue;
332
+ }
333
+ const have = new Set(modelIdsOf(p));
334
+ const missing = declared
335
+ .map((m) => String(m).trim())
336
+ .filter((m) => m && !have.has(m));
337
+ // Nothing to add — hand back the SAME object, so a complete payload is
338
+ // byte-identical after this pass and a caller cannot tell it ran.
339
+ if (!missing.length) {
340
+ out.push(p);
341
+ continue;
342
+ }
343
+ const models = Array.isArray(p.models) ? p.models : [];
344
+ out.push({ ...p, models: [...models, ...missing] });
345
+ }
346
+ return out;
347
+ }
348
+
349
+ /**
350
+ * Declared providers the payload does NOT list — the honest half of the rules
351
+ * above. A host reports these ("no provider row for `foo` — the relay takes
352
+ * keys for: …") instead of either hiding the declaration or showing a row that
353
+ * would 401 on its first turn.
354
+ */
355
+ function unmatchedUserProviders(providers, extra) {
356
+ const raw = providerArray(providers) || [];
357
+ const map = extra === undefined ? readUserModels() : isPlainObject(extra) ? extra : {};
358
+ const known = new Set(
359
+ raw.map((p) => (p && typeof p.id === 'string' ? p.id.trim() : '')).filter(Boolean)
360
+ );
361
+ return Object.keys(map).filter((id) => !known.has(id));
362
+ }
363
+
364
+ module.exports = {
365
+ USER_MODELS_FILE,
366
+ MAX_MODELS_PER_PROVIDER,
367
+ userModelsDir,
368
+ userModelsPath,
369
+ sanitizeProvider,
370
+ sanitizeModel,
371
+ load,
372
+ readUserModels,
373
+ userModelIdsFor,
374
+ addUserModel,
375
+ removeUserModel,
376
+ withUserModels,
377
+ unmatchedUserProviders,
378
+ };