aegiscode 6.7.6 → 6.7.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/README.md CHANGED
@@ -224,6 +224,7 @@ Three layers, from broadest to narrowest. You only need the first one.
224
224
  /class # show the picker
225
225
  /class aegis # pooled AEGIS Cloud (the default)
226
226
  /class byok # your own provider key, relayed by AEGIS
227
+ /class custom # a LOCAL endpoint of yours (Ollama, llama.cpp, a LAN box), called directly
227
228
  ```
228
229
 
229
230
  A class is *whose credential pays and who talks to the vendor*, not a model.
@@ -235,6 +236,7 @@ restart.
235
236
  |---|---|---|
236
237
  | `aegis` *(default)* | the AEGIS pool — one id, `nexus-brain` (alias `aegis-brain`), auto-routed server-side across whichever providers are live | your AEGIS account balance |
237
238
  | `byok` | your provider key, relayed via `POST /api/v1/byok/chat/completions` | your provider direct, **plus** a small AEGIS handling fee on your account |
239
+ | `custom` | a **local** base URL (localhost, a LAN address, `*.local`, a dotless host name) called **directly** by aegiscode — nothing is relayed | nobody. No vendor is involved, so there is no cost, no AEGIS fee and no margin. Remote endpoints are refused here — use `byok` |
238
240
 
239
241
  **2. The model id — what to pin.**
240
242
 
@@ -245,10 +247,10 @@ restart.
245
247
  /model - # clear the pin, back to the class default
246
248
  ```
247
249
 
248
- `/models` is class-aware: it answers from the pool catalogue under `aegis`, and
249
- from the models your saved keys actually unlock under `byok`. A pooled id is
250
- **cleared with a reason** if you switch to `byok` while it is pinned, instead of
251
- failing later at the relay.
250
+ `/models` is class-aware: it answers from the pool catalogue under `aegis`, from
251
+ the models your saved keys actually unlock under `byok`, and from the entries you
252
+ added with `/model add` under `custom`. A pin is **cleared with a reason** if you
253
+ switch to a class it does not belong to, instead of failing later at the route.
252
254
 
253
255
  Under `byok` every id is compound — `provider:model`:
254
256
 
@@ -257,9 +259,17 @@ Under `byok` every id is compound — `provider:model`:
257
259
  /model anthropic:claude-sonnet-4-5
258
260
  ```
259
261
 
262
+ Under `custom` the id is whatever you named the entry:
263
+
264
+ ```bash
265
+ /models # e.g. local-llama, lan-box
266
+ /model local-llama
267
+ ```
268
+
260
269
  ```bash
261
270
  aegiscode -m nexus-brain -p "…" # pin at launch
262
271
  aegiscode -m anthropic:claude-sonnet-4-5 -p "…" # a BYOK id at launch
