aegiscode 7.0.30 → 7.0.32

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 (38) hide show
  1. package/LICENSING.md +186 -0
  2. package/package.json +4 -2
  3. package/src/app.js +1 -1
  4. package/src/chatflow.js +1 -1
  5. package/src/commands.js +3 -1
  6. package/src/config.js +1 -1
  7. package/src/engine.js +1 -1
  8. package/src/history.js +1 -1
  9. package/src/models.js +1 -1
  10. package/src/overlays.js +1 -1
  11. package/src/panels.js +1 -1
  12. package/vendor/client/brain-catalog.js +1 -1
  13. package/vendor/client/byok-catalog.js +1 -1
  14. package/vendor/client/credits.js +45 -0
  15. package/vendor/client/foreign-sessions.js +3 -0
  16. package/vendor/client/naming.js +1 -1
  17. package/vendor/client/prefs.js +1 -1
  18. package/vendor/client/session-search.js +3 -0
  19. package/vendor/desktop/lib/local/claude-pro.js +1 -1
  20. package/vendor/desktop/lib/local/engine.js +1 -1
  21. package/vendor/desktop/lib/local/integrity.js +42 -2
  22. package/vendor/desktop/lib/local/perm-rules.js +206 -0
  23. package/vendor/desktop/lib/local/perm-store.js +298 -0
  24. package/vendor/desktop/lib/local/perm-write.js +199 -0
  25. package/vendor/desktop/lib/local/pro-sessions.js +3 -0
  26. package/vendor/desktop/lib/local/sandbox-appcontainer.js +242 -0
  27. package/vendor/desktop/lib/local/sandbox-bwrap.js +316 -0
  28. package/vendor/desktop/lib/local/sandbox-seatbelt.js +380 -0
  29. package/vendor/desktop/lib/local/sandbox.js +493 -0
  30. package/vendor/desktop/lib/local/shell.js +155 -20
  31. package/vendor/desktop/lib/local/tools.js +29 -4
  32. package/vendor/desktop/lib/settings.js +1 -1
  33. package/vendor/desktop/main.js +774 -37
  34. package/vendor/desktop/renderer/usage.js +1 -1
  35. package/vendor/mcp/admission.js +3 -0
  36. package/vendor/mcp/server.js +1 -1
  37. package/vendor/one/src/child.js +1 -1
  38. package/vendor/one/src/permissions.js +1 -1
@@ -195,6 +195,30 @@ const { createAccountKey, startupKeyOverride } = require('./lib/account-key.js')
195
195
  const { createSettingsStore, isReservedNamespace } = require('./lib/settings.js');
196
196
  const sessionStore = require('./lib/sync/sessions.js');
197
197
  const memoryQueue = require('./lib/sync/memory-queue.js');
198
+ // Session ranking (the View > Search sessions… sheet) and the credits/licence
199
+ // payload (Help > Credits & licence). Both are SHARED with the terminal face —
200
+ // one copy of "which session matches", one copy of "what is the licence and who
201
+ // is credited" — resolved the same two ways every other shared client module in
202
+ // this file is: `client/` in a checkout, staged beside the app when packaged.
203
+ const sessionSearch = (() => {
204
+ try {
205
+ return require('../client/session-search.js');
206
+ } catch {
207
+ return require('./vendor/session-search.js');
208
+ }
209
+ })();
210
+ const creditsLib = (() => {
211
+ try {
212
+ return require('../client/credits.js');
213
+ } catch {
214
+ return require('./vendor/credits.js');
215
+ }
216
+ })();
217
+ // The LOCAL memory index (~/plan/agent-safety-plan.md §5). Rebuildable from the
218
+ // cloud, never authoritative, and strictly best-effort: every call here is
219
+ // wrapped because a dead index must not fail a save the cloud already accepted.
220
+ // One handle per file, so this is constructed here and shared, never per-call.
221
+ const memoryStore = require('./lib/sync/memory-store.js');
198
222
  const persistGate = require('./lib/sync/persist-gate.js');
199
223
  // Avatar level authority. The ledger, the replay and the award
200
224
  // hooks live here in main — a renderer-held counter is a suggestion, not a
@@ -215,6 +239,16 @@ try {
215
239
  } catch {
216
240
  foreignMemory = require('./vendor/foreign-memory.js');
217
241
  }
242
+ // Foreign-SESSION scanner (client/foreign-sessions.js). A sibling of the memory
243
+ // scanner above, not a replacement: that one yields memory fragments, this one
244
+ // yields whole conversations for the shared session store. Same resolution rule
245
+ // (`client/` in a checkout, the predist-staged copy in a packaged app).
246
+ let foreignSessions;
247
+ try {
248
+ foreignSessions = require('../client/foreign-sessions.js');
249
+ } catch {
250
+ foreignSessions = require('./vendor/foreign-sessions.js');
251
+ }
218
252
  // Builtin tool executor for the agent loop (client half of the upstream engine's
219
253
  // tool calling). MAIN-process only: it is reachable from the renderer solely
220
254
  // through the whitelisted `tools:` IPC surface registered below — see the
@@ -294,6 +328,14 @@ const CHAT_DELTA_CHANNEL = `${IPC_PREFIX}chatDelta`;
294
328
  * "new chat" and "open search" behaviour, so the menu just asks for it. */
295
329
  const MENU_NEW_CHAT_CHANNEL = `${IPC_PREFIX}menuNewChat`;
296
330
  const MENU_SEARCH_CHANNEL = `${IPC_PREFIX}menuSearch`;
331
+ /** View > Search memory… — the inspector that `Search…`+Cmd/Ctrl+K used to
332
+ * open. Split off when the session search was built: one accelerator was
333
+ * doing two things, and the label named the wrong one. */
334
+ const MENU_SEARCH_MEMORY_CHANNEL = `${IPC_PREFIX}menuSearchMemory`;
335
+ /** Help > Credits & licence. Opens the sheet built from client/credits.js —
336
+ * the licence, the program notice and the vendored attributions, parsed out
337
+ * of LICENSING.md and the two NOTICE files rather than retyped in a renderer. */
338
+ const MENU_CREDITS_CHANNEL = `${IPC_PREFIX}menuCredits`;
297
339
  /** File > Save as… / Export session — same "menu has no state of its own,
298
340
  * renderer does the work" pattern as the two channels above: the renderer
299
341
  * knows the open session id, main.js just pings it. */
