aegiscode 6.7.7 → 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,7 +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 # your own endpoint, called by aegiscode directly
227
+ /class custom # a LOCAL endpoint of yours (Ollama, llama.cpp, a LAN box), called directly
228
228
  ```
229
229
 
230
230
  A class is *whose credential pays and who talks to the vendor*, not a model.
@@ -236,7 +236,7 @@ restart.
236
236
  |---|---|---|
237
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 |
238
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` | your own base URL, called **directly** by aegiscode — nothing is relayed | your provider direct. No AEGIS fee, no margin, no account balance |
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` |
240
240
 
241
241
  **2. The model id — what to pin.**
242
242
 
@@ -262,7 +262,7 @@ Under `byok` every id is compound — `provider:model`:
262
262
  Under `custom` the id is whatever you named the entry:
263
263
 
264
264
  ```bash
265
- /models # e.g. local-llama, work-gateway
265
+ /models # e.g. local-llama, lan-box
266
266
  /model local-llama
267
267
  ```
268
268
 
@@ -286,27 +286,67 @@ the per-provider mechanics).
286
286
  > **A `byok` turn is single-shot.** The relay takes no `tools` parameter, so the
287
287
  > agentic tool loop is off by construction — no file edits, no shell, no
288
288
  > subagents, no approval cards. `/class` says so rather than letting you discover
289
- > it mid-task. **`custom` does not have this limit** — aegiscode calls your
289
+ > it mid-task. **`custom` does not have this limit** — aegiscode calls the local
290
290
  > endpoint itself, so the full tool loop works normally.
291
291
 
292
- ## Custom models — your endpoint, called directly
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
+ ```
293
314
 
294
- `/model add` teaches aegiscode about an endpoint AEGIS never sees. There is no
295
- relay, no handling fee and no margin: the request goes straight from your machine
296
- to the base URL you gave, with the key you gave.
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.
297
319
 
298
320
  ```bash
299
321
  /model add local-llama "Local Llama" llama-3.3-70b http://localhost:11434/v1
300
- /model add work-gw "Work gateway" gpt-4o https://gw.corp/v1 openai
322
+ /model add lan-box "LAN box" qwen3:32b http://192.168.1.40:8080/v1
301
323
  /model key local-llama # set or replace the key later (prompted, masked)
302
324
  /class custom # route turns through these
303
325
  /model local-llama # pin one
304
326
  /model remove local-llama # drop the entry and its key
305
327
  ```
306
328
 
307
- The wire protocol is detected from the base URL — `anthropic.com` gets the
308
- Messages API, everything else the OpenAI-compatible one — or you can pass
309
- `openai` / `anthropic` explicitly to override it.
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.
310
350
 
311
351
  Where things are stored, and why it is split:
312
352
 
@@ -425,7 +465,7 @@ echo "why is the sky blue" | aegiscode -p -
425
465
  /class aegis # back to the pool
426
466
 
427
467
  /model add local-llama "Local Llama" llama-3.3-70b http://localhost:11434/v1
