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/src/config.js CHANGED
@@ -73,6 +73,20 @@ const DEFAULT_CONFIG = {
73
73
  // aegiscode- name so /model add/remove/switch stay compatible both ways.
74
74
  models: null,
75
75
  currentModelId: null,
76
+ // The named custom-model catalog behind the `custom` class — the
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'}.
89
+ customModels: [],
76
90
  // `null` = no effort pinned, i.e. "auto": each turn is sized by the server
77
91
  // from the ask itself (aegis1 services/pool_brain.py estimate_effort). The
78
92
  // old 'high' was a *pin* on the top rung of the budget ladder — the most the
@@ -0,0 +1,258 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * The named custom-model catalog behind the `custom` class.
5
+ *
6
+ * This is the aegiscodex-dev `/model add` concept ported into the CLI: a user
7
+ * registers an endpoint they bring themselves — their own base URL, their own
8
+ * model string, their own API key — and the turn is called DIRECTLY through the
9
+ * desktop transport (desktop/lib/local/providers.js openaiCompatible /
10
+ * anthropicMessages), the full agent loop and all, never through the pooled
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.
28
+ *
29
+ * Split storage, on purpose:
30
+ * · metadata (id, name, model, baseURL, wire) → config.json `customModels`.
31
+ * None of it is secret, and config.json is where /model pins already live.
32
+ * · the API key → the settings store under `custom:<id>` (file mode 0600,
33
+ * the same store byok keys use). config.json is NOT 0600 and participates in
34
+ * cloud sync, so a provider key must never land there.
35
+ *
36
+ * `wire` selects the transport: 'anthropic' → anthropicMessages (x-api-key,
37
+ * the Messages API), 'openai' → openaiCompatible (Bearer, /chat/completions).
38
+ * It is auto-detected from the base URL host on add, and overridable.
39
+ */
40
+
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
+ );
57
+
58
+ /** The settings-store row a custom model's key lives in. */
59
+ function customNamespace(id) {
60
+ return `custom:${id}`;
61
+ }
62
+
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 });
75
+ }
76
+
77
+ /**
78
+ * Which transport a base URL implies. Anthropic's Messages API is a different
79
+ * wire format (x-api-key, `/v1/messages`, a `system` top-level field) from the
80
+ * OpenAI-compatible majority, so it must be recognised rather than guessed at
81
+ * call time. Everything else — OpenAI, Groq, DeepSeek, together, openrouter,
82
+ * a local llama.cpp — speaks the OpenAI shape.
83
+ */
84
+ function inferWire(baseURL) {
85
+ const host = hostOf(baseURL);
86
+ return host && /(^|\.)anthropic\.com$/.test(host) ? 'anthropic' : 'openai';
87
+ }
88
+
89
+ const VALID_WIRES = Object.freeze(['openai', 'anthropic']);
90
+
91
+ /**
92
+ * Validate and normalise a would-be catalog entry. Returns `{ entry }` on
93
+ * success or `{ error }` with a one-line reason — never throws, so the command
94
+ * layer can show the reason and keep the session alive.
95
+ *
96
+ * The id rules are load-bearing, not cosmetic: a `:` would collide with the
97
+ * `provider:model` shape byok parses, and a whitespace id cannot be typed back
98
+ * to `/model <id>`. A base URL is required and must be http(s) — the transport
99
+ * POSTs to `${baseURL}/…`, so a bare host or a typo becomes an unroutable call
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.
107
+ */
108
+ function normalizeEntry({ id, name, model, baseURL, wire } = {}) {
109
+ const cleanId = String(id == null ? '' : id).trim();
110
+ if (!cleanId) return { error: 'an id is required — /model add <id> <name> <model> <baseURL>' };
111
+ if (/[\s:]/.test(cleanId)) return { error: `invalid id "${cleanId}" — no spaces or ":" (":" is the byok separator)` };
112
+
113
+ const cleanModel = String(model == null ? '' : model).trim();
114
+ if (!cleanModel) return { error: 'a model string is required — the id the provider expects on the wire' };
115
+
116
+ const cleanBase = String(baseURL == null ? '' : baseURL).trim();
117
+ if (!/^https?:\/\//i.test(cleanBase)) return { error: `base URL must start with http(s):// — got ${JSON.stringify(cleanBase)}` };
118
+ if (!hostOf(cleanBase)) return { error: `base URL does not parse — got ${JSON.stringify(cleanBase)}` };
119
+
120
+ let cleanWire = String(wire == null ? '' : wire).trim().toLowerCase();
121
+ if (cleanWire && !VALID_WIRES.includes(cleanWire)) {
122
+ return { error: `wire must be one of ${VALID_WIRES.join(', ')} — got ${JSON.stringify(cleanWire)}` };
123
+ }
124
+ if (!cleanWire) cleanWire = inferWire(cleanBase);
125
+
126
+ if (!isLocalEndpoint(cleanBase)) return { error: customRefusal(cleanBase) };
127
+
128
+ const cleanName = String(name == null ? '' : name).trim() || cleanId;
129
+ return { entry: { id: cleanId, name: cleanName, model: cleanModel, baseURL: cleanBase, wire: cleanWire } };
130
+ }
131
+
132
+ /** The stored catalog (metadata only), always an array. */
133
+ function rawCatalog() {
134
+ const list = loadConfig().customModels;
135
+ return Array.isArray(list) ? list.filter((e) => e && typeof e.id === 'string') : [];
136
+ }
137
+
138
+ /** One entry's metadata by id, or null. */
139
+ function getCustom(id) {
140
+ const want = String(id == null ? '' : id).trim();
141
+ return rawCatalog().find((e) => e.id === want) || null;
142
+ }
143
+
144
+ /**
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.
154
+ */
155
+ function listCustomModels(settings) {
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
+ });
167
+ }
168
+
169
+ /** Whether a key is stored for this custom id. */
170
+ function hasKey(settings, id) {
171
+ if (!settings || typeof settings.rawKey !== 'function') return false;
172
+ return Boolean(settings.rawKey(customNamespace(id)));
173
+ }
174
+
175
+ /**
176
+ * Add or replace a catalog entry, and store its key (when supplied) in the
177
+ * 0600 settings row. Returns `{ entry }` or `{ error }`. Adding an id that
178
+ * already exists REPLACES its metadata (and its key when a new one is given),
179
+ * so `/model add` doubles as an edit — re-running it to fix a typo'd base URL
180
+ * does not leave a second, dead row.
181
+ */
182
+ function addCustom(fields, settings) {
183
+ const res = normalizeEntry(fields);
184
+ if (res.error) return res;
185
+ const { entry } = res;
186
+ const next = rawCatalog().filter((e) => e.id !== entry.id);
187
+ next.push(entry);
188
+ updateConfig({ customModels: next });
189
+ if (settings && typeof settings.set === 'function' && fields && fields.key != null && String(fields.key).trim()) {
190
+ settings.set(customNamespace(entry.id), { key: String(fields.key).trim() });
191
+ }
192
+ return { entry };
193
+ }
194
+
195
+ /** Store (or clear) just the key for an existing custom id. */
196
+ function setCustomKey(id, key, settings) {
197
+ if (!settings || typeof settings.set !== 'function') return { error: 'no key store available' };
198
+ settings.set(customNamespace(id), { key: key ? String(key).trim() : null });
199
+ return { ok: true };
200
+ }
201
+
202
+ /**
203
+ * Remove a catalog entry and forget its key. Returns whether anything was
204
+ * removed, so the command can say "removed" vs "there was no such entry".
205
+ */
206
+ function removeCustom(id, settings) {
207
+ const want = String(id == null ? '' : id).trim();
208
+ const before = rawCatalog();
209
+ const after = before.filter((e) => e.id !== want);
210
+ const removed = after.length !== before.length;
211
+ if (removed) updateConfig({ customModels: after });
212
+ if (settings && typeof settings.remove === 'function') {
213
+ try { settings.remove(customNamespace(want)); } catch { /* nothing stored */ }
214
+ }
215
+ return { removed };
216
+ }
217
+
218
+ /**
219
+ * Resolve a pinned custom id to everything the dispatch needs: the transport
220
+ * class it maps to ('anthropic' | 'openai-compat'), its base URL, its wire
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.
227
+ */
228
+ function resolveCustom(id, settings) {
229
+ const entry = getCustom(id);
230
+ if (!entry) return null;
231
+ const key = settings && typeof settings.rawKey === 'function' ? settings.rawKey(customNamespace(entry.id)) : null;
232
+ return {
233
+ wireClass: entry.wire === 'anthropic' ? 'anthropic' : 'openai-compat',
234
+ baseURL: entry.baseURL,
235
+ model: entry.model,
236
+ key: key || null,
237
+ wire: entry.wire,
238
+ id: entry.id,
239
+ local: isLocalEndpoint(entry.baseURL),
240
+ };
241
+ }
242
+
243
+ module.exports = {
244
+ customNamespace,
245
+ inferWire,
246
+ isLocalEndpoint,
247
+ remoteRefusal,
248
+ customRefusal,
249
+ normalizeEntry,
250
+ getCustom,
251
+ listCustomModels,
252
+ hasKey,
253
+ addCustom,
254
+ setCustomKey,
255
+ removeCustom,
256
+ resolveCustom,
257
+ VALID_WIRES,
258
+ };
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'));
@@ -81,11 +66,20 @@ const updatePath = resolveShared(path.join('client', 'update.js'));
81
66
  // must work the SAME queue with the SAME rules (scoped commits included).