272
+ aegiscode -m local-llama -p "…" # a custom id at launch
263
273
  ```
264
274
 
265
275
  **3. Effort — how hard it reasons.**
@@ -273,10 +283,80 @@ Effort scales the token budget the provider is given, so it is the dial that
273
283
  actually changes reasoning depth on a reasoning model (see the root README for
274
284
  the per-provider mechanics).
275
285
 
276
- > **A BYOK turn is single-shot.** The relay takes no `tools` parameter, so the
286
+ > **A `byok` turn is single-shot.** The relay takes no `tools` parameter, so the
277
287
  > agentic tool loop is off by construction — no file edits, no shell, no
278
288
  > subagents, no approval cards. `/class` says so rather than letting you discover
279
- > it mid-task.
289
+ > it mid-task. **`custom` does not have this limit** — aegiscode calls the local
290
+ > endpoint itself, so the full tool loop works normally.
291
+
292
+ ## Custom models — your local endpoint, called directly
293
+
294
+ `/model add` teaches aegiscode about an endpoint on **your own machine** — an
295
+ Ollama or llama.cpp server, a box on your LAN. There is no relay, no handling fee
296
+ and no margin: the request goes straight from your machine to the base URL you
297
+ gave, with the key you gave, and no vendor is paid because no vendor is
298
+ involved.
299
+
300
+ **Local only, by policy.** Remote endpoints are *not offered* on this lane. Every
301
+ other class bills — `aegis` the pooled route, `byok` the AEGIS handling fee on
302
+ the relay — and this lane bills nothing, so it is free for exactly one kind of
303
+ traffic: traffic that never leaves your machine. A remote base URL is refused at
304
+ the moment you add it, with a pointer at the lane that can serve it:
305
+
306
+ ```console
307
+ $ /model add work-gw "Work gateway" gpt-4o https://gw.corp/v1
308
+ couldn't add "work-gw": custom endpoints must be LOCAL — remote base URL "https://gw.corp/v1"
309
+ is not offered on this lane. Allowed: localhost, 127.0.0.1, a private/LAN address
310
+ (10.x, 172.16-31.x, 192.168.x), *.local/.internal/.lan, or a dotless host like "ollama".
311
+ Remote providers are billed, so use /class byok with /byok-key <provider> (the AEGIS
312
+ relay charges the handling fee there), or point this entry at a local address.
313
+ ```
314
+
315
+ There is no flag, env var or override that re-opens the remote direct lane: such
316
+ a switch would be a billing bypass. The refusal is enforced twice — in the add
317
+ path, and again in the dispatch gate before any network call — so an entry left
318
+ in `config.json` from an older build is still refused rather than dialled.
319
+
320
+ ```bash
321
+ /model add local-llama "Local Llama" llama-3.3-70b http://localhost:11434/v1
322
+ /model add lan-box "LAN box" qwen3:32b http://192.168.1.40:8080/v1
323
+ /model key local-llama # set or replace the key later (prompted, masked)
324
+ /class custom # route turns through these
325
+ /model local-llama # pin one
326
+ /model remove local-llama # drop the entry and its key
327
+ ```
328
+
329
+ Remote providers are a `byok` concern, and that lane bills:
330
+
331
+ ```bash
332
+ /class byok
333
+ /byok-key openai # …or anthropic, groq, deepseek, …
334
+ /model openai:gpt-4o
335
+ ```
336
+
337
+ A local base URL counts as local when it is a loopback address (`localhost`,
338
+ `127.0.0.0/8`, `::1`), a private range (`10/8`, `172.16/12`, `192.168/16`,
339
+ `fc00::/7`), link-local (`169.254/16`, `fe80::/10`), a reserved local suffix
340
+ (`.local`, `.internal`, `.lan`) or a bare dotless host name (`ollama`). Anything
341
+ else — including an address that does not parse — is treated as remote and
342
+ refused: the classifier fails closed, so an ambiguity costs you a retry, never an
343
+ unpaid remote turn.
344
+
345
+ The wire protocol is inferred from the base URL — anything that is not
346
+ `anthropic.com` speaks the OpenAI-compatible shape, which is what a local
347
+ inference server (Ollama, llama.cpp, vLLM, LM Studio) does — or you can pass
348
+ `openai` / `anthropic` explicitly to override it, which is how you point the
349
+ Messages API at a local gateway.
350
+
351
+ Where things are stored, and why it is split:
352
+
353
+ | What | Where | Why |
354
+ |---|---|---|
355
+ | name, model, base URL, wire | `~/.aegiscode/config.json` | it is configuration, and it is not secret |
356
+ | the API key | `~/.aegiscode/settings.json` (mode `0600`) | secrets belong in the file we chmod, keyed `custom:<id>` |
357
+
358
+ The key is never written into `config.json`. A local endpoint that needs no key
359
+ is fine — omit it and no `Authorization` header is sent.
280
360
 
281
361
  ## Bring your own key
282
362
 
@@ -377,12 +457,15 @@ echo "why is the sky blue" | aegiscode -p -
377
457
  ### Switch how you're paying
378
458
 
379
459
  ```bash
380
- /class # see both routes and who pays
460
+ /class # see every route and who pays
381
461
  /class byok # use your own key
382
462
  /byok-key openai # …save one first if it says you have none
383
463
  /models # what that key unlocks
384
464
  /model openai:gpt-4o # pin one
385
465
  /class aegis # back to the pool