428
- /class custom # or call your own endpoint directly
468
+ /class custom # or call a LOCAL endpoint directly (remote URLs are refused — use byok)
429
469
  ```
430
470
 
431
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.7",
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",
@@ -68,6 +68,15 @@ const FILES = [
68
68
  // base URL + key is called directly with the full tool loop — so this file
69
69
  // must ship. Pure node builtins (fetch), stages cleanly.
70
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',
71
80
  // The provider-config store: one row per provider (base URL + key), and the
72
81
  // row the 'byok' class reads for a per-provider key. The CLI now selects that
73
82
  // class (src/engine.js), so it needs the same store the desktop writes —
package/src/app.js CHANGED
@@ -1082,7 +1082,23 @@ function createApp(options = {}) {
1082
1082
  // dropped, live ids only (see models.js pickerEntries).
1083
1083
  // Whichever class is live decides what is pinnable — the pooled ids the
1084
1084
  // server advertises, or the `provider:model` ids this machine can relay.
1085
- 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
+ ),
1086
1102
  commands: visibleCommands(),
1087
1103
  transcript: transcript.slice(),
1088
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 {
@@ -159,16 +160,29 @@ const done = (c, text) => c.push({ role: 'done', text });
159
160
  const shortCwd = () => process.cwd().split('/').filter(Boolean).pop() || '~';
160
161
 
161
162
  /**
162
- * Refresh the pinnable-model list on the session context before reading it.
163
- * `c.loadModels()` (owned by the app/chatflow) fetches from the server and
164
- * records the result on `c.state().models`; it is best-effort — offline it
165
- * rejects, and the caller falls through to the honest empty note rather than
166
- * 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}>>}
167
179
  */
168
180
  async function loadModels(c) {
169
181
  try {
170
- await c.loadModels();
171
- } catch {}
182
+ return (await c.loadModels()) || [];
183
+ } catch {
184
+ return [];
185
+ }
172
186
  }
173
187
 
174
188
  /**
@@ -330,10 +344,12 @@ async function applyAccountKey(c, raw, { label = 'AEGIS API key' } = {}) {
330
344
  const acct = (res.account && (res.account.email || res.account.plan)) || null;
331
345
  done(c, `AEGIS key saved to ${res.path}${acct ? ` — signed in as ${acct}` : ' and verified'}`);
332
346
  // The catalog is key-gated, so a freshly authenticated session should offer
333
- // /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.
334
351
  try {
335
- await c.loadModels({ force: true });
336
- const n = (c.state().models || []).length;
352
+ const n = pickerEntries(await loadModels(c)).length;
337
353
  if (n) note(c, `${n} pinnable model${n === 1 ? '' : 's'} available — /model to pin one`);
338
354
  } catch {}
339
355
  return res;
@@ -848,32 +864,44 @@ const COMMANDS = [
848
864
  // will actually take (app.js's buildState().models is class-scoped too).
849
865
  const cls = (c.ctx && c.ctx.modelClass) || 'aegis';
850
866
  const byok = cls === 'byok';
867
+ const custom = cls === 'custom';
851
868
  // The sub-command token, lower-cased: `add` / `key` / `remove` are the
852
869
  // custom-endpoint catalog's verbs. A model id is never one of these in
853
870
  // practice, and `list` already shadows a real id the same way.
854
871
  const sub = id.toLowerCase();
855
872
  if (!id) {
856
873
  note(c, `model: ${c.ctx.model || 'server default'}`);
857
- // Populate the picker from the server first — app.js's state().models
858
- // is empty until loadModels() has run, so an unguarded read renders an
859
- // empty picker whose Enter does nothing.
860
- await loadModels(c);
861
- 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));
862
886
  if (!models.length) {
863
887
  // Say why, and what unblocks it: an unreachable catalog is almost
864
888
  // always a missing key or no network, and "no models advertised"
865
889
  // read as "the platform has none" rather than "this client could not
866
890
  // ask". On byok "no models" has a third cause — the relay is fine and
867
891
  // the account is fine, this machine simply holds no provider key yet,
868
- // which is exactly what /byok-key fixes.
869
- note(c, byok
870
- ? 'No relayable models — this machine holds no provider key yet. Save one with /byok-key <provider>, then retry /model.'
871
- : c.state().online
872
- ? 'Could not read the model catalog (offline, or the server refused it) — /models retries.'
873
- : // The key travels in the environment only (client/aegis.js reads
874
- // AEGIS_API_KEY); /login is an unavailable command here, so
875
- // pointing at it would send the user to a refusal.
876
- '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.');
877
905
  c.render();
878
906
  return true;
879
907
  }
@@ -881,35 +909,52 @@ const COMMANDS = [
881
909
  // from its own default with no error. Say so where the pin is visible
882
910
  // rather than letting the reply look like the pinned model. On byok the
883
911
  // failure mode is different and louder (the relay 400s on a provider it
884
- // 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.
885
914
  if (c.ctx.model && !models.some((m) => m.id === c.ctx.model)) {
886
- note(c, byok
887
- ? `pinned model "${c.ctx.model}" is not one this machine can relay — pick from the list below.`
888
- : `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.`);
889
920
  }
890
- // The overlay's own copy promises /model add|remove (overlays.js, a
891
- // separate workstream); this build refuses both, so say here how a
892
- // model is actually selected.
893
- note(c, byok
894
- ? '/model <id> pins one for this session; /models lists what this machine can relay.'
895
- : '/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.');
896
930
  // `cls` rides on the overlay so the picker's title and subtitle render
897
931
  // for the class that opened it, even if /class moves while it is open.
898
932
  c.openOverlay({ type: 'model', items: models, sel: 0, current: c.ctx.model, cls });
899
933
  return true;
900
934
  }
901
935
  if (id === 'list') {
902
- await loadModels(c);
903
- 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));
904
939
  if (!models.length) note(c, 'No pinnable models advertised — /models lists the server\'s ids.');
905
940
  else panel(c, panels.buildModelList(c.ctx.model, models, c.ctx));
906
941
  c.render();
907
942
  return true;
908
943
  }
909
- // The /model add catalog — the aegiscodex-dev concept ported in. A user
910
- // registers their own endpoint (own base URL, own model string, own key)
911
- // and the CLI calls it DIRECTLY through the desktop transport, the full
912
- // tool loop and all: no pooled route, no BYOK relay, no fee or margin.
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.
913
958
  // The classic entry form is the positional one
914
959
  // /model add <id> <name> <model> <baseURL> [wire]
915
960
  // with the key prompted for (masked) right after, or supplied inline
@@ -932,6 +977,8 @@ const COMMANDS = [
932
977
  if (!fields.id || !fields.model || !fields.baseURL) {
933
978
  note(c, 'Usage: /model add <id> <name> <model> <baseURL> [openai|anthropic] [key]');
934
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.');
935
982
  note(c, ' the key is prompted for and stored 0600 on this machine — never in config.json.');
936
983
  c.render();
937
984
  return true;
@@ -953,7 +1000,7 @@ const COMMANDS = [
953
1000
  if (key) {
954
1001
  customModelsCatalog.setCustomKey(entry.id, key, store);
955
1002
  }
956
- note(c, `added "${entry.id}" → ${entry.model} at ${entry.baseURL} (${entry.wire} wire)${key ? '' : ' — no key yet'}.`);
1003
+ note(c, `added "${entry.id}" → ${entry.model} at ${entry.baseURL} (${entry.wire} wire)${key ? '' : ' — no key yet'} — local endpoint, direct and free.`);
957
1004
  note(c, key
958
1005
  ? `run it with /class custom (then /model ${entry.id}), or /model ${entry.id} while on the custom class.`
959
1006
  : `add its key with /model key ${entry.id}, then /class custom runs it.`);
@@ -1020,8 +1067,7 @@ const COMMANDS = [
1020
1067
  // so a pooled id becomes "no key saved for <that id>" at the relay.
1021
1068
  // Warn, never refuse: the catalog is cached, and refusing would break a
1022
1069
  // pin made against a server that is briefly unreachable.
1023
- await loadModels(c);
1024
- const models = c.state().models || [];
1070
+ const models = (await loadModels(c)) || [];
1025
1071
  if (models.length && !models.some((m) => m.id === id)) {
1026
1072
  note(c, byok
1027
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.`
package/src/config.js CHANGED
@@ -74,14 +74,18 @@ const DEFAULT_CONFIG = {
74
74
  models: null,
75
75
  currentModelId: null,
76
76
  // The named custom-model catalog behind the `custom` class — the
77
- // aegiscodex-dev `/model add` concept: each entry names an endpoint the user
78
- // brings themselves (own base URL + own key), called DIRECTLY through the
79
- // desktop transport (providers.openaiCompatible / anthropicMessages), tools
80
- // and all, never through the pooled route or the BYOK relay. Only the
81
- // non-secret metadata lives here; the key is in the 0600 settings store under
82
- // `custom:<id>` (engine.js), never in this file (config.json is not 0600 and
83
- // participates in cloud sync). Shape: [{ id, name, model, baseURL, wire }],
84
- // wire ∈ {'openai','anthropic'}.
77
+ // aegiscodex-dev `/model add` concept: each entry names a LOCAL endpoint the
78
+ // user brings themselves (own base URL + own key — llama.cpp, Ollama, a LAN
79
+ // box), called DIRECTLY through the desktop transport
80
+ // (providers.openaiCompatible / anthropicMessages), tools and all, never
81
+ // through the pooled route or the BYOK relay. Free of AEGIS fee and margin
82
+ // for exactly that reason, which is why the add path and the dispatch gate
83
+ // both refuse a remote base URL: nothing on this lane is metered, so remote
84
+ // usage here would be unpaid. Remote providers are billed on /class byok.
85
+ // Only the non-secret metadata lives here; the key is in the 0600 settings
86
+ // store under `custom:<id>` (engine.js), never in this file (config.json is
87
+ // not 0600 and participates in cloud sync). Shape: [{ id, name, model,
88
+ // baseURL, wire }], wire ∈ {'openai','anthropic'}.
85
89
  customModels: [],
86
90
  // `null` = no effort pinned, i.e. "auto": each turn is sized by the server
87
91
  // from the ask itself (aegis1 services/pool_brain.py estimate_effort). The
@@ -8,8 +8,23 @@
8
8
  * model string, their own API key — and the turn is called DIRECTLY through the
9
9
  * desktop transport (desktop/lib/local/providers.js openaiCompatible /
10
10
  * anthropicMessages), the full agent loop and all, never through the pooled
11
- * route and never through the BYOK relay. There is no AEGIS margin or handling
12
- * fee on this lane at all: the request never touches aegiscloud.org.
11
+ * route and never through the BYOK relay. That lane is free of AEGIS margin and
12
+ * handling fee for exactly one reason: the request never touches
13
+ * aegiscloud.org — and that is only defensible for an endpoint ON THIS MACHINE.
14
+ *
15
+ * LOCAL ENDPOINTS ONLY (the policy this module enforces, see isLocalEndpoint).
16
+ * Every class that can bill does: `aegis` is the pooled route, `byok` is the
17
+ * stateless relay (services/pricing.price_byok_call → token_bank.charge_byok,
18
+ * the AEGIS handling fee). The direct transport bills nothing, so the ONLY
19
+ * unpaid-by-design usage it may carry is a local endpoint, where there is no
20
+ * vendor to pay in the first place. A remote base URL has nothing to bill
21
+ * against — the relay accepts a fixed catalog of provider ids
22
+ * (services/nexus_provider/catalog.py, key read from X-Provider-Key), so an
23
+ * arbitrary remote URL cannot be metered there either — and it is therefore
24
+ * REFUSED here, with a pointer at /class byok (billed) or a local address.
25
+ * Remote endpoints are not offered on this lane at all; there is deliberately
26
+ * no flag or env var that re-opens it, because such a flag would be a billing
27
+ * bypass.
13
28
  *
14
29
  * Split storage, on purpose:
15
30
  * · metadata (id, name, model, baseURL, wire) → config.json `customModels`.
@@ -24,19 +39,39 @@
24
39
  */
25
40
 
26
41
  const { loadConfig, updateConfig } = require('./config.js');
42
+ // The direct-dial policy, from the ONE implementation both hosts share
43
+ // (desktop/lib/local/endpoints.js). Resolved by path rather than required
44
+ // relatively because the CLI consumes desktop/lib/ in two layouts — beside cli/
45
+ // in the repo, and under cli/vendor/ in an installed package (src/deps.js
46
+ // documents both); sharedpaths.js is that resolution with no side effects, and
47
+ // it exists separately precisely so this module can reach the policy WITHOUT
48
+ // pulling in the engine (custommodels -> deps -> engine -> custommodels is a
49
+ // require cycle, and the cycle resolves to a half-built exports object).
50
+ //
51
+ // One implementation on purpose: a second copy is how the desktop would keep
52
+ // refusing remote endpoints while the terminal quietly served them — the exact
53
+ // drift that produces an unpaid turn.
54
+ const { hostOf, isLocalEndpoint, remoteRefusal } = require(
55
+ require('./sharedpaths.js').resolveShared(require('node:path').join('desktop', 'lib', 'local', 'endpoints.js'))
56
+ );
27
57
 
28
58
  /** The settings-store row a custom model's key lives in. */
29
59
  function customNamespace(id) {
30
60
  return `custom:${id}`;
31
61
  }
32
62
 
33
- /** Host of a URL, lower-cased, or '' if it does not parse. */
34
- function hostOf(url) {
35
- try {
36
- return new URL(String(url)).host.toLowerCase();
37
- } catch {
38
- return '';
39
- }
63
+ // `hostOf`, `isLocalEndpoint` and `remoteRefusal` come from the shared policy
64
+ // module above (see the require for why it is reached by path). The CLI's
65
+ // refusal text is that module's, plus the one thing only the CLI can name: the
66
+ // command that moves the user onto the billed lane. Previously this file held
67
+ // its own copy of all three, which is how the two hosts would have drifted.
68
+ const CLI_REMOTE_HINT =
69
+ 'Remote providers are billed, so use /class byok with /byok-key <provider> ' +
70
+ '(the AEGIS relay charges the handling fee there), or point this entry at a local address.';
71
+
72
+ /** The refusal a remote custom endpoint gets here, in the CLI's own words. */
73
+ function customRefusal(baseURL) {
74
+ return remoteRefusal(baseURL, { subject: 'custom endpoints', hint: CLI_REMOTE_HINT });
40
75
  }
41
76
 
42
77
  /**
@@ -63,6 +98,12 @@ const VALID_WIRES = Object.freeze(['openai', 'anthropic']);
63
98
  * to `/model <id>`. A base URL is required and must be http(s) — the transport
64
99
  * POSTs to `${baseURL}/…`, so a bare host or a typo becomes an unroutable call
65
100
  * later instead of a clear refusal now.
101
+ *
102
+ * The last gate is the policy one: a base URL that is not local to this machine
103
+ * is refused (isLocalEndpoint). A custom entry is the only thing that reaches
104
+ * the direct transport, and the direct transport bills nothing, so a remote URL
105
+ * here would be unpaid non-local usage. The refusal names /class byok, which is
106
+ * billed, and a local address, which is free.
66
107
  */
67
108
  function normalizeEntry({ id, name, model, baseURL, wire } = {}) {
68
109
  const cleanId = String(id == null ? '' : id).trim();
@@ -82,6 +123,8 @@ function normalizeEntry({ id, name, model, baseURL, wire } = {}) {
82
123
  }
83
124
  if (!cleanWire) cleanWire = inferWire(cleanBase);
84
125
 
126
+ if (!isLocalEndpoint(cleanBase)) return { error: customRefusal(cleanBase) };
127
+
85
128
  const cleanName = String(name == null ? '' : name).trim() || cleanId;
86
129
  return { entry: { id: cleanId, name: cleanName, model: cleanModel, baseURL: cleanBase, wire: cleanWire } };
87
130
  }
@@ -99,18 +142,28 @@ function getCustom(id) {
99
142
  }
100
143
 
101
144
  /**
102
- * The catalog as pickable model rows ({ id, label, note, configured }) — the
103
- * shape /models and the alt+p picker consume. `configured` reflects whether a
104
- * key is saved for the row, so the list can say which entries can actually run.
145
+ * The catalog as pickable model rows ({ id, label, note, configured, local }) —
146
+ * the shape /models, the picker and the engine share. `configured` reflects
147
+ * whether a key is saved for the row, so the list can say which entries can
148
+ * actually run.
149
+ *
150
+ * `local` is recomputed from the base URL on every read rather than read off
151
+ * the stored row: a config.json written before this lane closed can still hold
152
+ * a remote entry, and it must classify as remote (and be refused by the
153
+ * dispatch gate) rather than inherit a stale "local: true" flag.
105
154
  */
106
155
  function listCustomModels(settings) {
107
- return rawCatalog().map((e) => ({
108
- id: e.id,
109
- label: e.name || e.id,
110
- note: `${e.model} · ${hostOf(e.baseURL) || e.baseURL} · ${e.wire}`,
111
- configured: hasKey(settings, e.id),
112
- wire: e.wire,
113
- }));
156
+ return rawCatalog().map((e) => {
157
+ const local = isLocalEndpoint(e.baseURL);
158
+ return {
159
+ id: e.id,
160
+ label: e.name || e.id,
161
+ note: `${e.model} · ${hostOf(e.baseURL) || e.baseURL} · ${e.wire}${local ? '' : ' · REMOTE — refused on this lane, use /class byok'}`,
162
+ configured: hasKey(settings, e.id),
163
+ wire: e.wire,
164
+ local,
165
+ };
166
+ });
114
167
  }
115
168
 
116
169
  /** Whether a key is stored for this custom id. */
@@ -165,9 +218,12 @@ function removeCustom(id, settings) {
165
218
  /**
166
219
  * Resolve a pinned custom id to everything the dispatch needs: the transport
167
220
  * class it maps to ('anthropic' | 'openai-compat'), its base URL, its wire
168
- * model string, and its key. Null when the id is not in the catalog. The key
169
- * is read live from the settings store, never cached, so a key saved after the
170
- * engine was constructed is picked up on the very next turn.
221
+ * model string, its key, and whether the endpoint is local. Null when the id is
222
+ * not in the catalog. The key is read live from the settings store, never
223
+ * cached, so a key saved after the engine was constructed is picked up on the
224
+ * very next turn. `local` is likewise computed live from the base URL, so the
225
+ * engine's gate cannot be fooled by a row that was stored under the old,
226
+ * open-to-remote policy.
171
227
  */
172
228
  function resolveCustom(id, settings) {
173
229
  const entry = getCustom(id);
@@ -180,12 +236,16 @@ function resolveCustom(id, settings) {
180
236
  key: key || null,
181
237
  wire: entry.wire,
182
238
  id: entry.id,
239
+ local: isLocalEndpoint(entry.baseURL),
183
240
  };
184
241
  }
185
242
 
186
243
  module.exports = {
187
244
  customNamespace,
188
245
  inferWire,
246
+ isLocalEndpoint,
247
+ remoteRefusal,
248
+ customRefusal,
189
249
  normalizeEntry,
190
250
  getCustom,
191
251
  listCustomModels,
package/src/deps.js CHANGED
@@ -18,30 +18,15 @@
18
18
  * hosts would drift.
19
19
  */
20
20
 
21
- const fs = require('node:fs');
22
21
  const path = require('node:path');
23
22
 
24
- function roots() {
25
- const srcDir = __dirname; // <root>/cli/src
26
- const cliDir = path.join(srcDir, '..');
27
- return [
28
- path.join(srcDir, '..', '..'), // repo root (in-repo layout)
29
- path.join(cliDir, 'vendor'), // staged tree (published layout)
30
- ];
31
- }
32
-
33
- /** Resolve a repo-relative module path against whichever root has it. */
34
- function resolveShared(relPath) {
35
- for (const root of roots()) {
36
- const candidate = path.join(root, relPath);
37
- if (fs.existsSync(candidate)) return candidate;
38
- }
39
- throw new Error(
40
- `aegiscode: cannot find ${relPath}. Expected it beside cli/ (in the repo) or ` +
41
- 'under cli/vendor/ (installed package). Reinstall the package, or run ' +
42
- '`node scripts/predist.mjs` from cli/ if this is a source checkout.'
43
- );
44
- }
23
+ // Where the shared modules live, WITHOUT loading any of them. Kept in its own
24
+ // module because this file eagerly requires everything it resolves, which makes
25
+ // it unusable from inside the engine's own dependency graph (engine.js ->
26
+ // custommodels.js -> deps.js -> engine.js is a cycle, and the cycle resolves to
27
+ // `createLocalEngine === undefined`). src/custommodels.js needs to locate one
28
+ // shared file and nothing more, so it goes through sharedpaths.js instead.
29
+ const { roots, resolveShared } = require('./sharedpaths.js');
45
30
 
46
31
  const clientPath = resolveShared(path.join('client', 'aegis.js'));
47
32
  const toolsPath = resolveShared(path.join('mcp', 'tools.js'));
@@ -84,7 +69,10 @@ const autonomousPath = resolveShared(path.join('desktop', 'lib', 'local', 'auton
84
69
  // The direct-provider transport (openaiCompatible + anthropicMessages). The
85
70
  // desktop injects it into createLocalEngine for its custom-endpoint classes;
86
71
  // the CLI injects the same real module for its `custom` class (the /model add
87
- // catalog) rather than the throwing stub it shipped before.
72
+ // catalog) rather than the throwing stub it shipped before. That catalog is
73
+ // LOCAL-ONLY (see custommodels.js isLocalEndpoint): the free direct lane may
74
+ // only carry an endpoint on this machine, and the engine's gate refuses a
75
+ // remote base URL before this module is ever called.
88
76
  const providersPath = resolveShared(path.join('desktop', 'lib', 'local', 'providers.js'));
89
77
 
90
78
  const { createClient } = require(clientPath);
package/src/engine.js CHANGED
@@ -18,11 +18,17 @@
18
18
  * free ride — and why the key must never be handed to a direct provider
19
19
  * call from here.
20
20
  *
21
- * Only those two: `cls` is the engine's own class selector, and the two local
22
- * classes (ollama, custom endpoints) stay stubs that throw if the engine ever
23
- * calls them. They need a settings/endpoint surface this host does not offer,
24
- * and a stub is proof that a code path meant for another host never silently
25
- * runs here.
21
+ * custom LOCAL endpoints only. The `custom` class (the /model add catalog)
22
+ * reaches the direct provider transport — the free lane — and the
23
+ * catalog refuses every base URL that is not on this machine, so the
24
+ * only usage that never touches aegiscloud.org is usage with no vendor
25
+ * behind it (see custommodels.js isLocalEndpoint). A remote entry is
26
+ * refused in-process before any network call and pointed at /class
27
+ * byok, which bills the AEGIS handling fee.
28
+ *
29
+ * Ollama stays a stub that throws if the engine ever calls it: it needs an
30
+ * endpoint surface this host does not offer, and a stub is proof that a code
31
+ * path meant for another host never silently runs here.
26
32
  *
27
33
  * ── the key store ───────────────────────────────────────────────────────────
28
34
  *
@@ -44,11 +50,16 @@ const VERSION = require('../package.json').version;
44
50
 
45
51
  /**
46
52
  * The classes this host can actually run (see the docstring above).
47
- * aegis — the pooled route (account key pays, pool picks the provider).
53
+ * aegis — the pooled route (account key pays, pool picks the provider; bills).
48
54
  * byok — the BYOK relay (your provider key, AEGIS bills a handling fee).
49
- * custom — the /model add catalog: your own base URL + key, called DIRECTLY
55
+ * custom — the /model add catalog, LOCAL endpoints only: your own base URL +
56
+ * key on this machine (llama.cpp, Ollama, a LAN box), called DIRECTLY
50
57
  * through the desktop transport with the full tool loop, never
51
- * touching aegiscloud.org (no margin, no fee).
58
+ * touching aegiscloud.org. Free of AEGIS fee and margin for exactly
59
+ * that reason, which is why a remote base URL is refused here: no
60
+ * other class may reach the direct transport, and nothing on this
61
+ * lane is metered, so remote usage on it would be unpaid. Remote
62
+ * providers go through /class byok instead, where the relay bills.
52
63
  */
53
64
  const HOST_CLASSES = Object.freeze(['aegis', 'byok', 'custom']);
54
65
 
@@ -59,7 +70,7 @@ const DEFAULT_CLASS = 'aegis';
59
70
  const CLASS_LABELS = Object.freeze({
60
71
  aegis: 'AEGIS Cloud (pooled)',
61
72
  byok: 'Bring your own key (relayed, billed)',
62
- custom: 'Custom endpoint (your key, direct)',
73
+ custom: 'Custom endpoint (local only — free, direct)',
63
74
  });
64
75
 
65
76
  function unsupported(label) {
@@ -95,10 +106,12 @@ function createEngine({ client, getConfirmMode, getClass, settings: injectedSett
95
106
  chat: unsupported('Ollama'),
96
107
  },
97
108
  // The real direct-provider transport — no longer a throwing stub. The
98
- // `custom` class (the /model add catalog) rewrites a turn to the
99
- // 'openai-compat' / 'anthropic' class the desktop engine already drives
100
- // through exactly these two functions, so a user's own endpoint gets the
101
- // same tool loop the pooled class does.
109
+ // `custom` class (the /model add catalog, LOCAL endpoints only) rewrites a
110
+ // turn to the 'openai-compat' / 'anthropic' class the desktop engine
111
+ // already drives through exactly these two functions, so a local endpoint
112
+ // gets the same tool loop the pooled class does. Nothing else in this host
113
+ // reaches them: prepareCustom's local-only gate is the only door, and it
114
+ // throws for a remote base URL before the call.
102
115
  providers: {
103
116
  anthropicMessages: providers.anthropicMessages,
104
117
  openaiCompatible: providers.openaiCompatible,
@@ -127,6 +140,14 @@ function createEngine({ client, getConfirmMode, getClass, settings: injectedSett
127
140
  * dispatch reads), and the payload's class + model are set to that wire class
128
141
  * and the entry's real model string. Throws a clear, in-process error rather
129
142
  * than shipping `model: undefined` or an empty base URL upstream.
143
+ *
144
+ * The local-only gate is the first thing after the catalog lookup, and it
145
+ * runs BEFORE any network call, before the key check and before the
146
+ * just-in-time settings write: a remote entry throws here, so the direct
147
+ * provider transport below is never reached with one and there is no
148
+ * fall-through path to it. Remote providers are billed, and nothing on this
149
+ * lane is metered, so the refusal points at /class byok (billed) and at a
150
+ * local address (free).
130
151
  */
131
152
  function prepareCustom(payload) {
132
153
  const modelId = payload && payload.model;
@@ -140,6 +161,11 @@ function createEngine({ client, getConfirmMode, getClass, settings: injectedSett
140
161
  err.status = 400;
141
162
  throw err;
142
163
  }
164
+ if (!resolved.local) {
165
+ const err = new Error(custom.customRefusal(resolved.baseURL));
166
+ err.status = 400;
167
+ throw err;
168
+ }
143
169
  if (resolved.wire === 'anthropic' && !resolved.key) {
144
170
  const err = new Error(
145
171
  `custom: "${resolved.id}" is an Anthropic-style endpoint and needs a key — /model key ${resolved.id}.`
@@ -0,0 +1,53 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * WHERE the CLI's shared modules are, with no side effects.
5
+ *
6
+ * This is `deps.js`'s path resolution split into its own module, and the split
7
+ * is load-bearing rather than cosmetic. `deps.js` eagerly requires everything
8
+ * it resolves — the engine, the tool registry, the client — so a module that
9
+ * only needs to *locate* one shared file cannot require deps.js: the CLI's
10
+ * engine requires `src/custommodels.js`, so `custommodels.js -> deps.js ->
11
+ * engine.js` would be a require cycle, and the cycle would hand one of them a
12
+ * half-built exports object (`createLocalEngine === undefined`) at load time.
13
+ *
14
+ * So: paths here, code in deps.js. `custommodels.js` resolves the shared
15
+ * endpoint policy (desktop/lib/local/endpoints.js) through this module and
16
+ * requires just that file, which needs nothing but node builtins.
17
+ *
18
+ * Two layouts must work, exactly as deps.js documents:
19
+ *
20
+ * in-repo <repo>/cli/src/sharedpaths.js -> <repo>/desktop/lib/local/...
21
+ * npm <pkg>/src/sharedpaths.js -> <pkg>/vendor/desktop/lib/...
22
+ *
23
+ * Resolution is by existence, and a missing module is a loud error rather than
24
+ * a silent fallback to a second copy: duplicate implementations are how the
25
+ * desktop and the terminal would drift apart.
26
+ */
27
+
28
+ const fs = require('node:fs');
29
+ const path = require('node:path');
30
+
31
+ function roots() {
32
+ const srcDir = __dirname; // <root>/cli/src
33
+ const cliDir = path.join(srcDir, '..');
34
+ return [
35
+ path.join(srcDir, '..', '..'), // repo root (in-repo layout)
36
+ path.join(cliDir, 'vendor'), // staged tree (published layout)
37
+ ];
38
+ }
39
+
40
+ /** Resolve a repo-relative module path against whichever root has it. */
41
+ function resolveShared(relPath) {
42
+ for (const root of roots()) {
43
+ const candidate = path.join(root, relPath);
44
+ if (fs.existsSync(candidate)) return candidate;
45
+ }
46
+ throw new Error(
47
+ `aegiscode: cannot find ${relPath}. Expected it beside cli/ (in the repo) or ` +
48
+ 'under cli/vendor/ (installed package). Reinstall the package, or run ' +
49
+ '`node scripts/predist.mjs` from cli/ if this is a source checkout.'
50
+ );
51
+ }
52
+
53
+ module.exports = { roots, resolveShared };
@@ -0,0 +1,228 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * The direct-dial policy: which base URLs may reach a provider transport, and
5
+ * why that is the only free lane left.
6
+ *
7
+ * Both hosts that can talk to a user-supplied endpoint — the desktop app
8
+ * (settings pane → 'openai-compat' / 'anthropic' classes) and the CLI
9
+ * (src/engine.js prepareCustom, the `/model add` catalog) — share THIS file
10
+ * rather than a copy each. The CLI vendors `desktop/lib/local/` wholesale and
11
+ * resolves this module through src/sharedpaths.js, so the two hosts cannot
12
+ * drift apart about what "local" means or which error a remote URL gets. A
13
+ * second implementation is how one host would keep billing correctly while the
14
+ * other quietly served unpaid traffic.
15
+ *
16
+ * The rule: every lane that can bill does. `aegis` is the pooled route (the
17
+ * account key is attached and the pool takes its margin); `byok` is the relay
18
+ * (`services/pricing.price_byok_call` → `token_bank.charge_byok`, the AEGIS
19
+ * handling fee, charged against the account resolved from `X-AEGIS-Key`). The
20
+ * provider transports in providers.js bill NOTHING — they are a direct dial to
21
+ * whoever owns the URL — so the only usage they may carry is an endpoint on
22
+ * this machine, where there is no vendor to pay in the first place.
23
+ *
24
+ * That is why a remote base URL is refused rather than metered: the relay
25
+ * accepts a fixed catalog of provider ids (`services/nexus_provider/catalog.py`,
26
+ * upstream key read from `X-Provider-Key`), so an arbitrary remote URL has
27
+ * nothing to be billed against even if a client wanted to invoice it. Remote
28
+ * providers belong on BYOK, which bills. There is deliberately no flag or env
29
+ * var that re-opens the direct lane for a remote URL, because such a flag would
30
+ * be a billing bypass.
31
+ *
32
+ * Where the gate lives — the seams, not the transport:
33
+ * · desktop/lib/settings.js `set()` refuses to STORE a remote base URL, so
34
+ * the unusable configuration cannot be created.
35
+ * · desktop/lib/local/engine.js `chat()` refuses to DIAL one before any
36
+ * transport call (a row hand-edited into the
37
+ * settings file, or written before this policy
38
+ * existed, still cannot be used).
39
+ * · cli/src/custommodels.js refuses one at `/model add` and again at
40
+ * dispatch, for the same two reasons.
41
+ * providers.js itself stays policy-free: it is a wire-format function, and
42
+ * pinning the policy there would make it unreachable for the tests that check
43
+ * URL building. Same split the BYOK balance gate uses — the relay owns the
44
+ * decision, the client refuses to send.
45
+ */
46
+
47
+ /** Host of a URL, lower-cased, or '' if it does not parse. */
48
+ function hostOf(url) {
49
+ try {
50
+ return new URL(String(url)).host.toLowerCase();
51
+ } catch {
52
+ return '';
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Whether a base URL addresses an endpoint on this machine — the gate that
58
+ * decides whether the free direct lane is available at all.
59
+ *
60
+ * True for: loopback (localhost, `*.localhost`, 127.0.0.0/8, `::1`), RFC1918
61
+ * private ranges (10/8, 172.16/12, 192.168/16), IPv6 unique-local fc00::/7,
62
+ * link-local (169.254/16, fe80::/10), the reserved local suffixes `.local`,
63
+ * `.internal`, `.lan`, and a bare dotless hostname (`ollama`, `gpu-box` — it
64
+ * can only resolve through this machine's own resolver).
65
+ *
66
+ * FAIL CLOSED: anything that does not parse, carries no host, is a public
67
+ * address or name, or is merely ambiguous is NOT local. That direction is the
68
+ * whole point — a false "local" is an unpaid turn, a false "remote" is a
69
+ * refusal the user can fix by pointing at a local address or by moving to the
70
+ * billed lane, which is the outcome we want in a tie.
71
+ */
72
+ function isLocalEndpoint(url) {
73
+ let host = '';
74
+ let scheme = '';
75
+ try {
76
+ const parsed = new URL(String(url == null ? '' : url));
77
+ host = parsed.hostname.toLowerCase();
78
+ scheme = parsed.protocol.toLowerCase();
79
+ } catch {
80
+ return false;
81
+ }
82
+ // Only a base URL a transport can actually dial. The transports in
83
+ // providers.js append '/chat/completions' and fetch it, so anything that is
84
+ // not http(s) — or has no scheme at all — is not an endpoint, and is refused
85
+ // by the same fail-closed rule as an unparseable value. Checked before the
86
+ // host, so `ftp://box.local` cannot ride the local suffix to a pass.
87
+ if (scheme !== 'http:' && scheme !== 'https:') return false;
88
+ if (!host) return false;
89
+ // WHATWG keeps the brackets on an IPv6 hostname; strip them so one spelling
90
+ // covers both `[::1]` and a bare `::1`.
91
+ if (host.startsWith('[') && host.endsWith(']')) host = host.slice(1, -1);
92
+ if (!host || /[\s/\\@]/.test(host)) return false;
93
+
94
+ // Loopback by name, plus the reserved local suffixes. `.local`/`.internal`/
95
+ // `.lan` are the mDNS / split-DNS names an on-box service answers to. The
96
+ // suffix must END the name: `example.local.evil.com` is somebody else's host.
97
+ if (host === 'localhost' || host.endsWith('.localhost')) return true;
98
+ if (/\.(local|internal|lan)$/.test(host)) return true;
99
+
100
+ // IPv6 literals.
101
+ if (host.includes(':')) {
102
+ if (host === '::1' || host === '0:0:0:0:0:0:0:1') return true; // loopback
103
+ if (/^f[cd][0-9a-f]{2}:/.test(host)) return true; // fc00::/7 unique-local
104
+ if (/^fe[89ab][0-9a-f]:/.test(host)) return true; // fe80::/10 link-local
105
+ return false;
106
+ }
107
+
108
+ // IPv4 literals.
109
+ const quad = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
110
+ if (quad) {
111
+ const o = quad.slice(1).map(Number);
112
+ if (o.some((n) => n > 255)) return false; // not an address, and not local
113
+ const [a, b] = o;
114
+ if (a === 127) return true; // 127.0.0.0/8 loopback
115
+ if (a === 10) return true; // 10.0.0.0/8
116
+ if (a === 172 && b >= 16 && b <= 31) return true; // 172.16.0.0/12
117
+ if (a === 192 && b === 168) return true; // 192.168.0.0/16
118
+ if (a === 169 && b === 254) return true; // 169.254.0.0/16 link-local
119
+ return false; // a real, routable address — remote, and billed
120
+ }
121
+
122
+ // A bare, dotless hostname is local by convention (`ollama`, `llama-box`):
123
+ // it can only resolve through this machine's own resolver or /etc/hosts.
124
+ // Anything with a dot is a DNS name for somebody else's machine.
125
+ return !host.includes('.');
126
+ }
127
+
128
+ /** What IS allowed here, in one sentence, shared by both hosts' refusals. */
129
+ const ALLOWED_HINT =
130
+ 'Allowed: localhost, 127.0.0.1, a private/LAN address (10.x, 172.16-31.x, 192.168.x), ' +
131
+ '*.local/.internal/.lan, or a dotless host like "ollama".';
132
+
133
+ /**
134
+ * The refusal a non-local base URL gets, in the words the user needs in order
135
+ * to act: it names the offending URL, the kind of address that IS allowed, and
136
+ * the lane that replaces this one. `hint` is the host-specific half —
137
+ * `/class byok` in the terminal, the Bring-your-own-key Settings row in the
138
+ * GUI — while the policy half is shared, so the two hosts cannot describe the
139
+ * same rule differently.
140
+ */
141
+ function remoteRefusal(baseURL, { subject = 'custom endpoints', hint = '' } = {}) {
142
+ const where = String(baseURL == null ? '' : baseURL);
143
+ const tail = hint || 'Remote providers are billed, so use the lane that bills them, or point this at a local address.';
144
+ return `${subject} must be LOCAL — remote base URL ${JSON.stringify(where)} is not offered on this lane. ` +
145
+ `${ALLOWED_HINT} ${tail}`;
146
+ }
147
+
148
+ /**
149
+ * Throw the refusal (as a 400-class error every caller already paints) unless
150
+ * the base URL is local. The one-line form of the gate for the dispatch and
151
+ * storage seams, so neither has to remember the status code.
152
+ *
153
+ * An EMPTY base URL is refused here like any other non-local value, because
154
+ * there is no endpoint to dial. The storage seam does not use this function
155
+ * directly for that reason — see allowsDirectDialRow below, which treats "no
156
+ * URL configured" as "nothing to gate".
157
+ */
158
+ function ensureLocalEndpoint(baseURL, opts) {
159
+ if (isLocalEndpoint(baseURL)) return true;
160
+ const err = new Error(remoteRefusal(baseURL, opts));
161
+ err.status = 400;
162
+ err.code = 'CUSTOM_ENDPOINT_NOT_LOCAL';
163
+ throw err;
164
+ }
165
+
166
+ /**
167
+ * The settings-store rows whose base URL is dialled DIRECTLY by the transports
168
+ * in providers.js — i.e. the rows the gate above exists for.
169
+ *
170
+ * 'openai-compat', 'anthropic' the desktop's two custom endpoints (its
171
+ * Settings pane names them exactly so, and
172
+ * engine.js's CUSTOM_CLASSES reads the row
173
+ * under the class name).
174
+ * 'custom:*' the CLI's per-model namespace (src/
175
+ * custommodels.js). The CLI keeps the base URL
176
+ * in config.json `customModels` and stores only
177
+ * the KEY here, so this prefix is a second lock
178
+ * on a door that is already shut — deliberate:
179
+ * a future writer that puts a URL in this row
180
+ * must not silently reopen the lane.
181
+ *
182
+ * It matters that this is a NAMED list and not "every row". The same store
183
+ * holds the billed lanes' rows, and those legitimately carry remote values or
184
+ * nothing at all:
185
+ * · `byok:<provider>` — always remote by definition (the provider's own API,
186
+ * reached through AEGIS's relay, which is what bills it). The desktop's
187
+ * Settings pane saves those rows with baseURL '' (the relay owns the URL),
188
+ * and a blanket "must be local" rule would refuse even the empty string,
189
+ * breaking BYOK configuration entirely.
190
+ * · `aegis` — reserved namespace, never touched through this surface.
191
+ * So a gate keyed on the value alone is wrong; it is keyed on the ROW.
192
+ */
193
+ const DIRECT_DIAL_ROWS = Object.freeze(['openai-compat', 'anthropic']);
194
+ const DIRECT_DIAL_PREFIXES = Object.freeze(['custom:']);
195
+
196
+ /** Whether a settings-store row's base URL is dialled directly (and so gated). */
197
+ function isDirectDialRow(provider) {
198
+ const p = String(provider == null ? '' : provider);
199
+ if (DIRECT_DIAL_ROWS.includes(p)) return true;
200
+ return DIRECT_DIAL_PREFIXES.some((pre) => p.startsWith(pre));
201
+ }
202
+
203
+ /**
204
+ * Whether a row may STORE this base URL — the storage seam's question, which is
205
+ * not quite the dispatch seam's.
206
+ *
207
+ * A direct-dial row with no URL is fine to store: that is how a row is cleared,
208
+ * and how it looks before it is configured (`customStatus` reports it as
209
+ * unconfigured, so nothing dials it). What must never be stored is a NON-EMPTY
210
+ * remote URL, which would make the row look configured and usable.
211
+ */
212
+ function allowsDirectDialRow(provider, baseURL) {
213
+ if (!isDirectDialRow(provider)) return true;
214
+ const url = String(baseURL == null ? '' : baseURL).trim();
215
+ if (!url) return true; // clearing the row, or a not-yet-configured one
216
+ return isLocalEndpoint(url);
217
+ }
218
+
219
+ module.exports = {
220
+ hostOf,
221
+ isLocalEndpoint,
222
+ remoteRefusal,
223
+ ensureLocalEndpoint,
224
+ isDirectDialRow,
225
+ allowsDirectDialRow,
226
+ ALLOWED_HINT,
227
+ DIRECT_DIAL_ROWS,
228
+ };
@@ -45,6 +45,10 @@ const os = require('node:os');
45
45
 
46
46
  const toolsModule = require('./tools.js');
47
47
  const promptModule = require('./prompt.js');
48
+ // The direct-dial policy: which base URLs may reach a provider transport, and
49
+ // why a remote one is refused rather than metered. The same module the CLI
50
+ // resolves (cli/src/custommodels.js), so both hosts answer with one rule.
51
+ const { isLocalEndpoint, remoteRefusal } = require('./endpoints.js');
48
52
  const { ShellSession } = require('./shell.js');
49
53
  const { agentSystemPrompt, agentRoleLabel } = require('./agents.js');
50
54
  // Cooperative working-tree sharing (see each module's header). The lock
@@ -657,14 +661,26 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
657
661
  * a base URL is mandatory for both, and Anthropic additionally needs its own
658
662
  * key (the wire format authenticates with x-api-key). Reporting them as
659
663
  * always-ready made chat() POST to `${undefined}/v1/…` (defect #2).
664
+ *
665
+ * A stored REMOTE base URL is reported as not-configured rather than ready,
666
+ * plus `blocked` and the reason. This is the third face of the direct-dial
667
+ * gate (storage in settings.js set, dispatch in chat below): a row that
668
+ * predates the rule must not be OFFERED either, or the class list advertises
669
+ * a lane the turn then refuses. The reason travels so the UI can explain it
670
+ * instead of showing a dead row — and it is recoverable by design: saving a
671
+ * local URL (or clearing the field) makes the class usable again, which is
672
+ * what the refusal text tells the user to do.
660
673
  */
661
674
  function customStatus(cls) {
662
675
  const cfg = settings.get(cls) || {};
663
676
  const baseURL = typeof cfg.baseURL === 'string' ? cfg.baseURL.trim() : '';
664
677
  const hasBase = Boolean(baseURL);
665
678
  const hasKey = Boolean(cfg.configured);
679
+ const blocked = hasBase && !isLocalEndpoint(baseURL);
666
680
  return {
667
- configured: cls === 'anthropic' ? hasBase && hasKey : hasBase,
681
+ configured: !blocked && (cls === 'anthropic' ? hasBase && hasKey : hasBase),
682
+ blocked,
683
+ ...(blocked ? { blockedReason: remoteRefusal(baseURL, { subject: `the ${cls} endpoint` }) } : {}),
668
684
  baseURL,
669
685
  keyMask: cfg.keyMask || null,
670
686
  };
@@ -770,7 +786,18 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
770
786
  // along for display only.
771
787
  const cfg = settings.get(cls) || {};
772
788
  const baseURL = typeof cfg.baseURL === 'string' ? cfg.baseURL.trim() : '';
773
- return { class: cls, models: [], needsModelId: true, baseURL };
789
+ // Same reporting as customStatus: a stored remote URL is not a usable
790
+ // model list, and the reason has to reach the UI with it (see customStatus).
791
+ const blocked = Boolean(baseURL) && !isLocalEndpoint(baseURL);
792
+ return {
793
+ class: cls,
794
+ models: [],
795
+ needsModelId: true,
796
+ baseURL,
797
+ ...(blocked
798
+ ? { blocked: true, blockedReason: remoteRefusal(baseURL, { subject: `the ${cls} endpoint` }) }
799
+ : {}),
800
+ };
774
801
  }
775
802
 
776
803
  /**
@@ -1154,6 +1181,39 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
1154
1181
  throw err;
1155
1182
  }
1156
1183
 
1184
+ // THE DIRECT-DIAL GATE. A custom class talks to the user's base URL
1185
+ // itself (providers.js openaiCompatible / anthropicMessages), and that
1186
+ // transport bills NOBODY: no pooled margin, no BYOK handling fee, no
1187
+ // account key attached. The only usage it may therefore carry is an
1188
+ // endpoint on this machine, where there is no vendor to pay. A remote URL
1189
+ // here is an unpaid turn, and it is refused rather than metered because
1190
+ // there is nothing to meter it against — the relay accepts a fixed
1191
+ // catalog of provider ids (services/nexus_provider/catalog.py), so an
1192
+ // arbitrary remote URL cannot be billed there either.
1193
+ //
1194
+ // Checked at DISPATCH and not only at storage (settings.js set refuses
1195
+ // the same URL): a row written before this rule existed, or hand-edited
1196
+ // into settings.json, is still in the file, and reading it back happily
1197
+ // would keep the lane open. Both seams, one rule — the message is
1198
+ // endpoints.js's, so the desktop and the CLI say the same thing.
1199
+ if (CUSTOM_CLASSES.includes(cls)) {
1200
+ const raw = cfg && typeof cfg.baseURL === 'string' ? cfg.baseURL.trim() : '';
1201
+ if (raw && !isLocalEndpoint(raw)) {
1202
+ const err = new Error(
1203
+ remoteRefusal(raw, {
1204
+ subject: `the ${cls} endpoint`,
1205
+ hint:
1206
+ 'This class dials your URL directly and bills nobody, so it is local-only. ' +
1207
+ 'Use a model on this machine, or move the provider to the BYOK card (/class byok), ' +
1208
+ 'which relays through AEGIS and charges the handling fee.',
1209
+ })
1210
+ );
1211
+ err.status = 400;
1212
+ err.code = 'CUSTOM_ENDPOINT_NOT_LOCAL';
1213
+ throw err;
1214
+ }
1215
+ }
1216
+
1157
1217
  // Custom classes carry no enumerable model list (see listModels), so a
1158
1218
  // blank id here means the user never typed one. Fail loudly in-process
1159
1219
  // instead of shipping `model: undefined` upstream (defect B).
@@ -17,6 +17,12 @@
17
17
 
18
18
  const fs = require('node:fs');
19
19
  const path = require('node:path');
20
+ // The direct-dial policy (see that file): which rows may hold a remote base URL.
21
+ // Enforced HERE, at the storage seam, so the unusable configuration cannot be
22
+ // created by either host — the desktop's Settings pane or the CLI's `/model add`
23
+ // — rather than only being refused at send time. Pure node builtins, so this
24
+ // store stays loadable without Electron.
25
+ const { isLocalEndpoint, remoteRefusal, isDirectDialRow } = require('./local/endpoints.js');
20
26
 
21
27
  const SETTINGS_FILE = 'settings.json';
22
28
 
@@ -154,8 +160,38 @@ function createSettingsStore({ dir, safeStorage } = {}) {
154
160
  };
155
161
  }
156
162
 
163
+ /**
164
+ * Write a provider row.
165
+ *
166
+ * A direct-dial row ('openai-compat', 'anthropic', 'custom:*') may not hold a
167
+ * remote base URL: those classes talk to the URL themselves (providers.js),
168
+ * which bills nobody, so the only usage they may carry is an endpoint on this
169
+ * machine. Refusing at STORAGE — the earliest seam, shared by the desktop's
170
+ * Settings pane and the CLI — means a remote custom endpoint cannot be
171
+ * configured into existence in the first place; the engine's dispatch gate
172
+ * then covers the rows that predate this rule or were hand-edited into the
173
+ * file. Empty is allowed (that is how the row is cleared, and how a
174
+ * not-yet-configured row looks), and every other namespace is untouched:
175
+ * `byok:<provider>` rows are remote by definition and reach their provider
176
+ * through AEGIS's relay, which is what bills them.
177
+ */
157
178
  function set(provider, { baseURL, key } = {}) {
158
179
  assertNotReserved(provider);
180
+ if (baseURL !== undefined && isDirectDialRow(provider)) {
181
+ const next = String(baseURL == null ? '' : baseURL).trim();
182
+ if (next && !isLocalEndpoint(next)) {
183
+ const err = new Error(remoteRefusal(next, {
184
+ subject: `the ${provider} endpoint`,
185
+ hint:
186
+ 'This lane is for a model running on this machine. To use a remote provider, ' +
187
+ 'save it under Bring-your-own-key (the CLI\'s /class byok), where the AEGIS handling ' +
188
+ 'fee bills the turn.',
189
+ }));
190
+ err.status = 400;
191
+ err.code = 'CUSTOM_ENDPOINT_NOT_LOCAL';
192
+ throw err;
193
+ }
194
+ }
159
195
  const data = load();
160
196
  const cfg = data[provider] || {};
161
197
  if (baseURL !== undefined) cfg.baseURL = baseURL;