82
67
  const queuePath = resolveShared(path.join('desktop', 'lib', 'local', 'queue.js'));
83
68
  const autonomousPath = resolveShared(path.join('desktop', 'lib', 'local', 'autonomous.js'));
69
+ // The direct-provider transport (openaiCompatible + anthropicMessages). The
70
+ // desktop injects it into createLocalEngine for its custom-endpoint classes;
71
+ // the CLI injects the same real module for its `custom` class (the /model add
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.
76
+ const providersPath = resolveShared(path.join('desktop', 'lib', 'local', 'providers.js'));
84
77
 
85
78
  const { createClient } = require(clientPath);
86
79
  const { createTools } = require(toolsPath);
87
80
  const { usageTokens } = require(usagePath);
88
81
  const { createLocalEngine } = require(enginePath);
82
+ const providers = require(providersPath);
89
83
  const { createSettingsStore, isReservedNamespace } = require(settingsPath);
90
84
  const { agentRoles, agentRoleLabel } = require(agentsPath);
91
85
  const { buildSystemPrompt } = require(promptPath);
@@ -99,6 +93,7 @@ module.exports = {
99
93
  createTools,
100
94
  usageTokens,
101
95
  createLocalEngine,
96
+ providers,
102
97
  createSettingsStore,
103
98
  isReservedNamespace,
104
99
  agentRoles,
@@ -107,6 +102,6 @@ module.exports = {
107
102
  updater,
108
103
  queue,
109
104
  autonomous,
110
- paths: { client: clientPath, tools: toolsPath, usage: usagePath, engine: enginePath, settings: settingsPath, agents: agentsPath, prompt: promptPath, update: updatePath, queue: queuePath, autonomous: autonomousPath },
105
+ paths: { client: clientPath, tools: toolsPath, usage: usagePath, engine: enginePath, providers: providersPath, settings: settingsPath, agents: agentsPath, prompt: promptPath, update: updatePath, queue: queuePath, autonomous: autonomousPath },
111
106
  roots,
112
107
  };
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
  *
@@ -37,12 +43,25 @@
37
43
  */
38
44
 
39
45
  const os = require('node:os');
40
- const { createLocalEngine, createSettingsStore } = require('./deps.js');
46
+ const { createLocalEngine, createSettingsStore, providers } = require('./deps.js');
41
47
  const { credentials } = require('./shared.js');
48
+ const custom = require('./custommodels.js');
42
49
  const VERSION = require('../package.json').version;
43
50
 
44
- /** The classes this host can actually run (see the docstring above). */
45
- const HOST_CLASSES = Object.freeze(['aegis', 'byok']);
51
+ /**
52
+ * The classes this host can actually run (see the docstring above).
53
+ * aegis — the pooled route (account key pays, pool picks the provider; bills).
54
+ * byok — the BYOK relay (your provider key, AEGIS bills a handling fee).
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
57
+ * through the desktop transport with the full tool loop, never
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.
63
+ */
64
+ const HOST_CLASSES = Object.freeze(['aegis', 'byok', 'custom']);
46
65
 
47
66
  /** The class a turn runs on when nothing else is said. */
48
67
  const DEFAULT_CLASS = 'aegis';
@@ -51,6 +70,7 @@ const DEFAULT_CLASS = 'aegis';
51
70
  const CLASS_LABELS = Object.freeze({
52
71
  aegis: 'AEGIS Cloud (pooled)',
53
72
  byok: 'Bring your own key (relayed, billed)',
73
+ custom: 'Custom endpoint (local only — free, direct)',
54
74
  });
55
75
 
56
76
  function unsupported(label) {
@@ -85,9 +105,16 @@ function createEngine({ client, getConfirmMode, getClass, settings: injectedSett
85
105
  listTags: async () => [],
86
106
  chat: unsupported('Ollama'),
87
107
  },
108
+ // The real direct-provider transport — no longer a throwing stub. The
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.
88
115
  providers: {
89
- anthropicMessages: unsupported('a custom Anthropic-compatible endpoint'),
90
- openaiCompatible: unsupported('a custom OpenAI-compatible endpoint'),
116
+ anthropicMessages: providers.anthropicMessages,
117
+ openaiCompatible: providers.openaiCompatible,
91
118
  },
92
119
  env: {
93
120
  platform: process.platform,
@@ -105,21 +132,87 @@ function createEngine({ client, getConfirmMode, getClass, settings: injectedSett
105
132
  return HOST_CLASSES.includes(asked) ? asked : DEFAULT_CLASS;
106
133
  }
107
134
 
108
- return {
135
+ /**
136
+ * Rewrite a `custom`-class turn to the concrete transport class the desktop
137
+ * engine already drives. The catalog entry is the source of truth for the
138
+ * endpoint; its base URL + key are written just-in-time into the wire-class
139
+ * settings row (settings.get(cls).baseURL / rawKey(cls) is what the engine's
140
+ * dispatch reads), and the payload's class + model are set to that wire class
141
+ * and the entry's real model string. Throws a clear, in-process error rather
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).
151
+ */
152
+ function prepareCustom(payload) {
153
+ const modelId = payload && payload.model;
154
+ const resolved = modelId ? custom.resolveCustom(modelId, settings) : null;
155
+ if (!resolved) {
156
+ const err = new Error(
157
+ modelId
158
+ ? `custom: no model "${modelId}" in the catalog — /model add <id> <name> <model> <baseURL>, or /models to list.`
159
+ : 'custom: no model pinned — pin one with /model <id> (/models lists your custom endpoints).'
160
+ );
161
+ err.status = 400;
162
+ throw err;
163
+ }
164
+ if (!resolved.local) {
165
+ const err = new Error(custom.customRefusal(resolved.baseURL));
166
+ err.status = 400;
167
+ throw err;
168
+ }
169
+ if (resolved.wire === 'anthropic' && !resolved.key) {
170
+ const err = new Error(
171
+ `custom: "${resolved.id}" is an Anthropic-style endpoint and needs a key — /model key ${resolved.id}.`
172
+ );
173
+ err.status = 400;
174
+ throw err;
175
+ }
176
+ // Just-in-time scratch write: the wire-class row is only ever this session's
177
+ // active custom endpoint, re-set on every custom turn, so two custom models
178
+ // sharing a wire never collide.
179
+ settings.set(resolved.wireClass, { baseURL: resolved.baseURL, key: resolved.key || null });
180
+ return { ...payload, class: resolved.wireClass, model: resolved.model };
181
+ }
182
+
183
+ function chat(payload, onDelta) {
184
+ const cls = currentClass();
185
+ if (cls === 'custom') return local.chat(prepareCustom(payload), onDelta);
109
186
  // `class` is stamped here rather than sent by every caller, so the class a
110
187
  // turn runs on has exactly one source of truth (the live session state) and
111
188
  // a caller cannot accidentally pin a stale one.
112
- chat: (payload, onDelta) => local.chat({ ...payload, class: currentClass() }, onDelta),
189
+ return local.chat({ ...payload, class: cls }, onDelta);
190
+ }
191
+
192
+ return {
193
+ chat,
113
194
  cancel: local.cancel,
114
195
  respondApproval: local.respondApproval,
115
196
  clearSessionApprovals: local.clearSessionApprovals,
116
- // The engine's own class table, narrowed to the two this host runs — so a
197
+ // The engine's own class table, narrowed to the ones this host runs — so a
117
198
  // UI built from listClasses() can never offer a class that would throw.
199
+ // `custom` is not in the desktop engine's own CLASSES (it is a CLI concept
200
+ // that rewrites to openai-compat/anthropic), so it is appended here.
118
201
  // Async, like the local engine's: listClasses() probes Ollama (a live
119
202
  // HTTP round-trip) before it can answer, so returning the raw promise made
120
203
  // `/class` throw "filter is not a function". The caller awaits it.
121
- listClasses: async () => (await local.listClasses()).filter((c) => HOST_CLASSES.includes(c.class)),
122
- listModels: (cls) => local.listModels(cls || currentClass()),
204
+ listClasses: async () => {
205
+ const base = (await local.listClasses()).filter((c) => HOST_CLASSES.includes(c.class));
206
+ const configured = custom.listCustomModels(settings).length > 0;
207
+ return [...base, { class: 'custom', label: CLASS_LABELS.custom, kind: 'custom', configured }];
208
+ },
209
+ // The `custom` class enumerates the catalog (the desktop engine has no such
210
+ // class, so delegating would throw); every other class delegates.
211
+ listModels: (cls) => {
212
+ const want = cls || currentClass();
213
+ if (want === 'custom') return { class: 'custom', models: custom.listCustomModels(settings) };
214
+ return local.listModels(want);
215
+ },
123
216
  classLabel: (cls) => CLASS_LABELS[cls] || CLASS_LABELS[DEFAULT_CLASS],
124
217
  getClass: currentClass,
125
218
  settings,
@@ -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 };
@@ -354,17 +354,27 @@ function createClient(opts = {}) {
354
354
  *
355
355
  * The caller's *AEGIS* key is sent alongside the provider key as X-AEGIS-Key.
356
356
  * Two credentials, two headers, on purpose: the provider key authenticates the
357
- * upstream call, the AEGIS key says whose bank pays the handling fee. With no
358
- * AEGIS key configured the header is omitted and the call stays anonymous:
359
- * the relay still serves it, and `_byok_identify_user` on the server resolves
360
- * no payer, so `charge_byok` logs the fee against user 0 as uncollected. The
361
- * turn is not refused — `AEGIS_BYOK_REQUIRE_BALANCE` (off by default) is the
362
- * server's own gate and the only place that decides this, deliberately, so
363
- * that pre-existing unauthenticated BYOK clients do not start getting 402s on
364
- * upgrade (aegis1 tests/test_byok_fee.py pins the anonymous path as allowed).
365
- * No client enforces it either: the desktop is one caller of a route that is
366
- * unauthenticated by design. What this header changes is attribution — sending
367
- * it is what makes the fee collectable from the account it belongs to.
357
+ * upstream call, the AEGIS key says whose bank pays the handling fee —
358
+ * `_byok_identify_user` on the server resolves the payer from it, and nothing
359
+ * else. With no AEGIS key the header is omitted and the call is anonymous;
360
+ * THIS function still sends it, because it is a transport and the route is
361
+ * unauthenticated by design (aegis1 tests/test_byok_fee.py pins the anonymous
362
+ * path as allowed) — refusing here would break every other caller of a
363
+ * published endpoint.
364
+ *
365
+ * Attribution is the whole game, because an unattributed turn is the one way
366
+ * a BYOK call escapes the fee: the relay serves it, `charge_byok` never runs
367
+ * (`app.py` charges only `if _byok_user_id:`), and the call is logged against
368
+ * user 0 as uncollected — a free ride. So the shipped HOSTS refuse a keyless
369
+ * BYOK send before the relay is reached: desktop/lib/local/engine.js raises
370
+ * 401, and the desktop app and the CLI share that engine (the CLI stages it
371
+ * as cli/vendor/desktop/lib/local/engine.js), so one gate covers both. Every
372
+ * turn is then attributable, and therefore billable: a funded balance is
373
+ * debited, an unfunded one is recorded as owed — `charge_byok` clamps the
374
+ * debit at zero and never refuses the call, so "cannot pay" and "must not be
375
+ * billed" stop being the same thing. `AEGIS_BYOK_REQUIRE_BALANCE` (off by
376
+ * default) remains the server's own, separate 402 gate and is not what makes
377
+ * the fee land.
368
378
  */
369
379
  async function byokChatCompletion({
370
380
  provider = 'openai',