466
+
467
+ /model add local-llama "Local Llama" llama-3.3-70b http://localhost:11434/v1
468
+ /class custom # or call a LOCAL endpoint directly (remote URLs are refused — use byok)
386
469
  ```
387
470
 
388
471
  ### Control the budget
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "6.7.6",
4
+ "version": "6.7.8",
5
5
  "description": "aegiscode — the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
@@ -61,6 +61,22 @@ const FILES = [
61
61
  'desktop/lib/local/shell.js',
62
62
  'desktop/lib/local/agents.js',
63
63
  'desktop/lib/local/prompt.js',
64
+ // The direct-provider transport (openaiCompatible + anthropicMessages) the
65
+ // desktop injects into the engine for its custom-endpoint classes. The CLI's
66
+ // `custom` class (src/engine.js, the /model add catalog) now injects the same
67
+ // real transport instead of the throwing stub it used to, so a user's own
68
+ // base URL + key is called directly with the full tool loop — so this file
69
+ // must ship. Pure node builtins (fetch), stages cleanly.
70
+ 'desktop/lib/local/providers.js',
71
+ // The direct-dial policy the transports above are gated by: which base URLs
72
+ // may reach them at all (local endpoints only — a remote one has nothing to
73
+ // bill against, see the module). BOTH hosts read it: the desktop engine and
74
+ // settings store require it relatively, and this package reaches it through
75
+ // src/sharedpaths.js from src/custommodels.js. Leaving it out of the staged
76
+ // tree is a MODULE_NOT_FOUND at CLI start-up — which is also why it must be
77
+ // listed before the settings store, whose `set()` refuses a remote URL for a
78
+ // direct-dial row (settings.js -> ./local/endpoints.js).
79
+ 'desktop/lib/local/endpoints.js',
64
80
  // The provider-config store: one row per provider (base URL + key), and the
65
81
  // row the 'byok' class reads for a per-provider key. The CLI now selects that
66
82
  // class (src/engine.js), so it needs the same store the desktop writes —
package/src/app.js CHANGED
@@ -40,6 +40,7 @@ const {
40
40
  const credentials = require('./credentials.js');
41
41
  const cloudsync = require('./cloudsync.js');
42
42
  const { readSecret } = require('./secret.js');
43
+ const customModelsCatalog = require('./custommodels.js');
43
44
  const { normalizeModelCatalog, pickerEntries, catalogIds } = require('./models.js');
44
45
  const { appendHistory, readSessionTranscript, readOwnSessions } = require('./history.js');
45
46
  const { snapshotCheckpoint } = require('./checkpoint.js');
@@ -493,15 +494,40 @@ function createApp(options = {}) {
493
494
  * offer": a catalog is a convenience, and an offline client must still be
494
495
  * able to chat on the server's own default.
495
496
  */
497
+ async function loadCustomModels() {
498
+ // The `custom` catalog is local (config.json + the 0600 key store), so this
499
+ // never touches the network and needs no cache. The engine already returns
500
+ // the picker/`/models` shape ({id, label, note, configured, wire}).
501
+ if (typeof engine.listModels !== 'function') return [];
502
+ const res = await engine.listModels('custom');
503
+ return (res && res.models) || [];
504
+ }
505
+
496
506
  async function listModelsFor(cls) {
497
507
  const want = HOST_CLASSES.includes(cls) ? cls : commandCtx.modelClass;
498
508
  try {
499
- return want === 'byok' ? await loadByokModels() : await loadModels();
509
+ if (want === 'byok') return await loadByokModels();
510
+ if (want === 'custom') return await loadCustomModels();
511
+ return await loadModels();
500
512
  } catch {
501
513
  return [];
502
514
  }
503
515
  }
504
516
 
517
+ /**
518
+ * Whether a pinned id can run on `cls`, decided synchronously (switchClass is
519
+ * not async). byok ids are `provider:model`; custom ids are the catalog's
520
+ * own (config.json, read sync); aegis takes anything that is neither — the
521
+ * pooled catalog is validated separately, at launch, by validatePinnedModel.
522
+ */
523
+ function pinBelongsToClass(cls, id) {
524
+ const s = String(id == null ? '' : id);
525
+ if (cls === 'byok') return s.includes(':');
526
+ if (cls === 'custom') return Boolean(customModelsCatalog.getCustom(s));
527
+ // aegis: not a byok id and not a custom-catalog id.
528
+ return !s.includes(':') && !customModelsCatalog.getCustom(s);
529
+ }
530
+
505
531
  /**
506
532
  * Switch the live class. Refuses anything this host cannot run (engine.js's
507
533
  * HOST_CLASSES is the authority — the local/custom classes stay stubs).
@@ -511,7 +537,9 @@ function createApp(options = {}) {
511
537
  * fail at the relay with a confusing "no key saved for …" instead of here,
512
538
  * with a reason. Symmetrically, `anthropic:claude-…` under aegis is an id the
513
539
  * pooled catalog does not advertise, which is the silent-fallback case
514
- * validatePinnedModel exists to prevent.
540
+ * validatePinnedModel exists to prevent. The `custom` class owns its own id
541
+ * space (the /model add catalog, resolvable synchronously from config.json),
542
+ * so a pin belongs to it exactly when it is one of those ids.
515
543
  */
516
544
  function switchClass(next) {
517
545
  const want = String(next == null ? '' : next).trim().toLowerCase();
@@ -522,8 +550,7 @@ function createApp(options = {}) {
522
550
  commandCtx.modelClass = want;
523
551
  let cleared = null;
524
552
  if (prev !== want && commandCtx.model) {
525
- const isByokId = String(commandCtx.model).includes(':');
526
- if (want === 'byok' ? !isByokId : isByokId) {
553
+ if (!pinBelongsToClass(want, commandCtx.model)) {
527
554
  cleared = commandCtx.model;
528
555
  commandCtx.model = null;
529
556
  }
@@ -583,6 +610,31 @@ function createApp(options = {}) {
583
610
  );
584
611
  return pinned;
585
612
  }
613
+ // A custom pin is validated against the local catalog, never the pooled one:
614
+ // its ids are the user's own (from /model add) and the pool has never heard
615
+ // of them, so checking the pooled catalog would clear every custom pin on
616
+ // launch. An empty catalog clears nothing (offline-safe like the pooled path).
617
+ if (commandCtx.modelClass === 'custom') {
618
+ let customModels;
619
+ try {
620
+ customModels = await loadCustomModels();
621
+ } catch {
622
+ return null;
623
+ }
624
+ if (!customModels.length) return null;
625
+ if (customModels.some((m) => m.id === pinned)) return null;
626
+ commandCtx.model = null;
627
+ updateConfig({ model: null, currentModelId: null });
628
+ emit(
629
+ render.renderNotice(
630
+ ctx(),
631
+ 'warn',
632
+ `pinned model "${pinned}" is not in your custom catalog — pin cleared; ` +
633
+ '/models lists your endpoints, /model add registers one.'
634
+ )
635
+ );
636
+ return pinned;
637
+ }
586
638
  let models;
587
639
  try {
588
640
  models = await loadModels();
@@ -1030,7 +1082,23 @@ function createApp(options = {}) {
1030
1082
  // dropped, live ids only (see models.js pickerEntries).
1031
1083
  // Whichever class is live decides what is pinnable — the pooled ids the
1032
1084
  // server advertises, or the `provider:model` ids this machine can relay.
1033
- models: pickerEntries(commandCtx.modelClass === 'byok' ? byokCache.models : modelCache.models),
1085
+ // The rows the picker/overlay offers. Class-scoped, because each class
1086
+ // owns a different id space: pool-advertised ids on aegis, this machine's
1087
+ // `provider:model` ids on byok, and the /model add catalog on custom.
1088
+ // The custom half is read synchronously from config.json (+ the 0600 key
1089
+ // store for the `configured` flag) because buildState() cannot await, and
1090
+ // it is the reason the picker used to fail on that class: the ternary
1091
+ // here was two-way, so `custom` fell through to the pooled modelCache,
1092
+ // which is never populated on a class that never asks the pool.
1093
+ // `listCustomModels` is the same builder /models and the engine use, so
1094
+ // the rows cannot drift from what the class will actually accept.
1095
+ models: pickerEntries(
1096
+ commandCtx.modelClass === 'byok'
1097
+ ? byokCache.models
1098
+ : commandCtx.modelClass === 'custom'
1099
+ ? customModelsCatalog.listCustomModels(engine.settings)
1100
+ : modelCache.models
1101
+ ),
1034
1102
  commands: visibleCommands(),
1035
1103
  transcript: transcript.slice(),
1036
1104
  sessions: [],
package/src/commands.js CHANGED
@@ -65,6 +65,7 @@ const { detectDevCommand, runDevServer } = require('./devrun.js');
65
65
  const credentials = require('./credentials.js');
66
66
  const cloudsync = require('./cloudsync.js');
67
67
  const { maskKey, fmtTokens } = require('./format.js');
68
+ const { pickerEntries } = require('./models.js');
68
69
  const { openUrl, URLS } = require('./system.js');
69
70
  const { sniffProject, buildAegisMd } = require('./init.js');
70
71
  const {
@@ -73,6 +74,9 @@ const {
73
74
  const {
74
75
  aggregateSessionUsage, pruneSessionHistory, readResumeList,
75
76
  } = require('./history.js');
77
+ // The custom-endpoint catalog behind the `custom` class and /model add|key|remove.
78
+ const customModelsCatalog = require('./custommodels.js');
79
+ const { VALID_WIRES } = customModelsCatalog;
76
80
 
77
81
  // Guarded: a concurrent workstream owns ./markdown.js.
78
82
  let markdownModule = null;
@@ -111,23 +115,74 @@ const EFFORT_LEVELS = overlays.EFFORT_VALUES;
111
115
 
112
116
  // ── Small handler helpers ─────────────────────────────────────────────────────
113
117
 
114
- const note = (c, text) => c.push({ role: 'note', text });
115
- const panel = (c, lines) => c.push({ role: 'panel', lines });
118
+ /**
119
+ * Split a command's raw tail into tokens, honouring double quotes so a model
120
+ * name or id with a space stays one token
121
+ * (`/model add local "Llama 3 70B" http://…`). Backslash escapes a quote or a
122
+ * backslash inside a quoted run. Never throws — an unclosed quote simply ends
123
+ * at the end of the line.
124
+ */
125
+ function splitArgs(raw) {
126
+ const text = String(raw == null ? '' : raw);
127
+ const out = [];
128
+ let cur = '';
129
+ let quoted = false;
130
+ let started = false;
131
+ for (let i = 0; i < text.length; i++) {
132
+ const ch = text[i];
133
+ if (ch === '\\' && quoted && i + 1 < text.length && (text[i + 1] === '"' || text[i + 1] === '\\')) {
134
+ cur += text[++i];
135
+ started = true;
136
+ continue;
137
+ }
138
+ if (ch === '"') {
139
+ quoted = !quoted;
140
+ // A quoted empty string ("") is a real, intentional token.
141
+ started = true;
142
+ continue;
143
+ }
144
+ if (!quoted && /\s/.test(ch)) {
145
+ if (started) out.push(cur);
146
+ cur = '';
147
+ started = false;
148
+ continue;
149
+ }
150
+ cur += ch;
151
+ started = true;
152
+ }
153
+ if (started) out.push(cur);
154
+ return out;
155
+ }
156
+
157
+ const note = (c, text) => c.push({ role: 'note', text });const panel = (c, lines) => c.push({ role: 'panel', lines });
116
158
  const tip = (c, text) => c.push({ role: 'tip', text });
