aegiscode 6.8.11 → 6.8.13

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.
@@ -42,6 +42,7 @@ const { spawn } = require('node:child_process');
42
42
  const crypto = require('node:crypto');
43
43
  const fs = require('node:fs');
44
44
  const path = require('node:path');
45
+ const { pathToFileURL } = require('node:url');
45
46
  const { agentRoles } = require('./agents.js');
46
47
 
47
48
  const OUTPUT_CAP = 30_000; // chars fed back to the model per tool result
@@ -770,9 +771,121 @@ function isTool(name) {
770
771
  * all land on the error branch rather than rejecting. `ctx` carries per-turn
771
772
  * state (getShell, signal); omit it and exec falls back to a one-shot spawn.
772
773
  */
774
+ /**
775
+ * `tools/agent-gate.mjs` is ESM and this module is CJS, so it is imported
776
+ * dynamically and once. The candidates are tried in order; the first that
777
+ * resolves wins:
778
+ *
779
+ * 1. `../../../tools/agent-gate.mjs` — the repo checkout (dev / CI). This is
780
+ * the SAME file the git hooks execute, so "what is allowed" is computed
781
+ * once, by one implementation.
782
+ * 2. `<process.resourcesPath>/tools/agent-gate.mjs` — where electron-builder's
783
+ * `extraResources` puts it in a packaged build, as a real file OUTSIDE the
784
+ * asar. That placement is load-bearing, not cosmetic: the gate is loaded
785
+ * with dynamic `import()`, and Node's ESM loader does not go through
786
+ * Electron's asar-aware fs patch (electron/asar#249), so a copy living only
787
+ * inside the archive can fail to resolve — leaving the packaged app with no
788
+ * gate at all. This is the app's only dynamic ESM import, so nothing else
789
+ * here exercises that path. Conveniently this is also what candidate (1)
790
+ * resolves to from `resources/app.asar/lib/local/`, so dev and packaged
791
+ * builds agree on one file.
792
+ * 3. `../../vendor/agent-gate.mjs` — the staged copy inside the app dir, kept
793
+ * as the last resort for a build that is not archived (`asar: false`) or an
794
+ * npm-installed tree. It is the candidate that fails inside an asar, hence
795
+ * third and not first.
796
+ *
797
+ * Before (2) existed a packaged build had no gate at all: the manifest is found
798
+ * by climbing from the working directory, so the packaged app would open a
799
+ * guarded tree and every write through it succeeded while the same call through
800
+ * the repo copy was refused.
801
+ *
802
+ * If nothing resolves, that is a broken gate rather than a permissive one, and
803
+ * executeTool refuses mutating calls into a tree that declares a manifest.
804
+ */
805
+ let agentGatePromise;
806
+
807
+ function agentGateCandidates({ resourcesPath = process.resourcesPath, dirname = __dirname } = {}) {
808
+ const candidates = ['../../../tools/agent-gate.mjs'];
809
+ // process.resourcesPath is an Electron-provided value and is absent under
810
+ // plain node, so this is guarded rather than assumed. An absolute path must
811
+ // be a file URL to be imported.
812
+ if (typeof resourcesPath === 'string' && resourcesPath) {
813
+ candidates.push(pathToFileURL(path.join(resourcesPath, 'tools', 'agent-gate.mjs')).href);
814
+ }
815
+ candidates.push('../../vendor/agent-gate.mjs');
816
+ return candidates;
817
+ }
818
+
819
+ function loadAgentGate() {
820
+ if (!agentGatePromise) {
821
+ const candidates = agentGateCandidates();
822
+ const tryNext = (i) => (i >= candidates.length
823
+ ? null
824
+ : import(candidates[i]).catch(() => tryNext(i + 1)));
825
+ agentGatePromise = tryNext(0);
826
+ }
827
+ return agentGatePromise;
828
+ }
829
+
830
+ /**
831
+ * The nearest `.aegis/guard.json` at or above `start`, or null. The identical
832
+ * climb as findManifest() in tools/agent-gate.mjs and src/repoguard.js. It is
833
+ * used ONLY to decide whether a call that could not load the gate module is
834
+ * unsafe; when the module loads it is the sole authority.
835
+ */
836
+ function nearestManifest(start) {
837
+ let dir = path.resolve(start || process.cwd());
838
+ try { if (fs.statSync(dir).isFile()) dir = path.dirname(dir); } catch { /* keep as-is */ }
839
+ for (;;) {
840
+ const candidate = path.join(dir, '.aegis', 'guard.json');
841
+ if (fs.existsSync(candidate)) return candidate;
842
+ const parent = path.dirname(dir);
843
+ if (parent === dir) return null;
844
+ dir = parent;
845
+ }
846
+ }
847
+
773
848
  async function executeTool(name, args, ctx) {
774
849
  if (!isTool(name)) return fail(`unknown tool "${name}" (known: ${toolNames().join(', ')})`);
775
850
  const input = args && typeof args === 'object' ? args : {};
851
+ // ── agent-key gate (tools/agent-gate.mjs) ──────────────────────────────
852
+ // The in-process half of the lock whose other half is .githooks/. A tree
853
+ // that declares .aegis/guard.json must not be mutated through this app
854
+ // without the key, exactly as it cannot be mutated by the engine or
855
+ // committed by git. Reads are never gated. Refused — not warned — when the
856
+ // key is absent, the manifest is unreadable, or the key file is
857
+ // world-readable; AEGIS_GATE_SKIP=1 is the one bypass, and it is refused in
858
+ // an unattended run. The module is required lazily so a packaged app whose
859
+ // tree has no tools/ directory still starts and simply has no gate.
860
+ let gate = null;
861
+ try {
862
+ gate = await loadAgentGate();
863
+ } catch { /* not running from the repo: no manifest to honour */ }
864
+ if (gate) {
865
+ const verdict = gate.guardTool({
866
+ tool: name, args: input, cwd: (ctx && ctx.cwd) || process.cwd(),
867
+ env: process.env, unattended: Boolean(ctx && ctx.autonomous),
868
+ });
869
+ if (!verdict.allowed) return fail(gate.refusalText(verdict));
870
+ if (verdict.code === 'skipped') {
871
+ const res = await EXECUTORS[name](input, ctx || {});
872
+ return res && typeof res === 'object' ? { ...res, output: `⚠ ${verdict.reason}\n${res.output || ''}` } : res;
873
+ }
874
+ } else if (MUTATING_TOOLS.has(name)) {
875
+ // Neither the repo copy nor the staged one loaded. A broken gate must
876
+ // never silently allow (the hooks exit 4 for exactly this reason), so a
877
+ // mutating call into a tree that declares a manifest is refused with the
878
+ // path of the manifest that could not be honoured.
879
+ const man = nearestManifest((ctx && ctx.cwd) || process.cwd());
880
+ if (man) {
881
+ return fail(
882
+ `error: refused — ${man} declares an agent-gated tree, but the agent-key gate module could not be loaded `
883
+ + '(tried tools/agent-gate.mjs beside the app and vendor/agent-gate.mjs inside it), so this '
884
+ + `${name} cannot be authorised. A build that missed the staged copy is the usual cause: `
885
+ + 'run scripts/predist.mjs before packaging.',
886
+ );
887
+ }
888
+ }
776
889
  try {
777
890
  return await EXECUTORS[name](input, ctx || {});
778
891
  } catch (e) {
@@ -92,7 +92,59 @@ const AVATAR_NAMESPACE = '__avatar';
92
92
  * main.js telemetryEnabled() through getTelemetryOptIn(). */
93
93
  const TELEMETRY_NAMESPACE = '__telemetry';
94
94
 
95
- /** Namespaces the provider-config surface must never see or mutate. */
95
+ /** Reserved namespace for the auto-drain opt-in:
96
+ * `{ enabled, intervalMs }` — app-level, not a provider.
97
+ *
98
+ * DEFAULT OFF, and unlike every preference above that default is the design
99
+ * rather than a convention: this is the one setting in the app that causes a
100
+ * full tool loop to run on a real model in the user's checkout with nobody
101
+ * watching. desktop/main.js and desktop/preload.js both used to state the
102
+ * absolute rule — "there is no interval, no drain at startup, and no
103
+ * drain-on-idle anywhere" — and that rule is still what an install that never
104
+ * touches this namespace gets. What changed (user request, phase A of the
105
+ * automation work) is that the rule became a DEFAULT instead of an absolute:
106
+ * an explicit `enabled: true` here is the only thing that arms a timer, the
107
+ * toggle that writes it is in the queue card, and `lib/auto.js` refuses to
108
+ * run a tick when the queue is empty or another host already holds the drain
109
+ * lock. Nothing secret lives here, so no encryption — same shape as
110
+ * `__confirmMode`/`__memoryPersist` above. */
111
+ const AUTO_DRAIN_NAMESPACE = '__autoDrain';
112
+
113
+ /** Reserved namespace for the auto-mint (seal-on-quiet) opt-in:
114
+ * `{ enabled, publish }` — app-level, not a provider.
115
+ *
116
+ * DEFAULT OFF for the same reason as auto-drain, and `publish` is a second,
117
+ * independent opt-in: sealing writes a local record, whereas publishing sends
118
+ * those bytes to the vault over `rclone` and writes an anchor beside them. An
119
+ * automatic network copy is never implied by an automatic seal.
120
+ *
121
+ * The AI half of the record resolves through the shared rungs in
122
+ * client/attest.js (`$AEGIS_AI_SECRET`/`$AEGIS_AI_MODEL` in the app scope) —
123
+ * this namespace deliberately does NOT hold a credential, because a settings
124
+ * file that can carry a provider key is a second place to leak one. */
125
+ const AUTO_MINT_NAMESPACE = '__autoMint';
126
+
127
+ /** How often an armed auto-drain looks at the queue. One minute is the
128
+ * compromise the two failure modes set: a shorter interval makes the desktop
129
+ * a busy-waiter over a file several hosts write (each tick stats the queue and
130
+ * the lock), and a longer one means a task queued in the card sits visibly
131
+ * idle. The worker does the rest of the waiting itself. */
132
+ const AUTO_DRAIN_INTERVAL_DEFAULT_MS = 60_000;
133
+
134
+ /** Floor for `intervalMs`. Below this the timer is a poll loop, not a drain
135
+ * cadence: nothing about a queue whose tasks take minutes to run changes
136
+ * fifteen times a second, and the tick does file I/O. */
137
+ const AUTO_DRAIN_INTERVAL_MIN_MS = 15_000;
138
+
139
+ /** Ceiling for `intervalMs` — half an hour. A hand-edited settings file asking
140
+ * for a day is a typo, not a preference. */
141
+ const AUTO_DRAIN_INTERVAL_MAX_MS = 30 * 60_000;
142
+
143
+ /** Reserved namespaces: the provider-config surface must never see or mutate
144
+ * any of these. The two automation switches are here for the SAME reason the
145
+ * others are — `set()`/`remove()`/`list()` operate on provider rows, and a
146
+ * preference parked in that namespace would be listed as a provider and
147
+ * deletable with "Remove". */
96
148
  const RESERVED_NAMESPACES = Object.freeze([
97
149
  AEGIS_KEY_NAMESPACE,
98
150
  LEGACY_AEGIS_NAMESPACE,
@@ -101,6 +153,8 @@ const RESERVED_NAMESPACES = Object.freeze([
101
153
  MEMORY_PERSIST_NAMESPACE,
102
154
  AVATAR_NAMESPACE,
103
155
  TELEMETRY_NAMESPACE,
156
+ AUTO_DRAIN_NAMESPACE,
157
+ AUTO_MINT_NAMESPACE,
104
158
  ]);
105
159
 
106
160
  /** Motion modes the renderer understands (`system` = follow the OS). */
@@ -451,6 +505,93 @@ function createSettingsStore({ dir, safeStorage } = {}) {
451
505
  return avatarState();
452
506
  }
453
507
 
508
+ // --- Auto-drain / auto-mint: reserved namespaces, DEFAULT OFF ------------
509
+ // The two opt-in automations (lib/auto.js). Both live in their own top-level
510
+ // namespace, both are booted OFF, and both keep the "off" and "never set"
511
+ // cases distinguishable through a `source` field — the same shape
512
+ // memoryPersistState()/avatarState() use above, for the same reason: a UI
513
+ // that cannot tell "you turned it off" from "this build never had it" shows
514
+ // the wrong sentence after an upgrade.
515
+ //
516
+ // `intervalMs` is clamped rather than trusted: it comes back through IPC from
517
+ // a renderer and off disk from a hand-edited file, and a timer is the one
518
+ // place where a hostile or fat-fingered number costs real CPU.
519
+
520
+ /** A usable tick interval, or the default. Out-of-range reads as unset. */
521
+ function clampAutoDrainInterval(value) {
522
+ const n = Number(value);
523
+ if (!Number.isFinite(n)) return AUTO_DRAIN_INTERVAL_DEFAULT_MS;
524
+ const ms = Math.round(n);
525
+ if (ms < AUTO_DRAIN_INTERVAL_MIN_MS || ms > AUTO_DRAIN_INTERVAL_MAX_MS) {
526
+ return AUTO_DRAIN_INTERVAL_DEFAULT_MS;
527
+ }
528
+ return ms;
529
+ }
530
+
531
+ function getAutoDrain() {
532
+ const cfg = load()[AUTO_DRAIN_NAMESPACE] || {};
533
+ return {
534
+ // Unset === false. This is the opposite of confirm mode/memory persist,
535
+ // and it is the whole point of the feature: nothing drains itself until
536
+ // someone says so in as many words.
537
+ enabled: cfg.enabled === true,
538
+ intervalMs: clampAutoDrainInterval(cfg.intervalMs),
539
+ };
540
+ }
541
+
542
+ function autoDrainState() {
543
+ const cfg = load()[AUTO_DRAIN_NAMESPACE] || {};
544
+ return {
545
+ ...getAutoDrain(),
546
+ source: cfg.enabled === undefined ? 'default' : 'config',
547
+ };
548
+ }
549
+
550
+ function setAutoDrain(patch = {}) {
551
+ const current = getAutoDrain();
552
+ const p = patch && typeof patch === 'object' ? patch : {};
553
+ const data = load();
554
+ data[AUTO_DRAIN_NAMESPACE] = {
555
+ enabled: p.enabled === undefined ? current.enabled : Boolean(p.enabled),
556
+ intervalMs:
557
+ p.intervalMs === undefined
558
+ ? current.intervalMs
559
+ : clampAutoDrainInterval(p.intervalMs),
560
+ };
561
+ save(data);
562
+ return autoDrainState();
563
+ }
564
+
565
+ function getAutoMint() {
566
+ const cfg = load()[AUTO_MINT_NAMESPACE] || {};
567
+ return {
568
+ enabled: cfg.enabled === true,
569
+ // Independent of `enabled` on purpose: an automatic seal must not drag
570
+ // an automatic upload along with it.
571
+ publish: cfg.publish === true,
572
+ };
573
+ }
574
+
575
+ function autoMintState() {
576
+ const cfg = load()[AUTO_MINT_NAMESPACE] || {};
577
+ return {
578
+ ...getAutoMint(),
579
+ source: cfg.enabled === undefined ? 'default' : 'config',
580
+ };
581
+ }
582
+
583
+ function setAutoMint(patch = {}) {
584
+ const current = getAutoMint();
585
+ const p = patch && typeof patch === 'object' ? patch : {};
586
+ const data = load();
587
+ data[AUTO_MINT_NAMESPACE] = {
588
+ enabled: p.enabled === undefined ? current.enabled : Boolean(p.enabled),
589
+ publish: p.publish === undefined ? current.publish : Boolean(p.publish),
590
+ };
591
+ save(data);
592
+ return autoMintState();
593
+ }
594
+
454
595
  return {
455
596
  file,
456
597
  get,
@@ -476,6 +617,13 @@ function createSettingsStore({ dir, safeStorage } = {}) {
476
617
  getAvatar,
477
618
  avatarState,
478
619
  setAvatar,
620
+ getAutoDrain,
621
+ autoDrainState,
622
+ setAutoDrain,
623
+ getAutoMint,
624
+ autoMintState,
625
+ setAutoMint,
626
+ clampAutoDrainInterval,
479
627
  };
480
628
  }
481
629
 
@@ -488,6 +636,11 @@ module.exports = {
488
636
  MEMORY_PERSIST_NAMESPACE,
489
637
  AVATAR_NAMESPACE,
490
638
  TELEMETRY_NAMESPACE,
639
+ AUTO_DRAIN_NAMESPACE,
640
+ AUTO_MINT_NAMESPACE,
641
+ AUTO_DRAIN_INTERVAL_DEFAULT_MS,
642
+ AUTO_DRAIN_INTERVAL_MIN_MS,
643
+ AUTO_DRAIN_INTERVAL_MAX_MS,
491
644
  AVATAR_MOTION_MODES,
492
645
  DEFAULT_QUICK_LAUNCHER_SHORTCUT,
493
646
  RESERVED_NAMESPACES,