aegiscode 6.7.5 → 6.7.6

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/tokens.js CHANGED
@@ -41,25 +41,53 @@ const RATES = {
41
41
  deepseek: { input: 0.14, output: 0.28, cacheRead: 0.014, cacheWrite: 0.14 },
42
42
  };
43
43
 
44
+ /**
45
+ * Rate rows a model id may name as a whole word rather than as a prefix.
46
+ * Anthropic spells its family *inside* the id — "claude-opus-4" matches no
47
+ * prefix — so prefix matching alone cannot see it.
48
+ */
49
+ const RATE_FAMILIES = Object.keys(RATES).filter((k) => k !== 'default');
50
+
44
51
  /**
45
52
  * The rate row for a model id, provider, or alias. Exact id wins, then the
46
- * longest matching prefix, then the Sonnet-class default — the same resolution
47
- * order contextWindowFor uses, so the cost meter and the context meter cannot
48
- * disagree about which family a model belongs to.
53
+ * longest matching prefix, then a family named inside the id, then the
54
+ * Sonnet-class default — the same resolution order contextWindowFor uses, so
55
+ * the cost meter and the context meter cannot disagree about which family a
56
+ * model belongs to.
49
57
  */
50
58
  function ratesFor(model) {
51
- const id = String(model || '').toLowerCase();
52
- if (!id) return RATES.default;
53
- if (RATES[id]) return RATES[id];
54
- let best = null;
55
- let bestLen = 0;
56
- for (const [prefix, rates] of Object.entries(RATES)) {
57
- if (id.startsWith(prefix) && prefix.length > bestLen) {
58
- best = rates;
59
- bestLen = prefix.length;
59
+ const raw = String(model || '').toLowerCase();
60
+ if (!raw) return RATES.default;
61
+ // `/class byok` selects a "provider:model" id, and the provider half is a
62
+ // routing label, not a rate: rating it as written fell through every prefix
63
+ // to RATES.default, so an Opus BYOK turn was priced at Sonnet's $3/$15
64
+ // against the vendor's real $5/$25.
65
+ const ids = [raw];
66
+ const tail = raw.slice(raw.lastIndexOf(':') + 1);
67
+ if (tail && tail !== raw) ids.push(tail);
68
+ for (const id of ids) {
69
+ if (RATES[id]) return RATES[id];
70
+ let best = null;
71
+ let bestLen = 0;
72
+ for (const [prefix, rates] of Object.entries(RATES)) {
73
+ if (id.startsWith(prefix) && prefix.length > bestLen) {
74
+ best = rates;
75
+ bestLen = prefix.length;
76
+ }
60
77
  }
78
+ if (best) return best;
61
79
  }
62
- return best || RATES.default;
80
+ // Longest family-key hit wins, so an overlapping pair resolves the same way
81
+ // twice running rather than by object key order.
82
+ let family = null;
83
+ let familyLen = 0;
84
+ for (const key of RATE_FAMILIES) {
85
+ if (raw.includes(key) && key.length > familyLen) {
86
+ family = RATES[key];
87
+ familyLen = key.length;
88
+ }
89
+ }
90
+ return family || RATES.default;
63
91
  }
64
92
 
65
93
  // System prompt + tool definitions overhead, roughly, in tokens.
@@ -97,11 +125,21 @@ const CONTEXT_WINDOWS = {
97
125
 
98
126
  /** The context budget to show/guard against for a model id, provider, or raw model string. */
99
127
  function contextWindowFor(model) {
100
- const id = String(model || '').toLowerCase();
101
- if (!id) return CONTEXT_WINDOW;
102
- if (CONTEXT_WINDOWS[id]) return CONTEXT_WINDOWS[id];
103
- for (const [prefix, win] of Object.entries(CONTEXT_WINDOWS)) {
104
- if (id.startsWith(prefix)) return win;
128
+ const raw = String(model || '').toLowerCase();
129
+ if (!raw) return CONTEXT_WINDOW;
130
+ // Same two-candidate lookup as ratesFor above, for the same reason: a byok
131
+ // id ("deepseek:deepseek-v4-flash") carries a routing label in front of the
132
+ // model, and matching it as written left the 1M-token DeepSeek window reading
133
+ // as the 200k default — a meter that would have told a user they were at 20%
134
+ // of a context that was 4% full.
135
+ const ids = [raw];
136
+ const tail = raw.slice(raw.lastIndexOf(':') + 1);
137
+ if (tail && tail !== raw) ids.push(tail);
138
+ for (const id of ids) {
139
+ if (CONTEXT_WINDOWS[id]) return CONTEXT_WINDOWS[id];
140
+ for (const [prefix, win] of Object.entries(CONTEXT_WINDOWS)) {
141
+ if (id.startsWith(prefix)) return win;
142
+ }
105
143
  }
106
144
  return CONTEXT_WINDOW;
107
145
  }
@@ -355,8 +355,16 @@ function createClient(opts = {}) {
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
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
- * allowed, just unbilled (see _byok_identify_user on the server).
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.
360
368
  */
361
369
  async function byokChatCompletion({
362
370
  provider = 'openai',
@@ -714,14 +714,27 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
714
714
  if (cls === 'byok') {
715
715
  // The server's catalog names every provider it accepts a key for, the
716
716
  // models each unlocks, and whether an AEGIS account key is even needed
717
- // to ask (it is not — see byokProviders' own docstring). Deliberately
718
- // NOT gated on aegis.apiKey the way the pooled class above is: BYOK's
719
- // whole point is a caller who brings their own credential, and the
720
- // catalog itself answers to an anonymous request.
717
+ // to ask (it is not — the catalog answers an anonymous request).
718
+ // Deliberately NOT gated on aegis.apiKey the way the pooled class above
719
+ // is: BYOK's whole point is a caller who brings their own credential, and
720
+ // hiding the catalog would hide the answer to "which key do I go and get"
721
+ // from exactly the person deciding whether to bother. Nothing here
722
+ // enforces billing either: the desktop is one client of a route that is
723
+ // unauthenticated by design, so refusing in this process would stop
724
+ // exactly one host out of many. The relay owns that decision, and reports
725
+ // it via `fee.require_balance` below.
721
726
  let providers = [];
727
+ let fee = null;
722
728
  try {
723
729
  const data = await aegis.byokProviders();
724
730
  providers = (data && data.providers) || [];
731
+ // The handling fee AEGIS adds on top of the caller's vendor bill. It is
732
+ // the server's own published rate (services/pricing.price_byok_call) and
733
+ // is passed through untouched — never re-derived here, because a client
734
+ // that hardcodes a fee is a client that can disagree with the ledger.
735
+ // Absent until the server publishes one, and the UI must then say
736
+ // nothing rather than show a guess.
737
+ fee = (data && data.fee) || null;
725
738
  } catch {
726
739
  providers = [];
727
740
  }
@@ -744,6 +757,8 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
744
757
  return {
745
758
  class: cls, models, providers,
746
759
  needsProviderKey: models.length > 0 && !models.some((m) => m.configured),
760
+ needsAegisKey: !aegis.apiKey,
761
+ fee,
747
762
  };
748
763
  }
749
764
  // Custom endpoints: the model id is the *user's* choice — a provider model
@@ -1093,6 +1108,16 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
1093
1108
  err.status = 400;
1094
1109
  throw err;
1095
1110
  }
1111
+ // …and the AEGIS account key is what makes the turn BILLABLE at all. The
1112
+ // relay authenticates on the provider key and resolves the payer
1113
+ // separately, from X-AEGIS-Key (app.py `_byok_identify_user`): with no
1114
+ // account key the fee is logged against user 0 as uncollected, and with
1115
+ // AEGIS_BYOK_REQUIRE_BALANCE off — the default — the turn is served
1116
+ // anyway. That is the server's documented behaviour, so nothing is
1117
+ // refused here: `listModels` reports the missing key as `needsAegisKey`
1118
+ // and the settings UI says plainly where the fee lands, which is the part
1119
+ // a client can do honestly. Enforcement lives in the relay's own gate,
1120
+ // which every caller passes through.
1096
1121
 
1097
1122
  // Custom classes carry no enumerable model list (see listModels), so a
1098
1123
  // blank id here means the user never typed one. Fail loudly in-process
@@ -0,0 +1,364 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * settings.js — provider-config store for the desktop host (plan P1 §5.1).
5
+ * Holds base URLs and provider keys in the main process only. Keys are
6
+ * encrypted at rest via Electron safeStorage when available, otherwise stored
7
+ * base64 (best-effort; never real security) — and only masked previews ever
8
+ * cross the IPC bridge.
9
+ *
10
+ * The in-app AEGIS key lives in its own reserved namespace (AEGIS_KEY_NAMESPACE)
11
+ * with dedicated accessors, so the provider CRUD surface — and the Settings
12
+ * pane built on it — can never list it as a provider or remove it.
13
+ *
14
+ * Pure Node + injectable storage dir / safeStorage so it unit-tests without
15
+ * an Electron binary.
16
+ */
17
+
18
+ const fs = require('node:fs');
19
+ const path = require('node:path');
20
+
21
+ const SETTINGS_FILE = 'settings.json';
22
+
23
+ /**
24
+ * Reserved namespace for the in-app AEGIS API key. It deliberately does NOT
25
+ * look like a provider id: the provider-config surface (get/set/remove/list,
26
+ * and therefore the Settings pane and the model: IPC) must never be able to
27
+ * list it as a provider or delete it via "Remove" — that coupling is defect
28
+ * #1 of the AEGIS-key wiring review (settings.set('aegis', …) used the same
29
+ * namespace as user provider configs). Use the dedicated AEGIS accessors on
30
+ * the store (setAegisKey / aegisRawKey / aegisKey) to touch it.
31
+ */
32
+ const AEGIS_KEY_NAMESPACE = '__aegis';
33
+
34
+ /** Pre-fix builds persisted the AEGIS key as a plain provider named 'aegis';
35
+ * migrateLegacyAegisKey() relocates it (and list() hides it meanwhile). */
36
+ const LEGACY_AEGIS_NAMESPACE = 'aegis';
37
+
38
+ /** Reserved namespace for the global quick-launcher shortcut config
39
+ * ({ enabled, shortcut }) — app-level settings, not a provider, so it must
40
+ * stay out of the provider CRUD surface for the same reason the AEGIS key
41
+ * does (see AEGIS_KEY_NAMESPACE above). */
42
+ const QUICK_LAUNCHER_NAMESPACE = '__quickLauncher';
43
+
44
+ /** Default global shortcut: rare enough on both major platforms to avoid
45
+ * fighting existing app/OS bindings, memorable enough to type once. */
46
+ const DEFAULT_QUICK_LAUNCHER_SHORTCUT = 'CmdOrCtrl+Shift+Space';
47
+
48
+ /** Reserved namespace for the tool-call approval ("confirm mode") preference:
49
+ * `{ enabled }` — app-level, not a provider, so it stays out of the provider
50
+ * CRUD surface for the same reason the AEGIS key does. Default is ON
51
+ * (settings.getConfirmMode() === true when unset), which is the historical
52
+ * behaviour: exec/writeFile/editFile always asked for approval.
53
+ * NOTE: like the AEGIS key and the quick launcher, this lives in its own
54
+ * top-level namespace — never inside a provider's `cfg[provider]` object. */
55
+ const CONFIRM_MODE_NAMESPACE = '__confirmMode';
56
+
57
+ /** Reserved namespace for the persisting-memory preference: `{ enabled }` —
58
+ * app-level, not a provider. This is the desktop's counterpart to the CLI's
59
+ * `memoryPersist` config key, and the gate `lib/sync/persist-gate.js` reads
60
+ * before any automatic cloud push. Default is ON (an absent namespace means
61
+ * persistence is on, which is the shipped decision); an explicit `false` is
62
+ * what turns it off. Nothing secret lives here, so no encryption. */
63
+ const MEMORY_PERSIST_NAMESPACE = '__memoryPersist';
64
+
65
+ /** Namespaces the provider-config surface must never see or mutate. */
66
+ const RESERVED_NAMESPACES = Object.freeze([
67
+ AEGIS_KEY_NAMESPACE,
68
+ LEGACY_AEGIS_NAMESPACE,
69
+ QUICK_LAUNCHER_NAMESPACE,
70
+ CONFIRM_MODE_NAMESPACE,
71
+ MEMORY_PERSIST_NAMESPACE,
72
+ ]);
73
+
74
+ /** True for the AEGIS-key namespace(s) — provider CRUD must refuse these. */
75
+ function isReservedNamespace(provider) {
76
+ return RESERVED_NAMESPACES.includes(provider);
77
+ }
78
+
79
+ /** Same masking shape as desktop/main.js so previews are consistent. */
80
+ function maskKey(key) {
81
+ if (!key) return null;
82
+ if (key.length <= 10) return 'configured';
83
+ return `${key.slice(0, 9)}\u2026${key.slice(-4)}`;
84
+ }
85
+
86
+ function createSettingsStore({ dir, safeStorage } = {}) {
87
+ if (!dir) throw new Error('createSettingsStore requires a storage dir');
88
+ const file = path.join(dir, SETTINGS_FILE);
89
+
90
+ const safeAvailable = () =>
91
+ Boolean(
92
+ safeStorage &&
93
+ typeof safeStorage.isEncryptionAvailable === 'function' &&
94
+ safeStorage.isEncryptionAvailable()
95
+ );
96
+
97
+ function encrypt(value) {
98
+ if (value == null) return null;
99
+ if (safeAvailable()) {
100
+ return safeStorage.encryptString(String(value)).toString('base64');
101
+ }
102
+ return Buffer.from(String(value), 'utf8').toString('base64');
103
+ }
104
+
105
+ function decrypt(value) {
106
+ if (!value) return null;
107
+ try {
108
+ const buf = Buffer.from(String(value), 'base64');
109
+ if (safeAvailable()) return safeStorage.decryptString(buf);
110
+ return buf.toString('utf8');
111
+ } catch {
112
+ return null;
113
+ }
114
+ }
115
+
116
+ function load() {
117
+ try {
118
+ return JSON.parse(fs.readFileSync(file, 'utf8')) || {};
119
+ } catch {
120
+ return {};
121
+ }
122
+ }
123
+
124
+ function save(data) {
125
+ fs.mkdirSync(path.dirname(file), { recursive: true });
126
+ const tmp = `${file}.tmp-${process.pid}`;
127
+ // 0600, written before the rename so the file is never briefly readable:
128
+ // this store holds provider keys, and both hosts are now able to write it
129
+ // (the CLI uses the same file, without Electron's safeStorage, so at-rest
130
+ // base64 is all the protection there is — file mode is the real control).
131
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 0o600 });
132
+ fs.renameSync(tmp, file);
133
+ try { fs.chmodSync(file, 0o600); } catch {}
134
+ }
135
+
136
+ /** Provider CRUD must never touch a reserved (AEGIS-key) namespace. */
137
+ function assertNotReserved(provider) {
138
+ if (isReservedNamespace(provider)) {
139
+ throw new Error(
140
+ `reserved namespace "${provider}" is not a provider config — ` +
141
+ 'use setAegisKey()/aegisRawKey() for the AEGIS key'
142
+ );
143
+ }
144
+ }
145
+
146
+ function get(provider) {
147
+ const cfg = (load()[provider]) || {};
148
+ const key = decrypt(cfg.key);
149
+ return {
150
+ provider,
151
+ baseURL: cfg.baseURL || '',
152
+ configured: Boolean(key),
153
+ keyMask: maskKey(key),
154
+ };
155
+ }
156
+
157
+ function set(provider, { baseURL, key } = {}) {
158
+ assertNotReserved(provider);
159
+ const data = load();
160
+ const cfg = data[provider] || {};
161
+ if (baseURL !== undefined) cfg.baseURL = baseURL;
162
+ if (key !== undefined) cfg.key = key ? encrypt(key) : null;
163
+ data[provider] = cfg;
164
+ save(data);
165
+ return get(provider);
166
+ }
167
+
168
+ function rawKey(provider) {
169
+ const cfg = load()[provider] || {};
170
+ return decrypt(cfg.key);
171
+ }
172
+
173
+ function remove(provider) {
174
+ assertNotReserved(provider);
175
+ const data = load();
176
+ delete data[provider];
177
+ save(data);
178
+ return { ok: true };
179
+ }
180
+
181
+ /** Every provider config, never the AEGIS key (defect #1). */
182
+ function list() {
183
+ const data = load();
184
+ return Object.keys(data)
185
+ .filter((p) => !isReservedNamespace(p))
186
+ .map((p) => get(p));
187
+ }
188
+
189
+ // --- AEGIS key: separate namespace, separate accessors -------------------
190
+
191
+ function aegisKey() {
192
+ const cfg = load()[AEGIS_KEY_NAMESPACE] || {};
193
+ const key = decrypt(cfg.key);
194
+ return { configured: Boolean(key), keyMask: maskKey(key) };
195
+ }
196
+
197
+ /** Main-process-only: the decrypted AEGIS key. Never crosses IPC. */
198
+ function aegisRawKey() {
199
+ const cfg = load()[AEGIS_KEY_NAMESPACE] || {};
200
+ return decrypt(cfg.key);
201
+ }
202
+
203
+ /**
204
+ * When this host last wrote its own AEGIS key (ISO string, or null).
205
+ *
206
+ * The shared credential file records the same thing, and startup compares the
207
+ * two so the most recently saved key wins. Without a stamp the app cannot tell
208
+ * "I saved this last week" from "the user ran `aegiscode login` a minute ago
209
+ * with a rotated key", and would silently keep presenting the stale one.
210
+ */
211
+ function aegisKeySavedAt() {
212
+ const cfg = load()[AEGIS_KEY_NAMESPACE] || {};
213
+ return cfg.savedAt || null;
214
+ }
215
+
216
+ function setAegisKey(key) {
217
+ const data = load();
218
+ data[AEGIS_KEY_NAMESPACE] = {
219
+ ...(data[AEGIS_KEY_NAMESPACE] || {}),
220
+ key: key ? encrypt(key) : null,
221
+ savedAt: key ? new Date().toISOString() : null,
222
+ };
223
+ save(data);
224
+ return aegisKey();
225
+ }
226
+
227
+ /**
228
+ * Relocate a pre-fix `settings['aegis'].key` into the reserved namespace and
229
+ * drop the pseudo-provider entry. Moved at ciphertext level (no decrypt /
230
+ * re-encrypt), so it is safe to run before Electron's app 'ready' — when
231
+ * safeStorage is not usable yet. Idempotent; never throws.
232
+ */
233
+ function migrateLegacyAegisKey() {
234
+ try {
235
+ const data = load();
236
+ if (!data[LEGACY_AEGIS_NAMESPACE]) return { migrated: false };
237
+ const legacy = data[LEGACY_AEGIS_NAMESPACE] || {};
238
+ const current = data[AEGIS_KEY_NAMESPACE] || {};
239
+ const next = { ...data };
240
+ if (legacy.key && !current.key) {
241
+ next[AEGIS_KEY_NAMESPACE] = { ...current, key: legacy.key };
242
+ }
243
+ delete next[LEGACY_AEGIS_NAMESPACE];
244
+ save(next);
245
+ return { migrated: true };
246
+ } catch {
247
+ return { migrated: false };
248
+ }
249
+ }
250
+
251
+ // --- Quick launcher: reserved namespace, plain (unencrypted) config ------
252
+ // No secret lives here — just a bool and a shortcut string — so unlike the
253
+ // AEGIS key above there is nothing to encrypt/decrypt.
254
+
255
+ function quickLauncherConfig() {
256
+ const cfg = load()[QUICK_LAUNCHER_NAMESPACE] || {};
257
+ const shortcut =
258
+ typeof cfg.shortcut === 'string' && cfg.shortcut.trim()
259
+ ? cfg.shortcut.trim()
260
+ : DEFAULT_QUICK_LAUNCHER_SHORTCUT;
261
+ return { enabled: Boolean(cfg.enabled), shortcut };
262
+ }
263
+
264
+ function setQuickLauncherConfig({ enabled, shortcut } = {}) {
265
+ const data = load();
266
+ data[QUICK_LAUNCHER_NAMESPACE] = {
267
+ enabled: Boolean(enabled),
268
+ shortcut:
269
+ typeof shortcut === 'string' && shortcut.trim()
270
+ ? shortcut.trim()
271
+ : DEFAULT_QUICK_LAUNCHER_SHORTCUT,
272
+ };
273
+ save(data);
274
+ return quickLauncherConfig();
275
+ }
276
+
277
+ // --- Confirm mode: reserved namespace, plain (unencrypted) preference ----
278
+ // "Confirm before running tools" — the ON/OFF switch for the renderer's
279
+ // tool-call approval gate (desktop/lib/local/engine.js gatedExecuteTool).
280
+ // ON (default, and the behaviour shipped so far) means every mutating tool
281
+ // call — exec / writeFile / editFile — is previewed and approved by the user
282
+ // first. OFF means the engine runs them straight through, like a tool the
283
+ // session already allowed. Nothing secret is stored here, so no encryption.
284
+
285
+ function getConfirmMode() {
286
+ const cfg = load()[CONFIRM_MODE_NAMESPACE] || {};
287
+ // Unset === true: an existing install that never touched the toggle keeps
288
+ // the gate exactly as it was.
289
+ return cfg.enabled === undefined ? true : Boolean(cfg.enabled);
290
+ }
291
+
292
+ function setConfirmMode(enabled) {
293
+ const data = load();
294
+ data[CONFIRM_MODE_NAMESPACE] = { enabled: Boolean(enabled) };
295
+ save(data);
296
+ return getConfirmMode();
297
+ }
298
+
299
+ // --- Persisting memory: reserved namespace, plain preference -------------
300
+ // The desktop's half of "persisting memory for every account": whether a
301
+ // finished turn is pushed to cloud memory automatically. ON when unset —
302
+ // an install that never touched the toggle behaves like cli/, whose
303
+ // `memoryPersist` also defaults to on. `memoryPersistState()` reports the
304
+ // SOURCE as well as the value so "off" and "never set" stay distinguishable;
305
+ // lib/sync/persist-gate.js reads the same namespace straight off disk, and
306
+ // the two must agree on the default.
307
+
308
+ function getMemoryPersist() {
309
+ const cfg = load()[MEMORY_PERSIST_NAMESPACE] || {};
310
+ return cfg.enabled === undefined ? true : Boolean(cfg.enabled);
311
+ }
312
+
313
+ /** `{ enabled, source }` — mirrors cli/src/cloudsync.js memoryPersistState(). */
314
+ function memoryPersistState() {
315
+ const cfg = load()[MEMORY_PERSIST_NAMESPACE] || {};
316
+ return {
317
+ enabled: getMemoryPersist(),
318
+ source: cfg.enabled === undefined ? 'default' : 'config',
319
+ };
320
+ }
321
+
322
+ function setMemoryPersist(enabled) {
323
+ const data = load();
324
+ data[MEMORY_PERSIST_NAMESPACE] = { enabled: Boolean(enabled) };
325
+ save(data);
326
+ return memoryPersistState();
327
+ }
328
+
329
+ return {
330
+ file,
331
+ get,
332
+ set,
333
+ rawKey,
334
+ remove,
335
+ list,
336
+ maskKey,
337
+ aegisKey,
338
+ aegisRawKey,
339
+ aegisKeySavedAt,
340
+ setAegisKey,
341
+ migrateLegacyAegisKey,
342
+ quickLauncherConfig,
343
+ setQuickLauncherConfig,
344
+ getConfirmMode,
345
+ setConfirmMode,
346
+ getMemoryPersist,
347
+ memoryPersistState,
348
+ setMemoryPersist,
349
+ };
350
+ }
351
+
352
+ module.exports = {
353
+ SETTINGS_FILE,
354
+ AEGIS_KEY_NAMESPACE,
355
+ LEGACY_AEGIS_NAMESPACE,
356
+ QUICK_LAUNCHER_NAMESPACE,
357
+ CONFIRM_MODE_NAMESPACE,
358
+ MEMORY_PERSIST_NAMESPACE,
359
+ DEFAULT_QUICK_LAUNCHER_SHORTCUT,
360
+ RESERVED_NAMESPACES,
361
+ isReservedNamespace,
362
+ maskKey,
363
+ createSettingsStore,
364
+ };
@@ -159,23 +159,54 @@ const RATES = {
159
159
  deepseek: { input: 0.14, output: 0.28, cacheRead: 0.014, cacheWrite: 0.14 },
160
160
  };
161
161
 
162
+ /**
163
+ * The rate rows a model id may name as a whole word rather than as a prefix.
164
+ * Anthropic spells its family *inside* the id — "claude-opus-4" matches no
165
+ * prefix — so prefix matching alone cannot see it.
166
+ */
167
+ const RATE_FAMILIES = Object.keys(RATES).filter((k) => k !== 'default');
168
+
162
169
  /**
163
170
  * The rate row for a model id, provider, or alias. Exact id wins, then the
164
- * longest matching prefix, then the Sonnet-class default.
171
+ * longest matching prefix, then a family named inside the id, then the
172
+ * Sonnet-class default.
165
173
  */
166
174
  function ratesFor(model) {
167
- const id = String(model || '').toLowerCase();
168
- if (!id) return RATES.default;
169
- if (RATES[id]) return RATES[id];
170
- let best = null;
171
- let bestLen = 0;
172
- for (const [prefix, rates] of Object.entries(RATES)) {
173
- if (id.startsWith(prefix) && prefix.length > bestLen) {
174
- best = rates;
175
- bestLen = prefix.length;
175
+ const raw = String(model || '').toLowerCase();
176
+ if (!raw) return RATES.default;
177
+ // A byok model id carries its provider as a routing label:
178
+ // "anthropic:claude-opus-4", "deepseek:deepseek-v4-flash". The label is not
179
+ // a rate, and rating it as written fell through every prefix to
180
+ // RATES.default — so an Opus BYOK turn was priced at Sonnet's $3/$15 against
181
+ // the vendor's real $5/$25. 15x, on the one class whose figure can only ever
182
+ // be an estimate, because there the vendor bills the caller and AEGIS only
183
+ // relays. Try the whole id first, then the model behind the label.
184
+ const ids = [raw];
185
+ const tail = raw.slice(raw.lastIndexOf(':') + 1);
186
+ if (tail && tail !== raw) ids.push(tail);
187
+ for (const id of ids) {
188
+ if (RATES[id]) return RATES[id];
189
+ let best = null;
190
+ let bestLen = 0;
191
+ for (const [prefix, rates] of Object.entries(RATES)) {
192
+ if (id.startsWith(prefix) && prefix.length > bestLen) {
193
+ best = rates;
194
+ bestLen = prefix.length;
195
+ }
196
+ }
197
+ if (best) return best;
198
+ }
199
+ // Longest family-key hit wins, so an overlapping pair resolves the same way
200
+ // twice running rather than by object key order.
201
+ let family = null;
202
+ let familyLen = 0;
203
+ for (const key of RATE_FAMILIES) {
204
+ if (raw.includes(key) && key.length > familyLen) {
205
+ family = RATES[key];
206
+ familyLen = key.length;
176
207
  }
177
208
  }
178
- return best || RATES.default;
209
+ return family || RATES.default;
179
210
  }
180
211
 
181
212
  /**