117
159
  const done = (c, text) => c.push({ role: 'done', text });
118
160
  const shortCwd = () => process.cwd().split('/').filter(Boolean).pop() || '~';
119
161
 
120
162
  /**
121
- * Refresh the pinnable-model list on the session context before reading it.
122
- * `c.loadModels()` (owned by the app/chatflow) fetches from the server and
123
- * records the result on `c.state().models`; it is best-effort — offline it
124
- * rejects, and the caller falls through to the honest empty note rather than
125
- * opening an empty picker.
163
+ * The pinnable-model list for the class the session is on, fetched fresh.
164
+ *
165
+ * `c.loadModels()` on the command context is `() => listModelsFor(cls)` — it
166
+ * already returns the class-scoped rows (pooled catalog on aegis, the
167
+ * `provider:model` ids this machine can relay on byok, the /model add catalog
168
+ * on custom). This helper must RETURN that value.
169
+ *
170
+ * It used to `await` it and discard the result, leaving every caller to read
171
+ * `c.state().models` instead — and that field was a two-way ternary over a
172
+ * three-class world, so on `custom` it fell through to the pooled catalog,
173
+ * which is never populated on that class. The picker therefore reported "Could
174
+ * not read the model catalog" on a class whose models are local and always
175
+ * readable, while `/models` (which reads listModelsFor directly) listed them
176
+ * correctly. Best-effort on failure: offline, the caller falls through to the
177
+ * honest empty note rather than opening an empty picker.
178
+ * @returns {Promise<Array<{id:string,label:string,note:string}>>}
126
179
  */