@@ -693,13 +735,66 @@ function watchTopupCredit(aegis, opts) {
693
735
  *
694
736
  * `avatar` is optional: without it the function behaves exactly as before.
695
737
  */
696
- async function saveMemoryWithQueue(aegis, dir, entry, avatar) {
738
+ /**
739
+ * The local memory index, opened lazily and exactly once per process
740
+ * (`~/plan/agent-safety-plan.md` §5).
741
+ *
742
+ * Three rules this accessor enforces, and they are the whole reason it is a
743
+ * function rather than a `const store = openStore(...)` at module scope:
744
+ *
745
+ * 1. **Never at import time.** The user-data dir is only known inside
746
+ * `createEngine`, and `node:sqlite` is experimental — a store that opens
747
+ * during require would turn "this Node is too old" into a failure to start
748
+ * the app. `open()` answering `{ ok: false }` is a degraded index, not a
749
+ * broken host.
750
+ * 2. **One handle per file.** `memory-store.js` throws if a second handle
751
+ * opens the same file in one process; caching here is what keeps that
752
+ * throw unreachable from the normal path.
753
+ * 3. **Failure is sticky and silent.** sqlite missing or the file unopenable
754
+ * is not transient, so the first failure latches off and later calls cost
755
+ * nothing. Returns `null` — every call site treats that as "no index".
756
+ */
757
+ let memoryIndexHandle = null;
758
+ let memoryIndexOff = false;
759
+ function memoryIndex(dir) {
760
+ if (memoryIndexHandle) return memoryIndexHandle;
761
+ if (memoryIndexOff || !dir) return null;
762
+ try {
763
+ const store = new memoryStore.MemoryStore({ dir });
764
+ const opened = store.open();
765
+ if (!opened.ok) {
766
+ memoryIndexOff = true;
767
+ return null;
768
+ }
769
+ memoryIndexHandle = store;
770
+ return memoryIndexHandle;
771
+ } catch {
772
+ memoryIndexOff = true;
773
+ return null;
774
+ }
775
+ }
776
+
777
+ /** Release the index in `will-quit`. WAL means an unclean close is survivable,
778
+ * but an explicit close lets sqlite checkpoint rather than recover. */
779
+ function closeMemoryIndex() {
780
+ if (!memoryIndexHandle) return;
781
+ try { memoryIndexHandle.close(); } catch { /* already closed */ }
782
+ memoryIndexHandle = null;
783
+ }
784
+
785
+ async function saveMemoryWithQueue(aegis, dir, entry, avatar, index) {
697
786
  const normalized = avatarStore.normalizeMemoryEntry(entry);
698
787
  try {
699
788
  const result = await aegis.memorySave(normalized);
700
789
  if (avatar && normalized && typeof normalized === 'object') {
701
790
  avatar.awardSave(normalized, { session: normalized.session });
702
791
  }
792
+ // Index only a save the cloud accepted. Order matters: an entry the cloud
793
+ // rejected must not appear in local recall, or recall would answer with
794
+ // something the account does not actually hold.
795
+ if (index && normalized && typeof normalized === 'object') {
796
+ try { index.upsert(normalized); } catch { /* the index is not the record */ }
797
+ }
703
798
  return result;
704
799
  } catch (err) {
705
800
  const upgrade = upgradeInfo(err);
@@ -740,6 +835,104 @@ async function normalizeMemoryRead(promise) {
740
835
  }
741
836
  }
742
837
 
838
+ /**
839
+ * The READ side of the local memory index — the half that was built and never
840
+ * called.
841
+ *
842
+ * ── why a cloud-first fallback, and not a merge ────────────────────────────
843
+ *
844
+ * The cloud is the system of record (see `memory-store.js`). Merging local rows
845
+ * into a successful cloud answer would let a stale entry the account has since
846
+ * deleted keep appearing in recall forever, and there is no tombstone in the
847
+ * index to prevent it. So the local index answers ONLY when the cloud could not:
848
+ * it is a substitute for the same query, never a supplement to it.
849
+ *
850
+ * Which failures fall back is deliberate. A 402 never reaches this function at
851
+ * all — `normalizeMemoryRead` turns it into a resolved `{ entries: [],
852
+ * upgrade }`, and an over-quota account genuinely has an empty page to show
853
+ * while the upgrade notice is what matters; falling back there would answer the
854
+ * same query from a local file and hide the cap. What is left divides in two:
855
+ *
856
+ * - **No answer** — a transport failure (offline, DNS, timeout) carries no
857
+ * `status`, and a 5xx means the service is up but cannot serve. Both are
858
+ * exactly what the index exists for, so both fall back.
859
+ * - **A refusal** — any other 4xx is the server speaking: 401/403 mean this
860
+ * credential may not read, and the UI must show that rather than quietly
861
+ * substituting a file. So 4xx does NOT fall back.
862
+ *
863
+ * `local: true` rides along on the payload so the renderer can say where the
864
+ * rows came from. An index that answers silently would make an offline session
865
+ * look like a signed-in one, which is the one thing recall must not do.
866
+ */
867
+ async function normalizeMemoryReadWithFallback(promise, index, query, limit) {
868
+ try {
869
+ return await normalizeMemoryRead(promise);
870
+ } catch (err) {
871
+ const status = Number(err && err.status);
872
+ // A typed refusal is the server answering. Only "no answer" substitutes.
873
+ const refused = status >= 400 && status < 500;
874
+ const local = refused || !index ? null : searchMemoryLocally(index, query, limit);
875
+ if (!local || !local.entries.length) throw err;
876
+ return local;
877
+ }
878
+ }
879
+
880
+ /**
881
+ * One local query, in the shape the renderer already parses.
882
+ *
883
+ * `memory-store.search()` answers `{ results: [{ id, body, scope, tags,
884
+ * updated }] }`; the cloud answers `{ entries: [{ id, content, source, … }] }`.
885
+ * The mapping is done here rather than in the renderer because the renderer
886
+ * normaliser (`normalizeMemoryEntry`) is deliberately lossy — it fills a
887
+ * missing source with "(unknown source)", so a local row promoted in the
888
+ * renderer would be labelled as unknown provenance when we know exactly what it
889
+ * is.
890
+ *
891
+ * `source` is `local-index` for that same reason: a row that came from the
892
+ * local file must not claim to be a freshly fetched cloud entry.
893
+ */
894
+ function searchMemoryLocally(index, query, limit) {
895
+ let res;
896
+ try {
897
+ res = index.search(query, { limit });
898
+ } catch {
899
+ return null;
900
+ }
901
+ if (!res || !res.ok || !Array.isArray(res.results)) return null;
902
+ return {
903
+ entries: res.results.map((r) => ({
904
+ id: r.id,
905
+ content: r.body,
906
+ source: 'local-index',
907
+ scope: r.scope,
908
+ tags: Array.isArray(r.tags) ? r.tags : [],
909
+ // The store keeps epoch ms; the renderer's `createdAt` is also epoch ms.
910
+ createdAt: r.updated,
911
+ })),
912
+ local: true,
913
+ // FTS tells the user whether this was a word search or a `LIKE` scan, and
914
+ // the difference matters when a result looks wrong.
915
+ fts: res.fts === true,
916
+ };
917
+ }
918
+
919
+ /**
920
+ * Index a pull. `memoryPull` returns the cloud's entries; this store mirrors
921
+ * them so an offline session can still recall. The pull is passed in already
922
+ * started so the cloud call keeps its exact rejection semantics — if it throws,
923
+ * the caller still sees the throw, and nothing is indexed.
924
+ *
925
+ * A pull is a reconciliation, not an append: entries reconcile by id, so
926
+ * replaying from 0 rebuilds the index without duplicating rows.
927
+ */
928
+ async function indexPulledMemory(pull, index) {
929
+ const data = await pull;
930
+ if (index && data && Array.isArray(data.entries) && data.entries.length) {
931
+ try { index.upsertMany(data.entries); } catch { /* the index is not the record */ }
932
+ }
933
+ return data;
934
+ }
935
+
743
936
  /** Over-quota notice derived from a successful read payload, or null.
744
937
  * `tokensUsed`/`tokenLimit` come from aegis1 `_token_quota_fields`. */
745
938
  function quotaFromPayload(data) {
@@ -759,6 +952,102 @@ function quotaFromPayload(data) {
759
952
  };
760
953
  }
761
954
 
955
+ /**
956
+ * `aegis:sessionsImport` — find the conversations OTHER AI coding tools left on
957
+ * this machine and (when confirmed) copy them into the shared session store.
958
+ *
959
+ * The toolbar's Import sheet, and the counterpart of `memoryImport` below. The
960
+ * difference is what lands where:
961
+ *
962
+ * memoryImport → one memory ENTRY per surviving foreign message, uploaded
963
+ * to cloud memory (`import:<source>` session).
964
+ * sessionsImport→ one SESSION per foreign transcript, written to
965
+ * `<aegisHome>/sessions.json` — the same file the window's
966
+ * sidebar and the terminal's `/resume` list out of.
967
+ *
968
+ * So an imported Claude Code conversation is not a second-class import: it
969
+ * opens, titles, exports and searches exactly like a conversation typed here,
970
+ * and it is visible to the CLI too.
971
+ *
972
+ * Read-only against the foreign stores (client/foreign-sessions.js never writes
973
+ * into them). Two-phase: `{ confirm: false }` scans and returns counts only —
974
+ * the sheet shows what would land before anything is copied. Imported records
975
+ * are written `pending: false` on purpose: the user asked to see these
976
+ * conversations in AEGIS, not to upload their history to the account, and a
977
+ * `pending` flag would push the whole import to the cloud on the next sync.
978
+ * The caller can opt in with `{ sync: true }`.
979
+ *
980
+ * Ids are stable (`imp-<hash of source + foreign id>`), so a second import of
981
+ * the same machine upserts rather than duplicating the sidebar.
982
+ */
983
+ async function importForeignSessions(dir, payload) {
984
+ const opts = payload || {};
985
+ const report = foreignSessions.scan({
986
+ sources: opts.sources,
987
+ limit: opts.limit || 500,
988
+ });
989
+ const summary = foreignSessions.describe(report);
990
+ const sources = report.sources.map((s) => ({
991
+ id: s.id,
992
+ label: s.label,
993
+ verified: s.verified,
994
+ present: s.present,
995
+ unreadable: s.unreadable,
996
+ count: s.count,
997
+ messages: s.messages,
998
+ files: s.files,
999
+ skipped: s.skipped,
1000
+ }));
1001
+ const base = { summary, totals: report.totals, sources };
1002
+
1003
+ if (!opts.confirm || !report.sessions.length) {
1004
+ return {
1005
+ ...base,
1006
+ ok: true,
1007
+ dryRun: !opts.confirm,
1008
+ imported: 0,
1009
+ skippedExisting: 0,
1010
+ sessions: report.sessions.map((s) => ({
1011
+ id: s.id,
1012
+ title: s.title,
1013
+ source: s.source,
1014
+ sourceLabel: s.sourceLabel,
1015
+ messages: s.messages.length,
1016
+ updatedAt: s.updatedAt,
1017
+ })),
1018
+ };
1019
+ }
1020
+
1021
+ // An id already in the store AND already imported from the same place is the
1022
+ // same conversation: count it, do not rewrite it. That keeps a re-scan from
1023
+ // touching the user's own renames, and from re-sorting the sidebar.
1024
+ const existing = new Set((sessions.listSessions(dir) || []).map((s) => s && s.id).filter(Boolean));
1025
+ let imported = 0;
1026
+ let skippedExisting = 0;
1027
+ const errors = [];
1028
+ for (const session of report.sessions) {
1029
+ try {
1030
+ if (existing.has(session.id)) {
1031
+ skippedExisting += 1;
1032
+ continue;
1033
+ }
1034
+ sessions.upsertSession(dir, foreignSessions.toRecord(session, { pending: opts.sync === true }));
1035
+ imported += 1;
1036
+ } catch (err) {
1037
+ errors.push(errorText(err));
1038
+ }
1039
+ }
1040
+
1041
+ return {
1042
+ ...base,
1043
+ ok: errors.length === 0,
1044
+ dryRun: false,
1045
+ imported,
1046
+ skippedExisting,
1047
+ reason: errors[0] || null,
1048
+ };
1049
+ }
1050
+
762
1051
  /**
763
1052
  * `aegis:memoryImport` — scan this machine for other AI tools' memory and,
764
1053
  * when confirmed, push it into AEGIS cloud memory.
@@ -782,7 +1071,7 @@ function quotaFromPayload(data) {
782
1071
  * same number, so a ten-tool import cannot jump ten levels. Entries that fell
783
1072
  * back to the local queue are queued events, not imports.
784
1073
  */
785
- async function importForeignMemory(aegis, dir, payload, avatar) {
1074
+ async function importForeignMemory(aegis, dir, payload, avatar, index) {
786
1075
  const opts = payload || {};
787
1076
  const report = foreignMemory.scan({
788
1077
  sources: opts.sources,
@@ -819,6 +1108,12 @@ async function importForeignMemory(aegis, dir, payload, avatar) {
819
1108
  source: first.session || first.source || 'foreign-import',
820
1109
  });
821
1110
  }
1111
+ // Same ordering rule as a single save: index after the cloud batch
1112
+ // lands, never before. A partially-failed batch throws to the catch
1113
+ // below, so nothing from it is indexed here.
1114
+ if (index && batch.length) {
1115
+ try { index.upsertMany(batch); } catch { /* the index is not the record */ }
1116
+ }
822
1117
  } catch (err) {
823
1118
  // The cap is not an offline failure: don't queue the batch. The entries
824
1119
  // are still in the foreign stores, so a later scan re-finds them — but a
@@ -1088,24 +1383,40 @@ function createIpcDispatch(aegis, dir, persistApiKey, openExternal, providerConf
1088
1383
  ),
1089
1384
 
1090
1385
  memorySearch: (payload) =>
1091
- normalizeMemoryRead(
1092
- aegis.memorySearch(payload && payload.query, payload && payload.limit)
1386
+ normalizeMemoryReadWithFallback(
1387
+ aegis.memorySearch(payload && payload.query, payload && payload.limit),
1388
+ memoryIndex(dir),
1389
+ payload && payload.query,
1390
+ payload && payload.limit
1093
1391
  ),
1094
1392
  memorySave: (payload) =>
1095
- saveMemoryWithQueue(aegis, dir, payload && payload.entry, avatar),
1393
+ saveMemoryWithQueue(aegis, dir, payload && payload.entry, avatar, memoryIndex(dir)),
1096
1394
  memoryList: (payload) =>
1097
- normalizeMemoryRead(aegis.memoryList(payload && payload.limit)),
1395
+ normalizeMemoryReadWithFallback(
1396
+ aegis.memoryList(payload && payload.limit),
1397
+ memoryIndex(dir),
1398
+ // `memoryList` is search with an empty query on the client side
1399
+ // (vendor/aegis.js), so the local equivalent is the same empty-query
1400
+ // branch: most recent first.
1401
+ '',
1402
+ payload && payload.limit
1403
+ ),
1098
1404
 
1099
1405
  verifyToken: (payload) =>
1100
1406
  aegis.verifyToken(payload && payload.token),
1101
1407
  memoryActivate: (payload) =>
1102
1408
  aegis.memoryActivate(payload && payload.token),
1103
1409
  memoryPull: (payload) =>
1104
- aegis.memoryPull(payload && payload.since),
1410
+ indexPulledMemory(aegis.memoryPull(payload && payload.since), memoryIndex(dir)),
1105
1411
  memorySaveBatch: (payload) =>
1106
1412
  aegis.memorySaveBatch(payload && payload.entries),
1107
1413
  memoryImport: (payload) =>
1108
- importForeignMemory(aegis, dir, payload, avatar),
1414
+ importForeignMemory(aegis, dir, payload, avatar, memoryIndex(dir)),
1415
+ // The toolbar's Import session sheet (client/foreign-sessions.js → the
1416
+ // shared session store). Separate channel from `memoryImport` because the
1417
+ // two answer different questions and write to different stores.
1418
+ sessionsImportScan: () => importForeignSessions(dir, { confirm: false }),
1419
+ sessionsImport: (payload) => importForeignSessions(dir, payload),
1109
1420
  importConversation: (payload) =>
1110
1421
  aegis.importConversation(payload || {}),
1111
1422
 
@@ -1214,6 +1525,39 @@ function createConfirmModeDispatch(settings) {
1214
1525
  };
1215
1526
  }
1216
1527
 
1528
+ /**
1529
+ * Plan mode: `aegis:getPermissionMode` / `aegis:setPermissionMode`. Same shape
1530
+ * as createConfirmModeDispatch, registered through the same generic
1531
+ * registerConfirmModeIpc — and the LAST mile of a feature that was otherwise
1532
+ * already built: `desktop/lib/settings.js` has carried `getPermissionMode`/
1533
+ * `setPermissionMode` (the window's half of the shared `/permissions mode`
1534
+ * key — see its own docstring) since the D8 posture work, but no IPC handler
1535
+ * ever exposed it and no renderer control ever called it, so the desktop app
1536
+ * had no way to enter plan mode at all. The engine-side enforcement
1537
+ * (lib/local/engine.js gatedExecuteTool, `planModeEnabled()`) already reads
1538
+ * `settings.getPermissionMode()` directly — this dispatch is only what lets
1539
+ * the Settings card read and change it.
1540
+ *
1541
+ * `set` accepts `'plan'` or `null`/`'off'` only: the other five stored modes
1542
+ * (acceptEdits, auto, bypassPermissions, manual, dontAsk) are the Claude-Pro
1543
+ * child's own vocabulary and have no meaning for this face's engine loop, so
1544
+ * exposing them here would invite a desktop user into a mode this host cannot
1545
+ * honour. A value outside that pair is refused rather than guessed.
1546
+ */
1547
+ function createPermissionModeDispatch(settings) {
1548
+ if (!settings) throw new Error('createPermissionModeDispatch requires a settings store');
1549
+ return {
1550
+ getPermissionMode: () => ({ mode: settings.getPermissionMode() }),
1551
+ setPermissionMode: (payload) => {
1552
+ const want = payload && payload.mode;
1553
+ if (want !== 'plan' && want !== null && want !== undefined) {
1554
+ return { mode: settings.getPermissionMode() };
1555
+ }
1556
+ return { mode: settings.setPermissionMode(want === 'plan' ? 'plan' : null) };
1557
+ },
1558
+ };
1559
+ }
1560
+
1217
1561
  /**
1218
1562
  * Auto mode's other switch: a posture of "don't ask" IS auto mode on this face,
1219
1563
  * so an explicit setConfirmMode must move the model dispatch's session state
@@ -1240,6 +1584,176 @@ function withAutoRoundsSwitch(confirmDispatch, modelDispatch) {
1240
1584
  };
1241
1585
  }
1242
1586
 
1587
+ /**
1588
+ * Permission-rules editor: `aegis:permRulesList` / `permRulesAdd` /
1589
+ * `permRulesRemove` (registered through the same generic
1590
+ * registerConfirmModeIpc, which wires `{name: handler}` pairs as
1591
+ * `aegis:<name>`).
1592
+ *
1593
+ * Same pure-injection shape as createConfirmModeDispatch, so it is testable in
1594
+ * plain Node: `store` is desktop/lib/local/perm-store.js in bootstrap, a stub
1595
+ * in tests. Every handler answers `{ ok, ... }` and NEVER throws across the
1596
+ * bridge — a refused rule is a sentence for the user, not an IPC rejection
1597
+ * that Electron would print as an unhandled error.
1598
+ *
1599
+ * `permRulesAdd` takes `{ list, rule }` and answers the full re-read rule set,
1600
+ * not just the delta: the renderer repaints from what the file actually holds,
1601
+ * so a rule the store refused can never be shown as saved. `permRulesRemove`
1602
+ * is deliberately unvalidated (see perm-store.js) — removing a malformed rule
1603
+ * is how a user repairs the file.
1604
+ */
1605
+ function createPermRulesDispatch(store) {
1606
+ if (!store) throw new Error('createPermRulesDispatch requires a rule store');
1607
+ const safe = (fn, fallback) => {
1608
+ try {
1609
+ return fn();
1610
+ } catch (e) {
1611
+ return { ...fallback, ok: false, reason: (e && e.message) || String(e) };
1612
+ }
1613
+ };
1614
+ return {
1615
+ permRulesList: () => safe(() => store.listRules(), {}),
1616
+ permRulesAdd: (payload) => {
1617
+ const list = payload && payload.list;
1618
+ const rule = payload && payload.rule;
1619
+ // A malformed payload changes nothing: it does not default to `allow`,
1620
+ // because "add to the permissive list" is the one wrong guess available.
1621
+ if (typeof list !== 'string' || typeof rule !== 'string') {
1622
+ return safe(() => store.listRules(), { reason: 'a rule needs a list and a pattern' });
1623
+ }
1624
+ return safe(() => store.addRule(list, rule), {});
1625
+ },
1626
+ permRulesRemove: (payload) => {
1627
+ const list = payload && payload.list;
1628
+ const rule = payload && payload.rule;
1629
+ if (typeof list !== 'string' || typeof rule !== 'string') {
1630
+ return safe(() => store.listRules(), { reason: 'a rule needs a list and a pattern' });
1631
+ }
1632
+ return safe(() => store.removeRule(list, rule), {});
1633
+ },
1634
+ };
1635
+ }
1636
+
1637
+ /**
1638
+ * Sandbox posture: `aegis:getSandboxPolicy` / `setSandboxPolicy`.
1639
+ *
1640
+ * Same pure-injection shape as createConfirmModeDispatch — unit-testable with a
1641
+ * stub store — and registered through the same generic registerConfirmModeIpc.
1642
+ *
1643
+ * The renderer may only choose a MODE (`off` | `read-only` | `workspace-write`)
1644
+ * and the network axis. It may NOT post path grants: the writable tree is the
1645
+ * one the engine is already rooted at, and letting the window append arbitrary
1646
+ * `fileSystem.entries` would turn a posture switch into a way to widen the
1647
+ * sandbox from a renderer compromise. Grants stay in the file, for a human.
1648
+ *
1649
+ * Every handler answers the policy as RE-READ from the store, never the value
1650
+ * that was posted, so a rejected choice cannot be painted as accepted.
1651
+ */
1652
+ function createSandboxPolicyDispatch(settings, sandbox, opts) {
1653
+ if (!settings) throw new Error('createSandboxPolicyDispatch requires a settings store');
1654
+ const mod = sandbox || {};
1655
+ const modes = Array.isArray(mod.MODES) ? mod.MODES : ['off', 'read-only', 'workspace-write', 'managed'];
1656
+ // `managed` is accepted by normalize() but has no enforcement path of its own
1657
+ // here, so it is not offered until it does — a mode selector must not list a
1658
+ // posture the product cannot hold.
1659
+ const offered = modes.filter((m) => m !== 'managed');
1660
+ // The app dir is passed IN rather than read from `app` here, because this
1661
+ // factory is required by test/local-sandbox.test.mjs outside Electron, where
1662
+ // `app` does not exist. It is the only input the probe needs.
1663
+ const appDir = opts && opts.appDir;
1664
+
1665
+ /**
1666
+ * What actually enforces the policy on THIS host, in the mechanism's own words.
1667
+ *
1668
+ * The pane used to paint a hardcoded sentence off the mode name alone, which
1669
+ * asserted `Network: blocked` on hosts with no bwrap at all — the precise
1670
+ * false assurance sandbox.js's header forbids. `describe()` is the module's
1671
+ * own sentence and already distinguishes "OFF — bwrap not found (commands run
1672
+ * with full user access)" from "workspace-write via bwrap — network
1673
+ * restricted", so the caption is derived from the probe rather than from the
1674
+ * mode. A probe that throws degrades the CAPTION, never the pane: the posture
1675
+ * switch must stay usable, and `enforced: null` says "unknown" rather than
1676
+ * either lie.
1677
+ */
1678
+ const mechanismOf = (policy) => {
1679
+ const detect = mod.detectCached || mod.detect;
1680
+ if (typeof detect !== 'function' || typeof mod.describe !== 'function') return null;
1681
+ try {
1682
+ const state = detect({ appDir });
1683
+ const sentence = mod.describe(state, policy);
1684
+ return {
1685
+ mechanism: (state && (state.mechanism || (state.path ? 'bwrap' : null))) || null,
1686
+ enforced: Boolean(state && state.available) && policy.mode !== 'off',
1687
+ sentence: typeof sentence === 'string' ? sentence : null,
1688
+ };
1689
+ } catch {
1690
+ return { mechanism: null, enforced: null, sentence: null };
1691
+ }
1692
+ };
1693
+
1694
+ const read = () => {
1695
+ const stored = settings.getSandboxPolicy();
1696
+ const mode = stored && offered.includes(stored.mode) ? stored.mode : 'workspace-write';
1697
+ const network = stored && stored.network === 'open' ? 'open' : 'restricted';
1698
+ // `stored: null` means nobody chose — the engine then falls back to
1699
+ // workspace-write. The renderer shows that as the effective default rather
1700
+ // than as "unset", so the caption never reads as weaker than it is.
1701
+ // The sentence describes the EFFECTIVE policy, so it is normalised the same
1702
+ // way the engine normalises it — otherwise the pane would quote a probe for
1703
+ // a policy the engine is not applying.
1704
+ let sentence = null;
1705
+ let enforced = null;
1706
+ let mechanism = null;
1707
+ try {
1708
+ const policy = typeof mod.normalize === 'function'
1709
+ ? mod.normalize(stored, undefined)
1710
+ : { mode, network };
1711
+ const found = mechanismOf(policy);
1712
+ if (found) ({ sentence, enforced, mechanism } = found);
1713
+ } catch {
1714
+ /* the caption is best-effort; the posture above is not */
1715
+ }
1716
+ return { ok: true, mode, network, modes: offered, stored: stored ? true : false, sentence, enforced, mechanism };
1717
+ };
1718
+ return {
1719
+ getSandboxPolicy: () => read(),
1720
+ setSandboxPolicy: (payload) => {
1721
+ const mode = payload && payload.mode;
1722
+ const network = payload && payload.network;
1723
+ if (typeof mode !== 'string' || !offered.includes(mode)) return read();
1724
+ if (network !== undefined && network !== 'open' && network !== 'restricted') return read();
1725
+ const current = settings.getSandboxPolicy();
1726
+ // Preserve any entry grants already in the file. The UI edits posture, not
1727
+ // the grant list, so a save must not silently delete a hand-written bind.
1728
+ const fileSystem =
1729
+ current && current.fileSystem && Array.isArray(current.fileSystem.entries)
1730
+ ? { entries: current.fileSystem.entries }
1731
+ : { entries: [] };
1732
+ const nextNetwork = network === undefined
1733
+ ? (current && current.network === 'open' ? 'open' : 'restricted')
1734
+ : network;
1735
+ try {
1736
+ settings.setSandboxPolicy({ mode, fileSystem, network: nextNetwork });
1737
+ } catch {
1738
+ // Same contract as the rule editor: a failed write answers the truth
1739
+ // that is on disk, not the intent that was refused.
1740
+ return read();
1741
+ }
1742
+ // A posture change is the one event that can change what the probe should
1743
+ // report (mode `off` short-circuits it), and the re-read below must not
1744
+ // quote the previous mode's sentence.
1745
+ if (typeof mod.invalidateProbe === 'function') {
1746
+ try {
1747
+ mod.invalidateProbe(appDir);
1748
+ } catch {
1749
+ /* cache miss is not a correctness problem */
1750
+ }
1751
+ }
1752
+ return read();
1753
+ },
1754
+ };
1755
+ }
1756
+
1243
1757
  /**
1244
1758
  * Register getConfirmMode/setConfirmMode as `aegis:<name>` on ipcMain —
1245
1759
  * the same ${IPC_PREFIX}<method> convention registerIpc uses for the rest of
@@ -1524,7 +2038,37 @@ function createEngine(aegis, { app, safeStorage, dir: dirOverride, sessionsDir:
1524
2038
  // Relocate a pre-fix `settings['aegis']` key into the reserved namespace so
1525
2039
  // it stops showing up as a provider. Ciphertext-level, so safe pre-'ready'.
1526
2040
  settings.migrateLegacyAegisKey();
1527
- const engine = createLocalEngine({ aegis, settings });
2041
+ const engine = createLocalEngine({
2042
+ aegis,
2043
+ settings,
2044
+ // The outcome bound (~/plan/agent-safety-plan.md §1b). The engine decides WHEN
2045
+ // to ask and what the policy is; this host decides only that it is wanted.
2046
+ // The stored policy (Settings › sandbox) is preferred, and `null` there means
2047
+ // "nobody chose", which the engine reads as its default workspace-write —
2048
+ // never as `off`. `strict` is the user's own choice and lives beside the
2049
+ // policy; absent means degrade-loudly, because refusing every command on an
2050
+ // AppArmor-restricted host would brick the product rather than protect it.
2051
+ sandbox: { policy: settings.getSandboxPolicy(), strict: false, appDir: __dirname },
2052
+ // Stored /permissions rules (~/plan/agent-safety-plan.md §2). The rules live
2053
+ // in the SHARED data dir (~/.aegiscode/permissions.json), which is the same
2054
+ // file the terminal face writes via `/permissions allow|deny|ask`, so a rule
2055
+ // written in one face governs the other. `rulesVerdict` answers 'allow' or
2056
+ // 'deny' only for a rule the user explicitly wrote and `null` otherwise, so
2057
+ // an un-touched rules file leaves the cards exactly as they were.
2058
+ permissionRules: {
2059
+ rulesVerdict: require('./lib/local/perm-rules.js').rulesVerdict,
2060
+ // §3 Defect A: the session tier keys its grants on the SUBJECT
2061
+ // (`npm test`), not the tool name, so approving one command does not
2062
+ // authorise every later command. Passed through the same option object
2063
+ // as the reader so the two cannot disagree about what a subject is —
2064
+ // and so a host that passes nothing (the CLI) keeps the old key.
2065
+ subjectFor: require('./lib/local/perm-rules.js').subjectFor,
2066
+ // §3: "Always allow this command". Passed alongside the reader because the
2067
+ // two halves must agree — a card that offers the button and a gate that
2068
+ // cannot store the rule would be the same lie in a different place.
2069
+ alwaysAllow: require('./lib/local/perm-write.js').alwaysAllow,
2070
+ },
2071
+ });
1528
2072
  // Sessions/memory live in the SHARED data dir ($AEGISCODE_HOME or
1529
2073
  // ~/.aegiscode) — the same file the terminal host and the MCP plugin read —
1530
2074
  // so a thread started in either shows up in the other without cloud sync and
@@ -1960,6 +2504,18 @@ function createModelDispatch(engine, { env = process.env, settings } = {}) {
1960
2504
  : { ok: false },
1961
2505
  clearApprovals: (payload) =>
1962
2506
  engine.clearSessionApprovals(payload && payload.sessionId),
2507
+ // Per-action undo (desktop/lib/local/engine.js guardedExecute/undoMutation):
2508
+ // the journal entry for every writeFile/editFile this conversation made,
2509
+ // and the reversal for one of them — `id` from `listUndoable` (a tool-call
2510
+ // row's own Undo button), or omitted for the most recent. Guarded the same
2511
+ // way respondRoundsAsk is: an older vendored engine simply does not offer
2512
+ // undo, and the renderer gets `{ ok: false }` / `[]` instead of a crash.
2513
+ listUndoable: (payload) =>
2514
+ typeof engine.listUndoable === 'function' ? engine.listUndoable(payload && payload.sessionId) : [],
2515
+ undoMutation: (payload) =>
2516
+ typeof engine.undoMutation === 'function'
2517
+ ? engine.undoMutation(payload && payload.sessionId, payload && payload.id)
2518
+ : { ok: false, error: 'undo is not available on this engine' },
1963
2519
  };
1964
2520
 
1965
2521
  // Auto mode's session state is read and moved DIRECTLY, never over IPC.
@@ -2010,6 +2566,12 @@ function createSyncDispatch(sessions, dir, aegis, settingsDir, modelDispatch) {
2010
2566
  try {
2011
2567
  await aegis.memorySave(queued[i]);
2012
2568
  flushed += 1;
2569
+ // The queued entry is only now actually held by the account, so this
2570
+ // is the first moment it belongs in local recall.
2571
+ const index = memoryIndex(dir);
2572
+ if (index) {
2573
+ try { index.upsert(queued[i]); } catch { /* index is not the record */ }
2574
+ }
2013
2575
  } catch (err) {
2014
2576
  const capped = upgradeInfo(err);
2015
2577
  if (capped) {
@@ -2149,6 +2711,41 @@ function createSyncDispatch(sessions, dir, aegis, settingsDir, modelDispatch) {
2149
2711
  auto: () => autoPush.auto(),
2150
2712
  memoryPersistState: () => autoPush.gate(),
2151
2713
  listSessions: () => ({ sessions: sessions.listSessions(dir) }),
2714
+ // The SESSION search the menu's "Search sessions…" (Cmd/Ctrl+K) runs. It
2715
+ // lives here, not in the renderer, for the same reason the list does: the
2716
+ // store is a main-process file, and `listSessions()` truncates — it returns
2717
+ // title/messages/updatedAt, so a renderer-side filter would be a second,
2718
+ // weaker copy of the same read. `searchSessions` takes the query and returns
2719
+ // the ranked matches plus WHICH field matched, so the row can say why it is
2720
+ // in the list. An empty query returns the newest N unchanged, so the sheet
2721
+ // opens on something instead of a blank pane.
2722
+ //
2723
+ // The ranking is `client/session-search.js` — the same module the CLI's
2724
+ // /resume picker filters with, so the two faces cannot order the same
2725
+ // conversation differently.
2726
+ searchSessions: (payload) => {
2727
+ const query = payload && typeof payload.query === 'string' ? payload.query : '';
2728
+ const limit = Number.isInteger(payload && payload.limit) ? payload.limit : 50;
2729
+ const all = sessions.listSessions(dir) || [];
2730
+ const ranked = sessionSearch.rankSessions(query, all).slice(0, Math.max(1, limit));
2731
+ return {
2732
+ query,
2733
+ total: all.length,
2734
+ sessions: ranked.map((s) => ({
2735
+ id: s && s.id,
2736
+ title: (s && s.title) || (s && s.id) || 'untitled',
2737
+ updatedAt: (s && s.updatedAt) || null,
2738
+ messages:
2739
+ s && Array.isArray(s.messages)
2740
+ ? s.messages.map((m) => ({
2741
+ role: m && m.role,
2742
+ content: typeof (m && m.content) === 'string' ? m.content.slice(0, 400) : '',
2743
+ }))
2744
+ : [],
2745
+ reason: sessionSearch.matchReason(query, s),
2746
+ })),
2747
+ };
2748
+ },
2152
2749
  open: (payload) => sessions.getSession(dir, payload && payload.sessionId),
2153
2750
  save: (payload) => sessions.upsertSession(dir, payload || {}),
2154
2751
  append: (payload) =>
@@ -3624,14 +4221,26 @@ function sendDeepLinkToWindow(win, parsed) {
3624
4221
 
3625
4222
  /** Application menu: the platform defaults (Edit roles, mac's app/quit
3626
4223
  * items) plus the native-shell accelerators this plan adds — New Chat
3627
- * (Cmd/Ctrl+N), Search (Cmd/Ctrl+K, opens the memory/session search
3628
- * overlay), Reload (Cmd/Ctrl+R) and Toggle DevTools (Cmd/Ctrl+Shift+I) are
3629
- * plain Electron roles that already carry the right accelerator on every
3630
- * platform — plus a manual "Check for Updates…" entry, since the automatic
3631
- * checks in createUpdateManager.start() only run on ready and every few
3632
- * hours, and an About item (mac gets one for free in the app submenu; other
3633
- * platforms get a Help menu — role 'about' shows app.setAboutPanelOptions()
3634
- * cross-platform since Electron 15). */
4224
+ * (Cmd/Ctrl+N), Search sessions… (Cmd/Ctrl+K), Search memory…
4225
+ * (Cmd/Ctrl+Shift+K), Reload (Cmd/Ctrl+R) and Toggle DevTools
4226
+ * (Cmd/Ctrl+Shift+I) are plain Electron roles that already carry the right
4227
+ * accelerator on every platform — plus a manual "Check for Updates…" entry,
4228
+ * since the automatic checks in createUpdateManager.start() only run on ready
4229
+ * and every few hours, and an About item (mac gets one for free in the app
4230
+ * submenu; role 'about' shows app.setAboutPanelOptions() cross-platform since
4231
+ * Electron 15).
4232
+ *
4233
+ * Two corrections live here, both from the same report:
4234
+ *
4235
+ * * Cmd/Ctrl+K opened the MEMORY inspector while the item said "Search…", so
4236
+ * the label named neither the sheet nor the thing the user wanted. The
4237
+ * chord now goes to a real session search (client/session-search.js); the
4238
+ * inspector keeps its own item on its own chord instead of sharing one.
4239
+ * * There was no licence surface anywhere in the app. `Help` is now on every
4240
+ * platform and leads with Credits & Licence, which renders
4241
+ * client/credits.js — the licence, the program notice and every vendored
4242
+ * attribution, parsed from LICENSING.md and the two NOTICE files so the
4243
+ * record cannot drift from the files that already are the record. */
3635
4244
  function buildAppMenu({ app, Menu, BrowserWindow, updateManager, loggedIn }) {
3636
4245
  const isMac = process.platform === 'darwin';
3637
4246
 
@@ -3639,6 +4248,15 @@ function buildAppMenu({ app, Menu, BrowserWindow, updateManager, loggedIn }) {
3639
4248
  applicationName: app.getName(),
3640
4249
  applicationVersion: app.getVersion(),
3641
4250
  version: app.getVersion(),
4251
+ // The licence and the copyright, where the OS shows them. macOS draws
4252
+ // `credits` under the version line in its About panel; on the other two
4253
+ // platforms it is ignored, which is why the real surface is Help > Credits
4254
+ // & licence below — the same sheet on all three, opened from the app menu.
4255
+ copyright: creditsLib.COPYRIGHT,
4256
+ credits:
4257
+ `${creditsLib.LICENCE_NAME}\n${creditsLib.COPYRIGHT}\n` +
4258
+ `Source: ${creditsLib.SOURCE_URL}\n` +
4259
+ 'Help > Credits & licence lists the vendored third-party code and fonts.',
3642
4260
  });
3643
4261
 
3644
4262
  const checkForUpdatesItem = {
@@ -3652,11 +4270,44 @@ function buildAppMenu({ app, Menu, BrowserWindow, updateManager, loggedIn }) {
3652
4270
  accelerator: 'CmdOrCtrl+N',
3653
4271
  click: () => sendToAppWindow(BrowserWindow, MENU_NEW_CHAT_CHANNEL),
3654
4272
  };
4273
+ // View > Search sessions… (Cmd/Ctrl+K).
4274
+ //
4275
+ // This item used to be labelled `Search…` and opened the MEMORY inspector — the
4276
+ // accelerator, the label and the sheet disagreed about what they were for, and
4277
+ // nothing in the app searched conversations at all. A session search is now a
4278
+ // thing that exists (renderer/openSessionSearch in app.js, ranked by
4279
+ // client/session-search.js), so the plain accelerator goes to the thing the
4280
+ // label promises; the inspector keeps a menu item of its own below.
3655
4281
  const searchItem = {
3656
- label: 'Search…',
4282
+ label: 'Search sessions…',
3657
4283
  accelerator: 'CmdOrCtrl+K',
3658
4284
  click: () => sendToAppWindow(BrowserWindow, MENU_SEARCH_CHANNEL),
3659
4285
  };
4286
+ // View > Search memory… — the inspector that Cmd/Ctrl+K used to open. Shift
4287
+ // because the plain chord is the session search now; the two are separate
4288
+ // sheets, so they cannot share a keystroke.
4289
+ const searchMemoryItem = {
4290
+ label: 'Search memory…',
4291
+ accelerator: 'CmdOrCtrl+Shift+K',
4292
+ click: () => sendToAppWindow(BrowserWindow, MENU_SEARCH_MEMORY_CHANNEL),
4293
+ };
4294
+ // Help > Credits & licence — the AGPL licence, the program notice, and every
4295
+ // vendored third-party file/font with its own licence, built by
4296
+ // client/credits.js from LICENSING.md and the two NOTICE files.
4297
+ const creditsItem = {
4298
+ label: 'Credits & Licence…',
4299
+ click: () => sendToAppWindow(BrowserWindow, MENU_CREDITS_CHANNEL),
4300
+ };
4301
+ const sourceItem = {
4302
+ label: 'Source Code',
4303
+ click: () => {
4304
+ try {
4305
+ require('electron').shell.openExternal(creditsLib.SOURCE_URL);
4306
+ } catch {
4307
+ // A shell that cannot open a URL must not break the menu build.
4308
+ }
4309
+ },
4310
+ };
3660
4311
  // Neither item knows the open session id — that's renderer state — so, like
3661
4312
  // newChatItem/searchItem above, the click just pings the renderer, which
3662
4313
  // calls window.aegis.exportSession() with its own currentSessionId. "Save
@@ -3687,17 +4338,20 @@ function buildAppMenu({ app, Menu, BrowserWindow, updateManager, loggedIn }) {
3687
4338
  {
3688
4339
  label: app.getName(),
3689
4340
  submenu: [
3690
- { role: 'about' },
3691
- checkForUpdatesItem,
3692
- { type: 'separator' },
3693
- { role: 'services' },
3694
- { type: 'separator' },
3695
- { role: 'hide' },
3696
- { role: 'hideOthers' },
3697
- { role: 'unhide' },
3698
- { type: 'separator' },
3699
- { role: 'quit' },
3700
- ],
4341
+ { role: 'about' },
4342
+ checkForUpdatesItem,
4343
+ { type: 'separator' },
4344
+ creditsItem,
4345
+ sourceItem,
4346
+ { type: 'separator' },
4347
+ { role: 'services' },
4348
+ { type: 'separator' },
4349
+ { role: 'hide' },
4350
+ { role: 'hideOthers' },
4351
+ { role: 'unhide' },
4352
+ { type: 'separator' },
4353
+ { role: 'quit' },
4354
+ ],
3701
4355
  },
3702
4356
  ]
3703
4357
  : []),
@@ -3729,6 +4383,7 @@ function buildAppMenu({ app, Menu, BrowserWindow, updateManager, loggedIn }) {
3729
4383
  label: 'View',
3730
4384
  submenu: [
3731
4385
  searchItem,
4386
+ searchMemoryItem,
3732
4387
  { type: 'separator' },
3733
4388
  fingerprintItem,
3734
4389
  googleDriveItem,
@@ -3739,14 +4394,21 @@ function buildAppMenu({ app, Menu, BrowserWindow, updateManager, loggedIn }) {
3739
4394
  { role: 'toggleDevTools', accelerator: 'CmdOrCtrl+Shift+I' },
3740
4395
  ],
3741
4396
  },
3742
- ...(isMac
3743
- ? []
3744
- : [
3745
- {
3746
- label: 'Help',
3747
- submenu: [{ role: 'about' }],
3748
- },
3749
- ]),
4397
+ // Help exists on EVERY platform now, not just the non-mac ones: it is where
4398
+ // Credits & Licence lives, and a mac build that only reached it through the
4399
+ // app submenu would be the one place the licence surface was hidden behind
4400
+ // a platform convention. mac keeps its `role: 'about'` in the app submenu
4401
+ // (that is a mac convention, and About wants to stay where the OS puts it),
4402
+ // so the duplicated item is omitted there rather than shown twice.
4403
+ {
4404
+ label: 'Help',
4405
+ submenu: [
4406
+ creditsItem,
4407
+ sourceItem,
4408
+ { type: 'separator' },
4409
+ ...(isMac ? [] : [{ role: 'about' }]),
4410
+ ],
4411
+ },
3750
4412
  ];
3751
4413
  return Menu.buildFromTemplate(template);
3752
4414
  }
@@ -4223,6 +4885,7 @@ function bootstrap() {
4223
4885
  // re-read as a veto on every horizon. Same escape hatch as `/automode on` in
4224
4886
  // the CLI, which shares this store.
4225
4887
  registerConfirmModeIpc(ipcMain, withAutoRoundsSwitch(createConfirmModeDispatch(settings), modelIpc.modelDispatch));
4888
+ registerConfirmModeIpc(ipcMain, createPermissionModeDispatch(settings));
4226
4889
 
4227
4890
  // Vault backend preference (Settings/the authorship panel → Google Drive /
4228
4891
  // AE / No sync): aegis:getVaultBackend / aegis:setVaultBackend. Registered
@@ -4233,6 +4896,25 @@ function bootstrap() {
4233
4896
  // next publish/anchor/vault/audit call with no restart.
4234
4897
  registerConfirmModeIpc(ipcMain, createVaultBackendDispatch(settings));
4235
4898
 
4899
+ // Permission rules editor (Settings › Tool approvals › Rules):
4900
+ // aegis:permRulesList / permRulesAdd / permRulesRemove, backed by
4901
+ // lib/local/perm-store.js — a thin view over the SAME
4902
+ // ~/.aegiscode/permissions.json that /permissions and §3's "Always allow this
4903
+ // command" write. Registered beside confirm mode because it is the other half
4904
+ // of the same card: the switch says whether the gate is up, these rules say
4905
+ // what it decides without asking. Read fresh on every call — no cache — so a
4906
+ // rule edited here reaches the very next tool call, and one edited in the CLI
4907
+ // window shows up here on the next repaint.
4908
+ registerConfirmModeIpc(ipcMain, createPermRulesDispatch(require('./lib/local/perm-store.js')));
4909
+
4910
+ // aegis:getSandboxPolicy / setSandboxPolicy — the posture switch above, in
4911
+ // the same card. `null` in the store means nobody chose, and the engine's
4912
+ // default (workspace-write) applies; the renderer shows the effective mode.
4913
+ registerConfirmModeIpc(
4914
+ ipcMain,
4915
+ createSandboxPolicyDispatch(settings, require('./lib/local/sandbox.js'), { appDir: __dirname })
4916
+ );
4917
+
4236
4918
  // Funnel instrumentation (Phase 2 of docs/upgrade-conversion-plan.md):
4237
4919
  // aegis:telemetryEvent / aegis:telemetryReport, backed by
4238
4920
  // lib/local/telemetry.js.
@@ -4521,6 +5203,7 @@ function bootstrap() {
4521
5203
  // it is what stops a beat from being sent while Electron tears the process
4522
5204
  // down under it.
4523
5205
  if (presenceBeacon && typeof presenceBeacon.stop === 'function') presenceBeacon.stop();
5206
+ closeMemoryIndex();
4524
5207
  globalShortcut.unregisterAll();
4525
5208
  // The update manager's retry/interval timers are unref'd so they never
4526
5209
  // hold the process open, but an explicit quit should still cancel them
@@ -4601,6 +5284,53 @@ function bootstrap() {
4601
5284
  (opts) => dialog.showSaveDialog(BrowserWindow.getFocusedWindow(), opts),
4602
5285
  (filePath, content) => fs.promises.writeFile(filePath, content, 'utf8')
4603
5286
  );
5287
+ // Help > Credits & licence. Resolves the whole attribution payload, so the
5288
+ // renderer paints rows it was handed rather than assembling a licence list of
5289
+ // its own — and so the SAME payload can be printed by the terminal face's
5290
+ // /license. Never throws: a packaged tree missing a NOTICE opens the sheet
5291
+ // with the part that IS there, because a credits surface that errors is a
5292
+ // credits surface that is missing, which is the bug this pair fixes.
5293
+ ipcMain.handle(`${IPC_PREFIX}credits`, () => {
5294
+ try {
5295
+ return creditsLib.creditsFromDisk({
5296
+ readText: (rel) => {
5297
+ // Two layouts, same reason as every other staged module: `client/`
5298
+ // beside this file in a checkout, or the packaged app dir (where the
5299
+ // documents are anchored at the repo-relative path because
5300
+ // electron-builder copies the app dir wholesale).
5301
+ const candidates = [
5302
+ path.join(__dirname, '..', rel),
5303
+ path.join(__dirname, rel),
5304
+ path.join(process.resourcesPath || '', 'app', rel),
5305
+ ];
5306
+ for (const file of candidates) {
5307
+ try {
5308
+ return { path: file, text: fs.readFileSync(file, 'utf8') };
5309
+ } catch {
5310
+ // next candidate
5311
+ }
5312
+ }
5313
+ return null;
5314
+ },
5315
+ });
5316
+ } catch (err) {
5317
+ return {
5318
+ program: {
5319
+ licence: creditsLib.LICENCE_ID,
5320
+ name: creditsLib.LICENCE_NAME,
5321
+ url: creditsLib.LICENCE_URL,
5322
+ source: creditsLib.SOURCE_URL,
5323
+ copyright: creditsLib.COPYRIGHT,
5324
+ notice: creditsLib.COPYRIGHT,
5325
+ },
5326
+ documents: [],
5327
+ code: [],
5328
+ fonts: [],
5329
+ missing: ['licensing', 'vendor', 'fonts'],
5330
+ error: String((err && err.message) || err),
5331
+ };
5332
+ }
5333
+ });
4604
5334
  rebuildAppMenu();
4605
5335
 
4606
5336
  // The local file this window is allowed to be at — used both to restore a
@@ -4884,6 +5614,8 @@ if (electron && electron.app) {
4884
5614
  }
4885
5615
 
4886
5616
  module.exports = {
5617
+ memoryIndex,
5618
+ closeMemoryIndex,
4887
5619
  createIpcDispatch,
4888
5620
  registerIpc,
4889
5621
  providerRouteConfigured,
@@ -4897,6 +5629,8 @@ module.exports = {
4897
5629
  CHAT_DELTA_CHANNEL,
4898
5630
  MENU_NEW_CHAT_CHANNEL,
4899
5631
  MENU_SEARCH_CHANNEL,
5632
+ MENU_SEARCH_MEMORY_CHANNEL,
5633
+ MENU_CREDITS_CHANNEL,
4900
5634
  MENU_EXPORT_MARKDOWN_CHANNEL,
4901
5635
  MENU_EXPORT_JSON_CHANNEL,
4902
5636
  MENU_FINGERPRINT_CHANNEL,
@@ -4921,6 +5655,7 @@ module.exports = {
4921
5655
  createEngine,
4922
5656
  resolveUserDataDir,
4923
5657
  importForeignMemory,
5658
+ importForeignSessions,
4924
5659
  isSafeExternalUrl,
4925
5660
  createUpdateManager,
4926
5661
  createNpmUpdateManager,
@@ -4939,6 +5674,8 @@ module.exports = {
4939
5674
  registerQuickLauncherIpc,
4940
5675
  createConfirmModeDispatch,
4941
5676
  createVaultBackendDispatch,
5677
+ createPermRulesDispatch,
5678
+ createSandboxPolicyDispatch,
4942
5679
  withAutoRoundsSwitch,
4943
5680
  createTelemetryDispatch,
4944
5681
  registerTelemetryIpc,