aegiscode 6.7.5 → 6.7.7

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.
@@ -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
  /**