127
180
  async function loadModels(c) {
128
181
  try {
129
- await c.loadModels();
130
- } catch {}
182
+ return (await c.loadModels()) || [];
183
+ } catch {
184
+ return [];
185
+ }
131
186
  }
132
187
 
133
188
  /**
@@ -289,10 +344,12 @@ async function applyAccountKey(c, raw, { label = 'AEGIS API key' } = {}) {
289
344
  const acct = (res.account && (res.account.email || res.account.plan)) || null;
290
345
  done(c, `AEGIS key saved to ${res.path}${acct ? ` — signed in as ${acct}` : ' and verified'}`);
291
346
  // The catalog is key-gated, so a freshly authenticated session should offer
292
- // /model's picker without the user having to know to re-run it.
347
+ // /model's picker without the user having to know to re-run it. Counted from
348
+ // the loader's return value (through pickerEntries, the same filter the
349
+ // picker applies) rather than `c.state().models`, so the number matches what
350
+ // the picker will actually offer.
293
351
  try {
294
- await c.loadModels({ force: true });
295
- const n = (c.state().models || []).length;
352
+ const n = pickerEntries(await loadModels(c)).length;
296
353
  if (n) note(c, `${n} pinnable model${n === 1 ? '' : 's'} available — /model to pin one`);
297
354
  } catch {}
298
355
  return res;
@@ -807,28 +864,44 @@ const COMMANDS = [
807
864
  // will actually take (app.js's buildState().models is class-scoped too).
808
865
  const cls = (c.ctx && c.ctx.modelClass) || 'aegis';
809
866
  const byok = cls === 'byok';
867
+ const custom = cls === 'custom';
868
+ // The sub-command token, lower-cased: `add` / `key` / `remove` are the
869
+ // custom-endpoint catalog's verbs. A model id is never one of these in
870
+ // practice, and `list` already shadows a real id the same way.
871
+ const sub = id.toLowerCase();
810
872
  if (!id) {
811
873
  note(c, `model: ${c.ctx.model || 'server default'}`);
812
- // Populate the picker from the server first — app.js's state().models
813
- // is empty until loadModels() has run, so an unguarded read renders an
814
- // empty picker whose Enter does nothing.
815
- await loadModels(c);
816
- const models = c.state().models || [];
874
+ // Populate the picker for the LIVE class first. The list is the return
875
+ // value, not `c.state().models`: that field is rebuilt from a cache the
876
+ // current class may not populate (and the custom class never asks the
877
+ // pool at all), so reading it rendered an empty picker on a class whose
878
+ // models are local and always readable.
879
+ //
880
+ // `pickerEntries` is the same filter app.js's buildState() applies to
881
+ // that field, and it has to be applied here for the same reason it is
882
+ // applied there: the loader returns the catalog — aliases included —
883
+ // and an alias row is not a pinnable entry, so listing it puts a
884
+ // duplicate in the picker that pins the id it points at.
885
+ const models = pickerEntries(await loadModels(c));
817
886
  if (!models.length) {
818
887
  // Say why, and what unblocks it: an unreachable catalog is almost
819
888
  // always a missing key or no network, and "no models advertised"
820
889
  // read as "the platform has none" rather than "this client could not
821
890
  // ask". On byok "no models" has a third cause — the relay is fine and
822
891
  // the account is fine, this machine simply holds no provider key yet,
823
- // which is exactly what /byok-key fixes.
824
- note(c, byok
825
- ? 'No relayable models — this machine holds no provider key yet. Save one with /byok-key <provider>, then retry /model.'
826
- : c.state().online
827
- ? 'Could not read the model catalog (offline, or the server refused it) — /models retries.'
828
- : // The key travels in the environment only (client/aegis.js reads
829
- // AEGIS_API_KEY); /login is an unavailable command here, so
830
- // pointing at it would send the user to a refusal.
831
- 'No API key set, so the model catalog cannot be read — export AEGIS_API_KEY (free at https://aegiscloud.org), then retry /model.');
892
+ // which is exactly what /byok-key fixes. On custom an empty list is
893
+ // never a network problem: the catalog is local, so the only cause is
894
+ // that it has not been filled in yet.
895
+ note(c, custom
896
+ ? 'No custom endpoints yet — /model add <id> <name> <model> <baseURL> registers a LOCAL endpoint (its key is prompted, or pass it last).'
897
+ : byok
898
+ ? 'No relayable models — this machine holds no provider key yet. Save one with /byok-key <provider>, then retry /model.'
899
+ : c.state().online
900
+ ? 'Could not read the model catalog (offline, or the server refused it) — /models retries.'
901
+ : // The key travels in the environment only (client/aegis.js reads
902
+ // AEGIS_API_KEY); /login is an unavailable command here, so
903
+ // pointing at it would send the user to a refusal.
904
+ 'No API key set, so the model catalog cannot be read — export AEGIS_API_KEY (free at https://aegiscloud.org), then retry /model.');
832
905
  c.render();
833
906
  return true;
834
907
  }
@@ -836,35 +909,133 @@ const COMMANDS = [
836
909
  // from its own default with no error. Say so where the pin is visible
837
910
  // rather than letting the reply look like the pinned model. On byok the
838
911
  // failure mode is different and louder (the relay 400s on a provider it
839
- // has no key for), so the sentence names the right one.
912
+ // has no key for), so the sentence names the right one; on custom the
913
+ // entry was simply removed or renamed after it was pinned.
840
914
  if (c.ctx.model && !models.some((m) => m.id === c.ctx.model)) {
841
- note(c, byok
842
- ? `pinned model "${c.ctx.model}" is not one this machine can relay — pick from the list below.`
843
- : `pinned model "${c.ctx.model}" is not in the catalog — the pool will answer with its own default; pick one below.`);
915
+ note(c, custom
916
+ ? `pinned model "${c.ctx.model}" is not in your custom catalog — pick one below, or re-add it with /model add.`
917
+ : byok
918
+ ? `pinned model "${c.ctx.model}" is not one this machine can relay — pick from the list below.`
919
+ : `pinned model "${c.ctx.model}" is not in the catalog — the pool will answer with its own default; pick one below.`);
844
920
  }
845
- // The overlay's own copy promises /model add|remove (overlays.js, a
846
- // separate workstream); this build refuses both, so say here how a
847
- // model is actually selected.
848
- note(c, byok
849
- ? '/model <id> pins one for this session; /models lists what this machine can relay.'
850
- : '/model <id> pins one for this session; /models lists what the server advertises.');
921
+ // The overlay's subtitle promises /model add|remove, and that promise is
922
+ // now kept: the custom class owns this catalog, so the verbs are real
923
+ // there. Say which surface applies to the live class instead of the
924
+ // blanket "this build refuses both" that used to sit here.
925
+ note(c, custom
926
+ ? '/model <id> pins one for this session; /model add|key|remove manage the catalog; /models lists it.'
927
+ : byok
928
+ ? '/model <id> pins one for this session; /models lists what this machine can relay.'
929
+ : '/model <id> pins one for this session; /models lists what the server advertises.');
851
930
  // `cls` rides on the overlay so the picker's title and subtitle render
852
931
  // for the class that opened it, even if /class moves while it is open.
853
932
  c.openOverlay({ type: 'model', items: models, sel: 0, current: c.ctx.model, cls });
854
933
  return true;
855
934
  }
856
935
  if (id === 'list') {
857
- await loadModels(c);
858
- const models = c.state().models || [];
936
+ // Filtered like the picker above: the panel lists what can be pinned,
937
+ // so it cannot carry the alias rows the loader returns alongside them.
938
+ const models = pickerEntries(await loadModels(c));
859
939
  if (!models.length) note(c, 'No pinnable models advertised — /models lists the server\'s ids.');
860
940
  else panel(c, panels.buildModelList(c.ctx.model, models, c.ctx));
861
941
  c.render();
862
942
  return true;
863
943
  }
864
- if (id === 'add' || id === 'remove' || id === 'rm') {
865
- note(c, byok
866
- ? 'Model add/remove isn\'t supported in this build — on the byok class the list follows the provider keys you hold (/byok-key <provider>), then /model <provider>:<model>.'
867
- : 'Model add/remove isn\'t supported in this build — pin an existing server id with /model <id>.');
944
+ // The /model add catalog — the aegiscodex-dev concept ported in, LOCAL
945
+ // endpoints only. A user registers an endpoint on their own machine (own
946
+ // base URL, own model string, own key) and the CLI calls it DIRECTLY
947
+ // through the desktop transport, the full tool loop and all: no pooled
948
+ // route, no BYOK relay, no fee or margin — because the request never
949
+ // touches aegiscloud.org and there is no vendor to pay.
950
+ //
951
+ // That is only defensible for an address on this machine. A REMOTE base
952
+ // URL is refused (custommodels.js isLocalEndpoint, fail-closed): nothing
953
+ // on this lane is metered, so remote usage on it would be unpaid, and the
954
+ // relay cannot bill an arbitrary URL either (it accepts a fixed catalog
955
+ // of provider ids). The refusal points at /class byok — whose providers
956
+ // ARE billed, a handling fee per 1k tokens — or at a local address.
957
+ // There is deliberately no flag that re-opens the remote direct lane.
958
+ // The classic entry form is the positional one
959
+ // /model add <id> <name> <model> <baseURL> [wire]
960
+ // with the key prompted for (masked) right after, or supplied inline
961
+ // /model add <id> <name> <model> <baseURL> [wire] <key>
962
+ // (the scriptable spelling, like /byok-key's second token).
963
+ if (sub === 'add') {
964
+ const parts = splitArgs(args._rest);
965
+ // `sub` itself is the first token of _rest, so drop its own copy.
966
+ const rest = parts[0] === 'add' ? parts.slice(1) : parts;
967
+ // The wire name is optional and only recognised when it is one of the
968
+ // two transports — otherwise that token is the key (so
969
+ // `/model add id name model url sk-…` needs no placeholder).
970
+ let at = 4;
971
+ let wire;
972
+ if (VALID_WIRES.includes(String(rest[at] || '').toLowerCase())) {
973
+ wire = String(rest[at]).toLowerCase();
974
+ at += 1;
975
+ }
976
+ const fields = { id: rest[0], name: rest[1], model: rest[2], baseURL: rest[3], wire };
977
+ if (!fields.id || !fields.model || !fields.baseURL) {
978
+ note(c, 'Usage: /model add <id> <name> <model> <baseURL> [openai|anthropic] [key]');
979
+ note(c, ' e.g. /model add local Llama-3 "meta-llama/Llama-3-70b" http://localhost:8080/v1');
980
+ note(c, ' the base URL must be LOCAL (localhost, 127.0.0.1, a LAN address, *.local, or a dotless host like "ollama").');
981
+ note(c, ' remote providers are billed, so they are not offered here — /class byok with /byok-key <provider> relays them and charges the AEGIS handling fee.');
982
+ note(c, ' the key is prompted for and stored 0600 on this machine — never in config.json.');
983
+ c.render();
984
+ return true;
985
+ }
986
+ const inlineKey = rest[at] || '';
987
+ const store = c.settings && c.settings();
988
+ const res = customModelsCatalog.addCustom({ ...fields, key: null }, store);
989
+ if (res.error) {
990
+ c.push({ role: 'error', text: `couldn't add "${fields.id}": ${res.error}` });
991
+ return true;
992
+ }
993
+ const entry = res.entry;
994
+ let key = inlineKey || '';
995
+ if (!key) {
996
+ note(c, `storing a key for "${entry.id}" — leave it blank to add it later with /model key ${entry.id}.`);
997
+ c.render();
998
+ key = String((await c.readSecret(`${entry.id} key: `)) || '').trim();
999
+ }
1000
+ if (key) {
1001
+ customModelsCatalog.setCustomKey(entry.id, key, store);
1002
+ }
1003
+ note(c, `added "${entry.id}" → ${entry.model} at ${entry.baseURL} (${entry.wire} wire)${key ? '' : ' — no key yet'} — local endpoint, direct and free.`);
1004
+ note(c, key
1005
+ ? `run it with /class custom (then /model ${entry.id}), or /model ${entry.id} while on the custom class.`
1006
+ : `add its key with /model key ${entry.id}, then /class custom runs it.`);
1007
+ c.render();
1008
+ return true;
1009
+ }
1010
+ if (sub === 'key') {
1011
+ const target = splitArgs(args._rest)[1];
1012
+ if (!target) { note(c, 'Usage: /model key <id> — /models lists your custom endpoints.'); c.render(); return true; }
1013
+ const entry = customModelsCatalog.getCustom(target);
1014
+ if (!entry) { note(c, `no custom endpoint "${target}" — /model add registers one.`); c.render(); return true; }
1015
+ const store = c.settings && c.settings();
1016
+ note(c, `storing a key for "${entry.id}" — blank clears it.`);
1017
+ c.render();
1018
+ const key = String((await c.readSecret(`${entry.id} key: `)) || '').trim();
1019
+ if (!key) { note(c, 'nothing saved.'); c.render(); return true; }
1020
+ customModelsCatalog.setCustomKey(entry.id, key, store);
1021
+ note(c, `saved a key for "${entry.id}" on this machine — /class custom runs it.`);
1022
+ c.render();
1023
+ return true;
1024
+ }
1025
+ if (sub === 'remove' || sub === 'rm') {
1026
+ const target = splitArgs(args._rest)[1];
1027
+ if (!target) { note(c, 'Usage: /model remove <id>'); c.render(); return true; }
1028
+ const store = c.settings && c.settings();
1029
+ const { removed } = customModelsCatalog.removeCustom(target, store);
1030
+ if (!removed) { note(c, `no custom endpoint "${target}" — /models lists your endpoints.`); c.render(); return true; }
1031
+ // A pin on the row we just deleted would otherwise outlive its entry and
1032
+ // fail at the next send with "no model … in the catalog".
1033
+ if (String(c.ctx.model || '') === String(target)) {
1034
+ c.ctx.model = null;
1035
+ c.saveConfig({ model: null, currentModelId: null });
1036
+ note(c, `unpinned "${target}" (its catalog entry is gone).`);
1037
+ }
1038
+ note(c, `removed "${target}" and forgot its key.`);
868
1039
  c.render();
869
1040
  return true;
870
1041
  }
@@ -896,8 +1067,7 @@ const COMMANDS = [
896
1067
  // so a pooled id becomes "no key saved for <that id>" at the relay.
897
1068
  // Warn, never refuse: the catalog is cached, and refusing would break a
898
1069
  // pin made against a server that is briefly unreachable.
899
- await loadModels(c);
900
- const models = c.state().models || [];
1070
+ const models = (await loadModels(c)) || [];
901
1071
  if (models.length && !models.some((m) => m.id === id)) {
902
1072
  note(c, byok
903
1073
  ? `"${id}" is not one this machine can relay — a byok id is "<provider>:<model>", and the relay will refuse anything else. /models lists the real ids.`