aegiscode 7.0.26 → 7.0.28

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.
Files changed (118) hide show
  1. package/SOURCE-OFFER.txt +9 -0
  2. package/package.json +4 -7
  3. package/scripts/check.mjs +1 -52
  4. package/scripts/demo.mjs +1 -94
  5. package/scripts/predist.mjs +1 -75
  6. package/scripts/runtests.mjs +1 -56
  7. package/scripts/seal-gate.mjs +1 -74
  8. package/src/agents.js +1 -139
  9. package/src/app.js +1 -2957
  10. package/src/art.js +1 -289
  11. package/src/chatflow.js +1 -3023
  12. package/src/checkpoint.js +1 -90
  13. package/src/clipboard.js +1 -424
  14. package/src/cloudsync.js +1 -528
  15. package/src/commands.js +1 -4089
  16. package/src/config.js +1 -581
  17. package/src/connect.js +1 -349
  18. package/src/credentials.js +1 -33
  19. package/src/deps.js +1 -232
  20. package/src/devrun.js +1 -187
  21. package/src/diff.js +1 -333
  22. package/src/diffview.js +1 -296
  23. package/src/engine.js +1 -297
  24. package/src/entitlement.js +1 -355
  25. package/src/events.js +1 -707
  26. package/src/export.js +1 -67
  27. package/src/filepreview.js +1 -153
  28. package/src/fingerprint.js +1 -592
  29. package/src/format.js +1 -259
  30. package/src/fuzzy.js +1 -119
  31. package/src/history.js +1 -423
  32. package/src/init.js +1 -175
  33. package/src/input.js +1 -139
  34. package/src/keys.js +1 -183
  35. package/src/markdown.js +1 -306
  36. package/src/models.js +1 -507
  37. package/src/naming.js +1 -57
  38. package/src/overlays.js +1 -462
  39. package/src/panels.js +1 -1418
  40. package/src/ping.js +1 -226
  41. package/src/presence.js +1 -238
  42. package/src/render.js +1 -516
  43. package/src/screen.js +1 -518
  44. package/src/screens.js +1 -896
  45. package/src/secret.js +1 -59
  46. package/src/securefs.js +1 -359
  47. package/src/settings.js +1 -155
  48. package/src/shared.js +1 -52
  49. package/src/sharedpaths.js +1 -53
  50. package/src/signup.js +1 -156
  51. package/src/summarize.js +1 -95
  52. package/src/sysdiag.js +1 -585
  53. package/src/system.js +1 -40
  54. package/src/theme.js +1 -570
  55. package/src/title.js +1 -220
  56. package/src/todos.js +1 -115
  57. package/src/tokens.js +1 -263
  58. package/src/topup.js +1 -210
  59. package/src/update.js +1 -191
  60. package/vendor/client/aegis.js +1 -2441
  61. package/vendor/client/attest.js +1 -518
  62. package/vendor/client/authorship-key.js +1 -410
  63. package/vendor/client/auto-provision.js +1 -134
  64. package/vendor/client/brain-catalog.js +1 -268
  65. package/vendor/client/byok-catalog.js +1 -199
  66. package/vendor/client/catalog-client.js +1 -487
  67. package/vendor/client/conversation-export.js +1 -177
  68. package/vendor/client/credentials.js +1 -494
  69. package/vendor/client/device-fingerprint.js +1 -141
  70. package/vendor/client/drive-connect.js +1 -110
  71. package/vendor/client/drive-upload.js +1 -234
  72. package/vendor/client/env-file.js +1 -1273
  73. package/vendor/client/fingerprint.js +1 -1064
  74. package/vendor/client/foreign-memory.js +1 -669
  75. package/vendor/client/google-signin.js +1 -133
  76. package/vendor/client/hooks.js +1 -430
  77. package/vendor/client/model-discovery.js +1 -373
  78. package/vendor/client/naming.js +1 -283
  79. package/vendor/client/platform.js +1 -937
  80. package/vendor/client/prefs.js +1 -351
  81. package/vendor/client/presence-constants.js +1 -107
  82. package/vendor/client/presence.js +1 -438
  83. package/vendor/client/record-vault.js +3 -1055
  84. package/vendor/client/session-store.js +1 -575
  85. package/vendor/client/topup.js +1 -297
  86. package/vendor/client/touch.js +1 -458
  87. package/vendor/client/update.js +1 -763
  88. package/vendor/client/user-models.js +1 -381
  89. package/vendor/desktop/lib/local/agents.js +1 -105
  90. package/vendor/desktop/lib/local/attachments.js +1 -276
  91. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  92. package/vendor/desktop/lib/local/claude-pro.js +1 -1028
  93. package/vendor/desktop/lib/local/context.js +1 -125
  94. package/vendor/desktop/lib/local/engine.js +1 -3666
  95. package/vendor/desktop/lib/local/entitlement.js +1 -660
  96. package/vendor/desktop/lib/local/exec-plan.js +1 -269
  97. package/vendor/desktop/lib/local/git-scope.js +1 -228
  98. package/vendor/desktop/lib/local/integrity.js +1 -163
  99. package/vendor/desktop/lib/local/local.js +1 -2145
  100. package/vendor/desktop/lib/local/prompt.js +1 -280
  101. package/vendor/desktop/lib/local/queue.js +1 -560
  102. package/vendor/desktop/lib/local/session-rounds.js +1 -238
  103. package/vendor/desktop/lib/local/shell.js +1 -712
  104. package/vendor/desktop/lib/local/spill.js +1 -75
  105. package/vendor/desktop/lib/local/tools.js +1 -1328
  106. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  107. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  108. package/vendor/desktop/lib/settings.js +1 -890
  109. package/vendor/desktop/main.js +1 -4890
  110. package/vendor/desktop/renderer/usage.js +1 -1239
  111. package/vendor/hosts/install.js +1 -638
  112. package/vendor/hosts/openai-shim.js +1 -515
  113. package/vendor/hosts/spec.js +1 -164
  114. package/vendor/hosts/targets.js +1 -346
  115. package/vendor/mcp/server.js +1 -221
  116. package/vendor/mcp/tools.js +1 -408
  117. package/vendor/one/src/child.js +1 -285
  118. package/vendor/one/src/permissions.js +1 -383
package/src/config.js CHANGED
@@ -1,583 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * User config + permissions persistence (~/.aegiscode/config.json and
10
- * permissions.json). Honors AEGISCODE_HOME so tests and side-by-side installs
11
- * can redirect the data dir. Reads and writes are best-effort: a corrupt
12
- * config falls back to defaults, and write failures never crash the session.
13
- *
14
- * Ported from the upstream engine reference (ESM → CommonJS). The data dir was
15
- * renamed ~/.aegiscodex → ~/.aegiscode and the override env var
16
- * AEGISCODEX_HOME → AEGISCODE_HOME; `aegisDir` is the one shared helper every
17
- * other module imports rather than recomputing the path.
18
- */
19
-
20
- const fs = require('node:fs');
21
- const path = require('node:path');
22
- const { writePrivateFile } = require('./securefs.js');
23
-
24
- // The data dir is defined once, in the shared credential module, because the
25
- // desktop app and the MCP plugin now read and write the same store: a second
26
- // definition here is how the hosts would drift back apart.
27
- const { credentials, prefs } = require('./shared.js');
28
-
29
- /** Data directory: $AEGISCODE_HOME or ~/.aegiscode (see client/credentials.js). */
30
- function aegisDir(env) {
31
- return credentials.aegisHome(env);
32
- }
33
-
34
- /**
35
- * The host-local config file (`$AEGISCODE_HOME/config.json`).
36
- *
37
- * Since AEGISONE D5 this holds only what is HOST-LOCAL: the update-check cache,
38
- * `lastCwd`, and anything the CLI alone owns (a stored `provider`/`baseURL` row,
39
- * the `light` palette flag). Non-secret *preferences* live in the shared store
40
- * (`$AEGISCODE_HOME/preferences.json`, client/prefs.js) so the window and the
41
- * shell read one value instead of two that can disagree — see `SHARED_KEYS`, and
42
- * `loadConfig()`/`updateConfig()` for the split and the one-way migration.
43
- */
44
- function configPath() {
45
- return path.join(aegisDir(), 'config.json');
46
- }
47
-
48
- /** The shared non-secret preference file the desktop's settings store writes too. */
49
- function prefsPath() {
50
- return prefs.prefsFile({ dir: aegisDir() });
51
- }
52
-
53
- /**
54
- * True once the user has run before — the config file is written during
55
- * onboarding (and on the first preference change). Used to gate the trust
56
- * check + theme picker to a genuine first run: re-showing them every launch
57
- * wiped the screen with the theme picker and discarded the prior session.
58
- */
59
- function configExists() {
60
- try { return fs.existsSync(configPath()); } catch { return false; }
61
- }
62
-
63
- function permissionsPath() {
64
- return path.join(aegisDir(), 'permissions.json');
65
- }
66
-
67
- const DEFAULT_CONFIG = {
68
- themeIndex: 1, // Dark mode
69
- // Cached `{ checkedAt, latest }` from the once-a-day registry check (see
70
- // src/update.js). Persisted so a launch reports what the LAST run learned
71
- // and never waits on the network to draw its own welcome box.
72
- updateCheck: null,
73
- // Cached `{ checkedAt, behind, required, latest, downloadUrl }` from the
74
- // once-a-day SERVER check (/api/v1/version, see src/update.js). Separate
75
- // from `updateCheck` because it answers a different question: the registry
76
- // says what was published, the server says what it will still serve. A
77
- // build can be merely superseded (a suggestion) or refused (an outage), and
78
- // collapsing the two would report the wrong urgency.
79
- updateCheckServer: null,
80
- // No pinned model. This host runs on AEGIS Cloud, whose pinnable ids are the
81
- // server's (`/models`) — a client-side default here would have to name one,
82
- // and the one it named (`sonnet`) is not advertised by the platform at all:
83
- // the pool accepts an unknown id and answers from its own default with no
84
- // error, so the pin looked honoured while the reply came from another model.
85
- // Worse, onboarding persists this object on first run (`updateConfig` merges
86
- // DEFAULT_CONFIG under the patch), so the phantom pin was written to disk for
87
- // every user who ever completed the trust check. `null` = no pin; the server
88
- // chooses, and app.js's validatePinnedModel() clears a stored id the catalog
89
- // does not advertise.
90
- model: null,
91
- // Which class turns run on: 'aegis' (the pool, authenticated and paid for by
92
- // the account key) or 'byok' (the user's own provider key, relayed and billed
93
- // a handling fee). Persisted so `/class byok` survives a restart — a class
94
- // choice that silently reverted would send the next launch's turn somewhere
95
- // the user did not choose, and on a BYOK setup there is no pooled key to fall
96
- // back to. Defaulted to the pooled class, which is the only one an account
97
- // key alone can run.
98
- modelClass: 'aegis',
99
- // Whether the `pro` class may be selected at all. OFF by default, and it
100
- // takes a deliberate `/class pro on` to turn it on — this is a one-time
101
- // opt-in, not a preference that drifts back.
102
- //
103
- // The reason is the failure this flag exists to prevent: `pro` spends a real
104
- // Claude Code Pro/Max subscription by spawning the `claude` CLI, and an
105
- // account whose organization has disabled Claude Code access answers every
106
- // such turn with `oauth_org_not_allowed` ("Your organization has disabled
107
- // Claude subscription access"). Nothing in this repo can re-enable that, so
108
- // a default of "offered" meant the Class picker, the `/model` list and the
109
- // anthropic→pro override all steered users into turns that could only fail.
110
- // Off by default means a machine that never asked for the subscription route
111
- // never lands on it; `/class pro on` is the single, explicit way in.
112
- proEnabled: false,
113
- // The full model table (seeded from src/models.js MODELS on first
114
- // read by pickerModels()). 'currentModelId' mirrors `model` under the
115
- // aegiscode- name so /model add/remove/switch stay compatible both ways.
116
- models: null,
117
- currentModelId: null,
118
- // The effort rung every turn is sized from, stored as a real level so the
119
- // value read back is the value sent. It used to be `null` ("auto": send no
120
- // rung and let the server infer one from the ask), which made the DEFAULT a
121
- // no-op — a fresh install carried no effort at all, so low/medium/high only
122
- // ever changed the status line. `high` is the rung the engine and the desktop
123
- // resolve an absent value to, so the default is now stated rather than
124
- // implied. Anything unreadable (null, a stale 'auto', junk) is coerced to
125
- // `high` by effortRung() in cli/src/engine.js before it reaches the wire.
126
- effort: 'high',
127
- vim: false,
128
- lastCwd: '',
129
- };
130
-
131
- // ── persisting memory (the WRITE half of aegis_memory) ──────────────────────
132
-
133
- /**
134
- * Cross-session memory has two halves. The READ half (`aegis_recall`) is sent
135
- * unconditionally by both hosts — it is cheap, it is what lets an interrupted
136
- * turn be picked up in a later session, and it is free on every plan. The
137
- * WRITE half is what actually stored anything, and it used to sit behind
138
- * `cloudSync`, which is absent (i.e. off) on every fresh install. That is the
139
- * defect this key replaces: the copy promises "cross-session memory free with
140
- * any account", the read half shipped to everybody, and the write half — the
141
- * half that makes the promise true — was opt-in and undiscoverable.
142
- *
143
- * So the gate is now `memoryPersist` and it defaults ON. It stays a real gate:
144
- * `/cloud memory off` (or `/sync off`) writes it false, and this resolver
145
- * honours it. The write half also has a price, so the ceiling is surfaced
146
- * rather than guessed at — aegis1 meters WRITES only (FREE_SYNC_TOKENS = 1 MB,
147
- * PRO_SYNC_TOKENS = 10 MB); reads keep working past it. `/cloud memory` and the
148
- * first-run notice state that in those words.
149
- *
150
- * Migration, not a reset. `loadConfig()` merges DEFAULT_CONFIG under the parsed
151
- * file, so the *absence* of a key cannot be told from a default once merged —
152
- * that is why this resolver reads the raw values in the order below instead of
153
- * checking a merged boolean:
154
- *
155
- * memoryPersist (explicit) → cloudSync (an explicit pre-flip choice)
156
- * → MEMORY_PERSIST_DEFAULT (on)
157
- *
158
- * An explicit `cloudSync: false` on disk therefore stays off (nobody who turned
159
- * sync off gets quietly opted back in), an explicit `cloudSync: true` stays on,
160
- * and a config with neither key becomes on. `setMemoryPersist()` then removes
161
- * the legacy key, so the choice exists in exactly one place from then on.
162
- */
163
- const MEMORY_PERSIST_KEY = 'memoryPersist';
164
- const LEGACY_MEMORY_PERSIST_KEY = 'cloudSync';
165
- const MEMORY_PERSIST_DEFAULT = true;
166
-
167
- /**
168
- * Resolve the write half, with where the answer came from.
169
- *
170
- * @param {object} [cfg] a loaded config (defaults to `loadConfig()`).
171
- * @returns {{enabled:boolean, source:'config'|'legacy'|'default'}}
172
- * `explicit` is true for the first two — that is the distinction the
173
- * status panels need to say "you turned this off" vs "this is the
174
- * default", which is the difference between a setting and a rumour.
175
- */
176
- function memoryPersistState(cfg) {
177
- let c = cfg;
178
- if (!c) {
179
- try {
180
- c = loadConfig();
181
- } catch {
182
- return { enabled: MEMORY_PERSIST_DEFAULT, source: 'default', explicit: false };
183
- }
184
- }
185
- if (c && typeof c[MEMORY_PERSIST_KEY] === 'boolean') {
186
- return { enabled: c[MEMORY_PERSIST_KEY], source: 'config', explicit: true };
187
- }
188
- if (c && typeof c[LEGACY_MEMORY_PERSIST_KEY] === 'boolean') {
189
- return { enabled: c[LEGACY_MEMORY_PERSIST_KEY], source: 'legacy', explicit: true };
190
- }
191
- return { enabled: MEMORY_PERSIST_DEFAULT, source: 'default', explicit: false };
192
- }
193
-
194
- /** True when this host should persist memory (default on — see above). */
195
- function memoryPersistEnabled(cfg) {
196
- return memoryPersistState(cfg).enabled;
197
- }
198
-
199
- /**
200
- * Persist the flip, and retire the legacy key in the same write so the two can
201
- * never disagree. `undefined` (not `false`) is what removes a key through
202
- * JSON.stringify — writing `false` would look like an explicit opt-out under
203
- * the legacy name.
204
- */
205
- function setMemoryPersist(on) {
206
- return updateConfig({
207
- [MEMORY_PERSIST_KEY]: on === true,
208
- [LEGACY_MEMORY_PERSIST_KEY]: undefined,
209
- });
210
- }
211
-
212
- /**
213
- * The config keys that live in the SHARED store (D5) rather than in this host's
214
- * config.json: the non-secret preferences the window and the shell must agree
215
- * about. The list itself lives in client/prefs.js (`SHARED_PREF_KEYS`) because
216
- * the desktop's settings store reads it too — one definition, two readers.
217
- */
218
- const SHARED_KEYS = new Set(prefs.SHARED_PREF_KEYS);
219
-
220
- /** The subset of `obj` whose keys live in the shared store. */
221
- function pickShared(obj) {
222
- const out = {};
223
- for (const k of Object.keys(obj || {})) if (SHARED_KEYS.has(k)) out[k] = obj[k];
224
- return out;
225
- }
226
-
227
- /** Read the host-local config file (never throws; {} when absent/corrupt). */
228
- function readHostConfig() {
229
- try {
230
- const parsed = JSON.parse(fs.readFileSync(configPath(), 'utf8'));
231
- if (parsed && typeof parsed === 'object') return parsed;
232
- } catch {}
233
- return {};
234
- }
235
-
236
- /** Read the shared preference store (`$AEGISCODE_HOME/preferences.json`). */
237
- function readSharedPrefs() {
238
- try {
239
- return prefs.load({ dir: aegisDir() });
240
- } catch {
241
- return {};
242
- }
243
- }
244
-
245
- /**
246
- * Read the config, falling back to defaults (never throws).
247
- *
248
- * Three layers, lowest first: `DEFAULT_CONFIG`, this host's config.json, the
249
- * shared preference store. The shared store wins because it is the store both
250
- * faces write — reading it second is what makes a preference set in the window
251
- * visible in the shell with no cloud round trip.
252
- *
253
- * A config.json written by an older CLI still holds the shared keys inline
254
- * (`themeIndex`, `model`, `effort`, …). That legacy copy is read here — this is
255
- * the read half of the one-way migration — but never written back: the next
256
- * `updateConfig()` moves it into the shared store and drops it from
257
- * config.json, so one preference ends up in exactly one place.
258
- */
259
- function loadConfig() {
260
- const host = readHostConfig();
261
- const shared = readSharedPrefs();
262
- const merged = { ...DEFAULT_CONFIG, ...host };
263
- const migrated = {};
264
- for (const k of SHARED_KEYS) {
265
- const inHost = host[k] !== undefined;
266
- const inShared = shared[k] !== undefined;
267
- if (inHost && inShared) {
268
- // The shared store outranks the host copy — except when its value is an
269
- // explicit `null` and the host copy is a real one. `sharedView()` writes
270
- // EVERY shared key on every save, filling an unset `model`/`effort` with
271
- // its `DEFAULT_CONFIG` value, so `null` there is usually the default and
272
- // not a decision. Reading it as one swallowed a legacy pin: a config.json
273
- // from a pre-D5 CLI keeps `model` inline, and the moment the new code
274
- // saved any other preference it also wrote `model: null` to the shared
275
- // store, which then beat the pin on every launch. That made the read half
276
- // of the one-way migration described above dead code — the exact
277
- // regression `test/cli-models.test.mjs` pins. A real value in the shared
278
- // store still wins (that is what makes a pin chosen in the window visible
279
- // in the shell), and once `updateConfig()` runs, shared keys are dropped
280
- // from config.json, so there is no stale host copy left to prefer.
281
- migrated[k] = shared[k] === null && host[k] !== null ? host[k] : shared[k];
282
- } else if (inHost) {
283
- migrated[k] = host[k];
284
- } else if (inShared) {
285
- migrated[k] = shared[k];
286
- }
287
- }
288
- return { ...merged, ...migrated };
289
- }
290
-
291
- /**
292
- * The shared store's view of this config.
293
- *
294
- * `model: null` / `effort: null` are written out explicitly rather than left
295
- * absent: the shared document is the resolved preference set both faces read,
296
- * and "no pin" is itself a stored decision (`DEFAULT_CONFIG` says so, and
297
- * `validatePinnedModel()` clears a phantom pin by writing `null`).
298
- *
299
- * `memoryPersist` is the one exception, and deliberately: filling it with the
300
- * default would defeat `memoryPersistState()`'s legacy migration, which exists
301
- * so that an explicit pre-flip `cloudSync: false` on disk is never quietly
302
- * opted back in. So it is written only when it is actually known — set by this
303
- * patch, already in the shared store, already in config.json, or stated by the
304
- * legacy `cloudSync` key.
305
- *
306
- * `confirmMode` (ON8) is the second, for the same reason and one more: it is a
307
- * posture, and `DEFAULT_CONFIG` has no entry for it, so the default-fill would
308
- * have written `undefined` — which `prefs.set()` drops. Every unrelated config
309
- * save (`/theme`, onboarding, an update-check cache write) would then DELETE the
310
- * gate's one shared copy, silently reverting the window's switch and the shell's
311
- * `/automode` (alias `/yolo`) to the rule file on the next launch. And filling it with `true` instead
312
- * would be worse, not better: an install whose desktop still holds a legacy
313
- * `__confirmMode: { enabled: false }` would be flipped ON by the first CLI save,
314
- * which is exactly the migration `client/prefs.js`'s `adopt()` exists to get
315
- * right. So: written when this patch states it, or when the store already has
316
- * one, and otherwise left alone for the rule file to answer.
317
- */
318
- const WRITE_WHEN_KNOWN = new Set(['memoryPersist', 'confirmMode']);
319
-
320
- function sharedView(patch, host, shared) {
321
- const view = {};
322
- for (const k of SHARED_KEYS) {
323
- if (WRITE_WHEN_KNOWN.has(k)) continue;
324
- if (patch[k] !== undefined) view[k] = patch[k];
325
- else if (shared[k] !== undefined) view[k] = shared[k];
326
- else if (host[k] !== undefined) view[k] = host[k];
327
- else view[k] = DEFAULT_CONFIG[k];
328
- }
329
- if (patch.memoryPersist !== undefined) view.memoryPersist = patch.memoryPersist;
330
- else if (shared.memoryPersist !== undefined) view.memoryPersist = shared.memoryPersist;
331
- else if (host.memoryPersist !== undefined) view.memoryPersist = host.memoryPersist;
332
- else if (typeof host[LEGACY_MEMORY_PERSIST_KEY] === 'boolean') {
333
- view.memoryPersist = host[LEGACY_MEMORY_PERSIST_KEY];
334
- }
335
- if (patch.confirmMode !== undefined) view.confirmMode = patch.confirmMode;
336
- else if (shared.confirmMode !== undefined) view.confirmMode = shared.confirmMode;
337
- return view;
338
- }
339
-
340
- /**
341
- * Merge a patch into the config on disk and return the merged config.
342
- *
343
- * Split by destination, never duplicated: the shared keys go to
344
- * `$AEGISCODE_HOME/preferences.json`, everything else to this host's
345
- * config.json (with any shared key a legacy file still carries dropped, which
346
- * completes the one-way migration). A no-op that still returns the merged view
347
- * when a file cannot be written.
348
- */
349
- function updateConfig(patch) {
350
- const p = patch || {};
351
- const host = readHostConfig();
352
- const sharedNow = readSharedPrefs();
353
- const sharedKeys = pickShared(p);
354
- const hostKeys = { ...p };
355
- for (const k of SHARED_KEYS) delete hostKeys[k];
356
-
357
- try {
358
- prefs.set(sharedView(p, host, sharedNow), { dir: aegisDir() });
359
- } catch (e) {
360
- if (process.env.AEGIS_HIST_DEBUG) console.error('[prefs] write failed:', e);
361
- }
362
-
363
- const hostNext = { ...DEFAULT_CONFIG, ...host, ...hostKeys };
364
- for (const k of SHARED_KEYS) delete hostNext[k];
365
- try {
366
- // Atomic (tmp + rename) so a crash can't corrupt it, and written 0600:
367
- // config.json carries `provider` and `baseURL`, so a group-writable copy is
368
- // a way for another local account to repoint the session's endpoint.
369
- writePrivateFile(configPath(), JSON.stringify(hostNext, null, 2) + '\n');
370
- } catch (e) {
371
- if (process.env.AEGIS_HIST_DEBUG) console.error('[config] write failed:', e);
372
- }
373
- return loadConfig();
374
- }
375
-
376
- // ── Permissions (~/.aegiscode/permissions.json) ─────────────────────────────
377
-
378
- const DEFAULT_PERMISSIONS = {
379
- defaultMode: 'ask', // 'ask' | 'allow' | 'deny'
380
- allow: [], // ["Bash(npm run *)", "Edit(src/**)"]
381
- deny: [],
382
- ask: [],
383
- };
384
-
385
- /**
386
- * Read permission rules, falling back to the empty default (never throws).
387
- * `explicitAsk` is true only when the permissions file *explicitly* writes
388
- * `"defaultMode": "ask"`. The file-free default is also 'ask', but it must
389
- * not trigger a prompt on every call out of the box — evalPermission only
390
- * consults explicitAsk, so the distinction matters.
391
- */
392
- function loadPermissions() {
393
- try {
394
- const raw = fs.readFileSync(permissionsPath(), 'utf8');
395
- const parsed = JSON.parse(raw);
396
- if (parsed && typeof parsed === 'object') {
397
- return {
398
- ...DEFAULT_PERMISSIONS,
399
- allow: Array.isArray(parsed.allow) ? parsed.allow : [],
400
- deny: Array.isArray(parsed.deny) ? parsed.deny : [],
401
- ask: Array.isArray(parsed.ask) ? parsed.ask : [],
402
- defaultMode: parsed.defaultMode || DEFAULT_PERMISSIONS.defaultMode,
403
- explicitAsk: parsed.defaultMode === 'ask',
404
- };
405
- }
406
- } catch {}
407
- return { ...DEFAULT_PERMISSIONS, allow: [], deny: [], ask: [], explicitAsk: false };
408
- }
409
-
410
- /** Persist permission rules. Returns the saved rules (or the input on failure). */
411
- function savePermissions(rules) {
412
- try {
413
- // 0600: the rules decide which tools run without a prompt, so a writable
414
- // copy is a way to pre-approve the next session's tool calls.
415
- writePrivateFile(permissionsPath(), JSON.stringify(rules, null, 2) + '\n');
416
- } catch (e) {
417
- if (process.env.AEGIS_HIST_DEBUG) console.error('[permissions] write failed:', e);
418
- }
419
- return rules;
420
- }
421
-
422
- /**
423
- * Write the rule file's residual mode WITHOUT the DERIVED `explicitAsk` field.
424
- *
425
- * `explicitAsk` is computed by loadPermissions() from `defaultMode`; it is a
426
- * read-time derivation, not stored state. Spreading `{ ...loadPermissions() }`
427
- * carries the value derived from the file being replaced, so `/confirm on` used
428
- * to leave `{"defaultMode":"ask","explicitAsk":false}` — a file that denies the
429
- * very field it sets — and `/confirm off` left `{"defaultMode":"allow",
430
- * "explicitAsk":true}`, which is worse: two fields disagreeing about whether
431
- * the user ever asked to be prompted.
432
- *
433
- * Harmless only while every reader recomputes (loadPermissions does), and a real
434
- * bug the moment one does not: `one/src/permissions.js` builds its rule set from
435
- * the file's `explicitAsk` as well as its `defaultMode`, and an operator reading
436
- * permissions.json to answer "is confirmation on?" reads the stale line. Every
437
- * writer here goes through this, so the file always says exactly one thing.
438
- *
439
- * This mirrors the engine's `persistRules` (aegiscodex-dev src/registry.js,
440
- * commit e7bb9db, "a switch that turns off"); the plugin's CLI face was the copy
441
- * that never got it.
442
- */
443
- function saveRuleMode(mode) {
444
- const { explicitAsk, ...rest } = loadPermissions();
445
- return savePermissions({ ...rest, defaultMode: mode });
446
- }
447
-
448
- /**
449
- * Add a rule to a permission list if not already present.
450
- * Returns { added, rules } — added is false when the rule already exists.
451
- */
452
- function addPermissionRule(list, pattern, rules) {
453
- const key = list === 'allow' || list === 'deny' || list === 'ask' ? list : 'allow';
454
- const patterns = rules[key];
455
- if (patterns.includes(pattern)) return { added: false, rules };
456
- return { added: true, rules: { ...rules, [key]: [...patterns, pattern] } };
457
- }
458
-
459
- /** Remove a rule from a permission list. Returns { removed, rules }. */
460
- function removePermissionRule(list, pattern, rules) {
461
- const key = list === 'allow' || list === 'deny' || list === 'ask' ? list : 'allow';
462
- const patterns = rules[key].filter((p) => p !== pattern);
463
- return { removed: patterns.length !== rules[key].length, rules: { ...rules, [key]: patterns } };
464
- }
465
-
466
- // ── The confirmation posture (AEGISONE ON8, decision D8 rule 1) ─────────────
467
- //
468
- // "One posture, two faces": the window's *Confirm before running tools* switch
469
- // and this face's gate (app.js's `getConfirmMode`, which the engine reads on
470
- // every tool round) answer the same question — may a mutating call run
471
- // unattended? — so they are one value, stored once, in the shared preference
472
- // store both hosts read (`confirmMode`).
473
- //
474
- // Why the writer lives HERE and not in permissions.js: this module owns BOTH
475
- // files, so it is the only place that can keep them consistent in one step.
476
- // permissions.json's `defaultMode` is NOT a second copy of the posture to be
477
- // retired — it is a field of the rule schema `evalPermission` reads (an
478
- // explicit `ask` is what makes the rule engine prompt on an unmatched call), so
479
- // it stays, and it is written in lockstep with the shared key. Then the read
480
- // order below is consistent by construction: the shared key answers, and it
481
- // cannot disagree with the file because nothing writes one without the other.
482
- //
483
- // Rule 2 is untouched and unreachable from here: the ÆGIS covenant's
484
- // `preActionAssert` and the avatar's `write|shell|network|offDevice` approvals
485
- // are asserted above this gate, in the engine, on purpose (see
486
- // desktop/lib/local/engine.js's "DO NOT MOVE THIS BELOW A SHORT-CIRCUIT"). A
487
- // posture is the *configurable* half and can only ever move that half.
488
-
489
- /**
490
- * The posture, resolved from the two stores, shared store first.
491
- *
492
- * @returns {{enabled: boolean, source: 'shared'|'rules'|'default'}}
493
- * `enabled` true means the gate is UP (confirmations on), which is the
494
- * polarity the window's switch and `getConfirmMode()` both use.
495
- *
496
- * `rules` is the un-migrated fallback rather than a competitor: an install that
497
- * never touched the switch has no `confirmMode` key and is answered by its rule
498
- * file exactly as it was before this phase. Nothing here throws — a store that
499
- * cannot be read keeps the gate UP, never off.
500
- */
501
- function confirmPosture() {
502
- try {
503
- const shared = readSharedPrefs().confirmMode;
504
- if (typeof shared === 'boolean') return { enabled: shared, source: 'shared' };
505
- } catch {
506
- /* fall through to the rule file, then the safe default */
507
- }
508
- try {
509
- const parsed = JSON.parse(fs.readFileSync(permissionsPath(), 'utf8'));
510
- if (parsed && typeof parsed === 'object' && typeof parsed.defaultMode === 'string') {
511
- // The pre-ON8 reading, verbatim: anything that is not an explicit `allow`
512
- // leaves the gate up.
513
- return { enabled: parsed.defaultMode !== 'allow', source: 'rules' };
514
- }
515
- } catch {
516
- /* absent or corrupt: the default below is ON */
517
- }
518
- return { enabled: true, source: 'default' };
519
- }
520
-
521
- /**
522
- * Set the posture: the shared key (both faces) + the rule file's residual.
523
- *
524
- * Called by every command that means "confirmations on/off" — /confirm,
525
- * /automode (alias /yolo), /multiyolo and the flag the desktop's switch mirrors — so there is exactly one
526
- * writer per fact and no command can leave the two stores disagreeing.
527
- */
528
- function setConfirmPosture(enabled) {
529
- const want = Boolean(enabled);
530
- try {
531
- prefs.set({ confirmMode: want }, { dir: aegisDir() });
532
- } catch (e) {
533
- if (process.env.AEGIS_HIST_DEBUG) console.error('[prefs] write failed:', e);
534
- }
535
- saveRuleMode(want ? 'ask' : 'allow');
536
- return want;
537
- }
538
-
539
- /**
540
- * `/permissions default <ask|allow|deny>` — the residual mode, and the posture
541
- * that follows from it.
542
- *
543
- * `ask`/`allow` ARE the posture (`setConfirmPosture`). `deny` is not: there is
544
- * no "confirmations: deny" switch, so the residual is written to the file while
545
- * the posture stays UP — a default of `deny` must not be implemented as a gate
546
- * that stopped asking.
547
- */
548
- function setPermissionDefaultMode(mode) {
549
- const want = mode === 'allow' ? 'allow' : mode === 'deny' ? 'deny' : 'ask';
550
- try {
551
- prefs.set({ confirmMode: want !== 'allow' }, { dir: aegisDir() });
552
- } catch (e) {
553
- if (process.env.AEGIS_HIST_DEBUG) console.error('[prefs] write failed:', e);
554
- }
555
- saveRuleMode(want);
556
- return want;
557
- }
558
-
559
- module.exports = {
560
- aegisDir,
561
- configPath,
562
- prefsPath,
563
- configExists,
564
- permissionsPath,
565
- DEFAULT_CONFIG,
566
- loadConfig,
567
- updateConfig,
568
- MEMORY_PERSIST_KEY,
569
- LEGACY_MEMORY_PERSIST_KEY,
570
- MEMORY_PERSIST_DEFAULT,
571
- memoryPersistState,
572
- memoryPersistEnabled,
573
- setMemoryPersist,
574
- DEFAULT_PERMISSIONS,
575
- loadPermissions,
576
- savePermissions,
577
- saveRuleMode,
578
- addPermissionRule,
579
- removePermissionRule,
580
- confirmPosture,
581
- setConfirmPosture,
582
- setPermissionDefaultMode,
583
- };
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{writePrivateFile:writePrivateFile}=require("./securefs.js"),{credentials:credentials,prefs:prefs}=require("./shared.js");function aegisDir(e){return credentials.aegisHome(e)}function configPath(){return path.join(aegisDir(),"config.json")}function prefsPath(){return prefs.prefsFile({dir:aegisDir()})}function configExists(){try{return fs.existsSync(configPath())}catch{return!1}}function permissionsPath(){return path.join(aegisDir(),"permissions.json")}const DEFAULT_CONFIG={themeIndex:1,updateCheck:null,updateCheckServer:null,model:null,modelClass:"aegis",proEnabled:!1,models:null,currentModelId:null,effort:"high",vim:!1,lastCwd:""},MEMORY_PERSIST_KEY="memoryPersist",LEGACY_MEMORY_PERSIST_KEY="cloudSync",MEMORY_PERSIST_DEFAULT=!0;function memoryPersistState(e){let r=e;if(!r)try{r=loadConfig()}catch{return{enabled:MEMORY_PERSIST_DEFAULT,source:"default",explicit:!1}}return r&&"boolean"==typeof r[MEMORY_PERSIST_KEY]?{enabled:r[MEMORY_PERSIST_KEY],source:"config",explicit:!0}:r&&"boolean"==typeof r[LEGACY_MEMORY_PERSIST_KEY]?{enabled:r[LEGACY_MEMORY_PERSIST_KEY],source:"legacy",explicit:!0}:{enabled:MEMORY_PERSIST_DEFAULT,source:"default",explicit:!1}}function memoryPersistEnabled(e){return memoryPersistState(e).enabled}function setMemoryPersist(e){return updateConfig({[MEMORY_PERSIST_KEY]:!0===e,[LEGACY_MEMORY_PERSIST_KEY]:void 0})}const SHARED_KEYS=new Set(prefs.SHARED_PREF_KEYS);function pickShared(e){const r={};for(const s of Object.keys(e||{}))SHARED_KEYS.has(s)&&(r[s]=e[s]);return r}function readHostConfig(){try{const e=JSON.parse(fs.readFileSync(configPath(),"utf8"));if(e&&"object"==typeof e)return e}catch{}return{}}function readSharedPrefs(){try{return prefs.load({dir:aegisDir()})}catch{return{}}}function loadConfig(){const e=readHostConfig(),r=readSharedPrefs(),s={...DEFAULT_CONFIG,...e},o={};for(const s of SHARED_KEYS){const t=void 0!==e[s],i=void 0!==r[s];t&&i?o[s]=null===r[s]&&null!==e[s]?e[s]:r[s]:t?o[s]=e[s]:i&&(o[s]=r[s])}return{...s,...o}}const WRITE_WHEN_KNOWN=new Set(["memoryPersist","confirmMode"]);function sharedView(e,r,s){const o={};for(const t of SHARED_KEYS)WRITE_WHEN_KNOWN.has(t)||(void 0!==e[t]?o[t]=e[t]:void 0!==s[t]?o[t]=s[t]:void 0!==r[t]?o[t]=r[t]:o[t]=DEFAULT_CONFIG[t]);return void 0!==e.memoryPersist?o.memoryPersist=e.memoryPersist:void 0!==s.memoryPersist?o.memoryPersist=s.memoryPersist:void 0!==r.memoryPersist?o.memoryPersist=r.memoryPersist:"boolean"==typeof r[LEGACY_MEMORY_PERSIST_KEY]&&(o.memoryPersist=r[LEGACY_MEMORY_PERSIST_KEY]),void 0!==e.confirmMode?o.confirmMode=e.confirmMode:void 0!==s.confirmMode&&(o.confirmMode=s.confirmMode),o}function updateConfig(e){const r=e||{},s=readHostConfig(),o=readSharedPrefs(),t=(pickShared(r),{...r});for(const e of SHARED_KEYS)delete t[e];try{prefs.set(sharedView(r,s,o),{dir:aegisDir()})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[prefs] write failed:",e)}const i={...DEFAULT_CONFIG,...s,...t};for(const e of SHARED_KEYS)delete i[e];try{writePrivateFile(configPath(),JSON.stringify(i,null,2)+"\n")}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[config] write failed:",e)}return loadConfig()}const DEFAULT_PERMISSIONS={defaultMode:"ask",allow:[],deny:[],ask:[]};function loadPermissions(){try{const e=fs.readFileSync(permissionsPath(),"utf8"),r=JSON.parse(e);if(r&&"object"==typeof r)return{...DEFAULT_PERMISSIONS,allow:Array.isArray(r.allow)?r.allow:[],deny:Array.isArray(r.deny)?r.deny:[],ask:Array.isArray(r.ask)?r.ask:[],defaultMode:r.defaultMode||DEFAULT_PERMISSIONS.defaultMode,explicitAsk:"ask"===r.defaultMode}}catch{}return{...DEFAULT_PERMISSIONS,allow:[],deny:[],ask:[],explicitAsk:!1}}function savePermissions(e){try{writePrivateFile(permissionsPath(),JSON.stringify(e,null,2)+"\n")}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[permissions] write failed:",e)}return e}function saveRuleMode(e){const{explicitAsk:r,...s}=loadPermissions();return savePermissions({...s,defaultMode:e})}function addPermissionRule(e,r,s){const o="allow"===e||"deny"===e||"ask"===e?e:"allow",t=s[o];return t.includes(r)?{added:!1,rules:s}:{added:!0,rules:{...s,[o]:[...t,r]}}}function removePermissionRule(e,r,s){const o="allow"===e||"deny"===e||"ask"===e?e:"allow",t=s[o].filter((e=>e!==r));return{removed:t.length!==s[o].length,rules:{...s,[o]:t}}}function confirmPosture(){try{const e=readSharedPrefs().confirmMode;if("boolean"==typeof e)return{enabled:e,source:"shared"}}catch{}try{const e=JSON.parse(fs.readFileSync(permissionsPath(),"utf8"));if(e&&"object"==typeof e&&"string"==typeof e.defaultMode)return{enabled:"allow"!==e.defaultMode,source:"rules"}}catch{}return{enabled:!0,source:"default"}}function setConfirmPosture(e){const r=Boolean(e);try{prefs.set({confirmMode:r},{dir:aegisDir()})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[prefs] write failed:",e)}return saveRuleMode(r?"ask":"allow"),r}function setPermissionDefaultMode(e){const r="allow"===e?"allow":"deny"===e?"deny":"ask";try{prefs.set({confirmMode:"allow"!==r},{dir:aegisDir()})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[prefs] write failed:",e)}return saveRuleMode(r),r}module.exports={aegisDir:aegisDir,configPath:configPath,prefsPath:prefsPath,configExists:configExists,permissionsPath:permissionsPath,DEFAULT_CONFIG:DEFAULT_CONFIG,loadConfig:loadConfig,updateConfig:updateConfig,MEMORY_PERSIST_KEY:MEMORY_PERSIST_KEY,LEGACY_MEMORY_PERSIST_KEY:LEGACY_MEMORY_PERSIST_KEY,MEMORY_PERSIST_DEFAULT:MEMORY_PERSIST_DEFAULT,memoryPersistState:memoryPersistState,memoryPersistEnabled:memoryPersistEnabled,setMemoryPersist:setMemoryPersist,DEFAULT_PERMISSIONS:DEFAULT_PERMISSIONS,loadPermissions:loadPermissions,savePermissions:savePermissions,saveRuleMode:saveRuleMode,addPermissionRule:addPermissionRule,removePermissionRule:removePermissionRule,confirmPosture:confirmPosture,setConfirmPosture:setConfirmPosture,setPermissionDefaultMode:setPermissionDefaultMode};