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
@@ -50,6 +50,14 @@ const crypto = require('node:crypto');
50
50
  // the digest, so silencing it here is itself a change to the digest.
51
51
  const integrity = require('./integrity.js');
52
52
 
53
+ // The outcome bound (~/plan/agent-safety-plan.md §1b). Asked at BOTH spawn seams
54
+ // below — the persistent session and the one-shot fallback — because a gate
55
+ // that only covers the session lets a self-healed turn fall through to an
56
+ // unconfined spawn, which is the same shape of hole the dialect probe closed.
57
+ // `spawnPlan` is the single decision, so the two paths cannot disagree about
58
+ // whether a command was confined.
59
+ const sandbox = require('./sandbox.js');
60
+
53
61
  // The ONE platform module (client/platform.js, Phase 30.1) — resolved the same
54
62
  // two ways this repo resolves every shared module (see tools.js/engine.js):
55
63
  // repo-relative in a checkout and in the CLI's mirrored vendor tree, then the
@@ -143,6 +151,33 @@ function shellSeams(options) {
143
151
  };
144
152
  }
145
153
 
154
+ /**
155
+ * The sandbox half of a spawn, read off the same options bag the shell choice
156
+ * comes from.
157
+ *
158
+ * Absent `sandbox` means "no policy was requested" and spawns unconfined, which
159
+ * is what every existing caller (and every test) gets — the engine opts in by
160
+ * passing it. An explicit `{ policy: { mode: 'off' } }` is also unconfined;
161
+ * the difference is that the engine can pass a real policy and have it apply.
162
+ *
163
+ * `strict` rides through: false degrades loudly when the host cannot confine,
164
+ * true refuses to spawn at all.
165
+ */
166
+ function shellSandbox(options) {
167
+ const o = options && typeof options === 'object' ? options : {};
168
+ const s = o.sandbox;
169
+ if (!s || typeof s !== 'object') return null;
170
+ return {
171
+ policy: s.policy || null,
172
+ state: s.state || null,
173
+ strict: s.strict === true,
174
+ workspace: s.workspace,
175
+ appDir: s.appDir,
176
+ env: s.env || o.env,
177
+ bwrap: s.bwrap,
178
+ };
179
+ }
180
+
146
181
  /**
147
182
  * Try one candidate. Returns a verified spec or null, recording why in `tried`
148
183
  * and every shell it actually executed in `executed`.
@@ -449,7 +484,19 @@ function oneShotShell({ command, timeout = DEFAULT_TIMEOUT, working_directory, s
449
484
  return;
450
485
  }
451
486
  const call = spec.kind === 'powershell' ? spec.oneShot : spec;
452
- const child = spawn(call.cmd, [call.arg, String(command || '')], {
487
+ // Sandbox seam (one-shot). `degraded` is non-null when the policy asked for
488
+ // confinement and the host could not provide it — surfaced in the output
489
+ // rather than swallowed, because a silent no-op sandbox is a false
490
+ // assurance (see sandbox.js's header).
491
+ const plan = sandbox.spawnPlan(
492
+ shellSandbox(shellOptions), call.cmd, [call.arg, String(command || '')],
493
+ { cwd: working_directory || process.cwd() },
494
+ );
495
+ if (!plan.ok) {
496
+ resolve({ content: `exec: ${plan.reason}`, isError: true });
497
+ return;
498
+ }
499
+ const child = spawn(plan.file, plan.args, {
453
500
  cwd: working_directory || process.cwd(),
454
501
  timeout: Math.min(Number(timeout) || DEFAULT_TIMEOUT, MAX_TIMEOUT),
455
502
  env: o.env,
@@ -469,7 +516,7 @@ function oneShotShell({ command, timeout = DEFAULT_TIMEOUT, working_directory, s
469
516
  }
470
517
 
471
518
  class ShellSession {
472
- constructor({ cwd, shellOptions } = {}) {
519
+ constructor({ cwd, shellOptions, sandbox } = {}) {
473
520
  this.sentinel = `__AEGIS_SH_${crypto.randomBytes(8).toString('hex')}__`;
474
521
  this.marker = `${this.sentinel}EXIT:`;
475
522
  this.buf = '';
@@ -479,7 +526,34 @@ class ShellSession {
479
526
  this.disposed = false; // an explicit dispose() must NOT be self-healed
480
527
  this._respawns = 0; // one self-heal attempt per session, never a loop
481
528
  this._degradedNoted = false; // the degrade marker is emitted once per session
482
- this.shellOptions = shellOptions || {};
529
+ // Set by _start(): `sandboxError` is a strict-mode refusal (run() reports
530
+ // it and never spawns), `sandboxDegraded` is the reason nothing confined
531
+ // this session. Both are null when the sandbox really applied, so a caller
532
+ // can tell "confined" from "not confined" from "not asked for".
533
+ this.sandboxError = null;
534
+ this.sandboxDegraded = null;
535
+ this._sandboxNoted = false; // the unconfined marker is emitted once per session
536
+ // A COPY, because the sandbox below is attached to this bag and mutating a
537
+ // caller's object would make the policy leak into whatever else shares it.
538
+ this.shellOptions = shellOptions && typeof shellOptions === 'object' ? { ...shellOptions } : {};
539
+ // ── The policy rides on the SAME bag both spawn seams read ─────────────
540
+ //
541
+ // engine.js has always passed `new ShellSession({ cwd, sandbox: turnSandbox })`,
542
+ // but this constructor only destructured `{ cwd, shellOptions }` — so the
543
+ // policy was silently DROPPED. `shellSandbox()` then answered null,
544
+ // `spawnPlan(null)` returned `{ ok: true, degraded: null }`, and the
545
+ // persistent session ran UNCONFINED while the transcript said nothing at
546
+ // all: not an error, not a degrade marker, just a command that looked
547
+ // confined because the turn had asked for confinement.
548
+ //
549
+ // This is the whole reason the two seams share one `spawnPlan`: the
550
+ // decision must be the same at the session and the one-shot, and it can
551
+ // only be if both are handed the same policy. Attaching it here is what
552
+ // makes the session seam reachable from engine.js at all.
553
+ //
554
+ // An explicit `shellOptions.sandbox` wins, so a caller that composes the
555
+ // bag itself (every existing test) keeps full control.
556
+ if (sandbox && !this.shellOptions.sandbox) this.shellOptions.sandbox = sandbox;
483
557
  // Resolved BEFORE anything is spawned or written: `shell.kind` is what the
484
558
  // command framing below branches on, so an unverified `$SHELL` can never
485
559
  // receive POSIX syntax — it is never spawned at all.
@@ -497,22 +571,36 @@ class ShellSession {
497
571
  }
498
572
  const env = shellSeams(this.shellOptions).env;
499
573
  try {
500
- this.child = this.shell.kind === 'powershell'
574
+ const args = this.shell.kind === 'powershell'
501
575
  // -Command - reads the script from stdin as a non-interactive session,
502
576
  // so there are no prompts to pollute output, but state still persists.
503
- ? spawn(this.shell.cmd, ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '-'], {
504
- cwd: cwd || process.cwd(),
505
- env,
506
- stdio: ['pipe', 'pipe', 'pipe'],
507
- })
577
+ ? ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '-']
508
578
  // No args → the shell reads commands from stdin as a non-interactive
509
579
  // script, so there are no prompts to pollute output, but state persists.
510
580
  // This is a shell that PASSED the POSIX probe (see resolveSessionShell).
511
- : spawn(this.shell.cmd, [], {
512
- cwd: cwd || process.cwd(),
513
- env,
514
- stdio: ['pipe', 'pipe', 'pipe'],
515
- });
581
+ : [];
582
+ // Sandbox seam (persistent session). Same `spawnPlan` the one-shot path
583
+ // uses, so "is this confined" has one answer. A non-ok plan does not
584
+ // spawn: `alive` stays false and run() reports `sandboxError` instead of
585
+ // silently degrading to an unconfined shell.
586
+ const plan = sandbox.spawnPlan(
587
+ shellSandbox(this.shellOptions), this.shell.cmd, args,
588
+ { cwd: cwd || process.cwd() },
589
+ );
590
+ if (!plan.ok) {
591
+ this.sandboxError = plan.reason;
592
+ this.alive = false;
593
+ return;
594
+ }
595
+ // The degrade marker is emitted ONCE per session, on its own line, so a
596
+ // turn that cannot be confined says so in the transcript the first time
597
+ // exec runs — not on every command, and not never.
598
+ this.sandboxDegraded = plan.degraded || null;
599
+ this.child = spawn(plan.file, plan.args, {
600
+ cwd: cwd || process.cwd(),
601
+ env,
602
+ stdio: ['pipe', 'pipe', 'pipe'],
603
+ });
516
604
  } catch {
517
605
  this.alive = false;
518
606
  return;
@@ -553,6 +641,12 @@ class ShellSession {
553
641
  if (integrity.armed()) {
554
642
  return Promise.resolve({ content: 'exec: unavailable in this build', isError: true });
555
643
  }
644
+ // A policy that could not be enforced in strict mode refuses here rather
645
+ // than falling through to the self-heal path, which would re-spawn the
646
+ // shell unconfined — the one outcome a sandbox must never produce.
647
+ if (this.sandboxError) {
648
+ return Promise.resolve({ content: `exec: ${this.sandboxError}`, isError: true });
649
+ }
556
650
  const posixSession = this.shell && this.shell.kind === 'posix-sh' && this.shell.verified;
557
651
  if (!this.alive || !this.child || ((this.shell && this.shell.kind === 'posix-sh') && !posixSession)) {
558
652
  if (!this.alive && this.shellError) {
@@ -583,7 +677,7 @@ class ShellSession {
583
677
  settled = true;
584
678
  clearTimeout(timer);
585
679
  this._pending = null;
586
- resolve(result);
680
+ resolve(this._noteSandboxDegraded(result));
587
681
  };
588
682
 
589
683
  const timer = setTimeout(() => {
@@ -666,12 +760,53 @@ class ShellSession {
666
760
  * Emitted ONCE per session so a degraded turn stays readable.
667
761
  */
668
762
  _noteDegraded(result, reason) {
763
+ // Both notices, shell first then sandbox, composed through ONE function
764
+ // because both call sites (_runViaSession and the one-shot path) need both
765
+ // and forgetting one of them is the silent-degradation bug each exists to
766
+ // prevent. Kept self-contained rather than delegating to the two helpers:
767
+ // test/shell-oneshot-win32.test.mjs calls this on a BARE receiver
768
+ // (`{_degradedNoted:false, shell:{...}}`) precisely so it does not arm a
769
+ // live session's sentinel timer, and a delegating version throws
770
+ // "this._noteShellDegraded is not a function" there. That is a real
771
+ // contract, not a test detail: every helper on this path must work when
772
+ // handed nothing but the fields it reads.
773
+ const r = result && typeof result === 'object' ? result : { content: String(result == null ? '' : result), isError: true };
774
+
775
+ let out = r;
776
+ if (this.sandboxDegraded && !this._sandboxNoted) {
777
+ this._sandboxNoted = true;
778
+ const marker = `[sandbox_unavailable] ran UNCONFINED: ${this.sandboxDegraded}`;
779
+ out = { ...out, content: `${marker}\n${out.content || ''}` };
780
+ }
781
+
782
+ if (!this._degradedNoted) {
783
+ this._degradedNoted = true;
784
+ const via = this.shell && this.shell.cmd ? this.shell.cmd : 'unknown shell';
785
+ const was = this.shell && this.shell.kind ? this.shell.kind : 'none';
786
+ const marker = `[shell_degraded] ran one-shot via ${via} (${reason}); session dialect was ${was} — quoting contracts may differ`;
787
+ out = { ...out, content: `${marker}\n${out.content || ''}` };
788
+ }
789
+ return out;
790
+ }
791
+
792
+ /**
793
+ * Say ONCE per session, in the transcript, that this command was NOT confined
794
+ * even though a policy asked for confinement.
795
+ *
796
+ * sandbox.js's header is explicit that a silent no-op sandbox is worse than no
797
+ * sandbox, because it is a false assurance: the user reads "workspace-write"
798
+ * in Settings and concludes the shell cannot touch `~/.ssh`. On an
799
+ * AppArmor-restricted host (Ubuntu 23.10+, most containers) bwrap cannot get a
800
+ * user namespace, so that is a real posture, not a hypothetical. Strict mode
801
+ * never reaches here — it refuses to spawn at all.
802
+ *
803
+ * Emitted on a marker line, once, so a whole turn stays readable.
804
+ */
805
+ _noteSandboxDegraded(result) {
669
806
  const r = result && typeof result === 'object' ? result : { content: String(result == null ? '' : result), isError: true };
670
- if (this._degradedNoted) return r;
671
- this._degradedNoted = true;
672
- const via = this.shell && this.shell.cmd ? this.shell.cmd : 'unknown shell';
673
- const was = this.shell && this.shell.kind ? this.shell.kind : 'none';
674
- const marker = `[shell_degraded] ran one-shot via ${via} (${reason}); session dialect was ${was} — quoting contracts may differ`;
807
+ if (!this.sandboxDegraded || this._sandboxNoted) return r;
808
+ this._sandboxNoted = true;
809
+ const marker = `[sandbox_unavailable] ran UNCONFINED: ${this.sandboxDegraded}`;
675
810
  return { ...r, content: `${marker}\n${r.content || ''}` };
676
811
  }
677
812
 
@@ -108,6 +108,11 @@ const pathDesc = (what) => `${what}. ${PATH_ARG_DESC}`;
108
108
  // dialect the command is written in, never in an unprobed `$SHELL`. Lives next
109
109
  // to this file in every tree that has it (repo, CLI vendor, packaged app dir).
110
110
  const shells = require('./shell.js');
111
+ // The outcome bound (~/plan/agent-safety-plan.md §1b). Required here as well as in
112
+ // shell.js because this one-shot path is a SEPARATE spawn seam: a turn whose
113
+ // session died runs here, and a sandbox wired only into the session would leave
114
+ // exactly that fallback unconfined.
115
+ const sandbox = require('./sandbox.js');
111
116
  // The second gate (see lib/local/integrity.js). Asked here because this module
112
117
  // is what HANDS the model its tool surface: a build whose own bytes have been
113
118
  // rewritten must not be given tools, and it must ask for itself rather than
@@ -927,7 +932,7 @@ function grep({ pattern, path: root } = {}, ctx = {}) {
927
932
  * exit is reported as an error so the model sees the failure, with whatever
928
933
  * the command printed attached).
929
934
  */
930
- function execOneShot({ command, cwd, timeout, maxBuffer } = {}) {
935
+ function execOneShot({ command, cwd, timeout, maxBuffer, sandboxCfg } = {}) {
931
936
  return new Promise((resolve) => {
932
937
  const limit = Math.min(Number(maxBuffer) || EXEC_MAX_BUFFER, EXEC_MAX_BUFFER);
933
938
  const ms = Math.min(Number(timeout) || EXEC_TIMEOUT_DEFAULT, EXEC_TIMEOUT_CAP);
@@ -946,9 +951,22 @@ function execOneShot({ command, cwd, timeout, maxBuffer } = {}) {
946
951
  }
947
952
  const { cmd, arg } = spec;
948
953
 
954
+ // Sandbox seam (one-shot via the tool path). `spawnPlan` is shared with
955
+ // shell.js so both seams answer "confined?" the same way; a refused plan
956
+ // reports instead of spawning, and a degraded one says so in the output.
957
+ const plan = sandbox.spawnPlan(sandboxCfg, cmd, [arg, command], { cwd: cwd || process.cwd() });
958
+ if (!plan.ok) {
959
+ resolve(fail(`sandbox: ${plan.reason}`));
960
+ return;
961
+ }
962
+ // A policy that asked for confinement and did not get it says so in the
963
+ // output, once, on the same marker line shell.js uses. Silent degradation
964
+ // would be a false assurance: the caller believes the command was confined.
965
+ const degradedNote = plan.degraded ? `[sandbox_unavailable] ran UNCONFINED: ${plan.degraded}\n` : '';
966
+
949
967
  let child;
950
968
  try {
951
- child = spawn(cmd, [arg, command], {
969
+ child = spawn(plan.file, plan.args, {
952
970
  cwd: cwd || process.cwd(),
953
971
  timeout: ms,
954
972
  killSignal: 'SIGKILL',
@@ -995,6 +1013,13 @@ function execOneShot({ command, cwd, timeout, maxBuffer } = {}) {
995
1013
  if (settled) return;
996
1014
  settled = true;
997
1015
  clearTimeout(timer);
1016
+ // Applied at the single exit point so EVERY path — success, non-zero exit,
1017
+ // timeout, overflow — carries the warning. Prepending only to `ok()` would
1018
+ // let a failing command (the interesting case) hide that it ran unconfined.
1019
+ if (degradedNote) {
1020
+ resolve(res.ok ? ok(`${degradedNote}${res.output}`) : fail(`${degradedNote}${res.error}`));
1021
+ return;
1022
+ }
998
1023
  resolve(res);
999
1024
  };
1000
1025
 
@@ -1060,11 +1085,11 @@ function exec({ command, cwd, timeout, maxBuffer } = {}, ctx = {}) {
1060
1085
  // classifier is the only thing that sets this flag; a plain tool call never
1061
1086
  // does, so the persistent session stays the default.
1062
1087
  if (ctx.oneShotExec) {
1063
- return execOneShot({ command, cwd: cwd || ctx.cwd, timeout, maxBuffer });
1088
+ return execOneShot({ command, cwd: cwd || ctx.cwd, timeout, maxBuffer, sandboxCfg: ctx.sandbox });
1064
1089
  }
1065
1090
  const shell = typeof ctx.getShell === 'function' ? ctx.getShell() : null;
1066
1091
  if (shell) return execInShell(shell, { command, cwd, timeout }, ctx.signal);
1067
- return execOneShot({ command, cwd, timeout, maxBuffer });
1092
+ return execOneShot({ command, cwd, timeout, maxBuffer, sandboxCfg: ctx.sandbox });
1068
1093
  }
1069
1094
 
1070
1095
  // ── hooks / installHooks ────────────────────────────────────────────────────
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const fs=require("node:fs"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),prefs=(()=>{try{return require("../../client/prefs.js")}catch{return require("../vendor/prefs.js")}})(),credentials=(()=>{try{return require("../../client/credentials.js")}catch{return require("../vendor/credentials.js")}})(),localTransport=require("./local/local.js"),LOCAL_NAMESPACE="local",SETTINGS_FILE="settings.json",AEGIS_KEY_NAMESPACE="__aegis",LEGACY_AEGIS_NAMESPACE="aegis",QUICK_LAUNCHER_NAMESPACE="__quickLauncher",DEFAULT_QUICK_LAUNCHER_SHORTCUT="CmdOrCtrl+Shift+Space",VAULT_BACKEND_NAMESPACE="__vaultBackend",DEFAULT_VAULT_BACKEND="aegiscloud",VAULT_BACKEND_VALUES=Object.freeze(["aegiscloud","drive","off"]),CONFIRM_MODE_NAMESPACE="__confirmMode",MEMORY_PERSIST_NAMESPACE="__memoryPersist",AVATAR_NAMESPACE="__avatar",TELEMETRY_NAMESPACE="__telemetry",AUTO_DRAIN_NAMESPACE="__autoDrain",AUTO_MINT_NAMESPACE="__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS=6e4,AUTO_DRAIN_INTERVAL_MIN_MS=15e3,AUTO_DRAIN_INTERVAL_MAX_MS=18e5,RESERVED_NAMESPACES=Object.freeze(["__aegis","aegis","__quickLauncher","__vaultBackend","__confirmMode","__memoryPersist","__avatar","__telemetry","__autoDrain","__autoMint"]),AVATAR_MOTION_MODES=Object.freeze(["system","full","minimal"]);function isReservedNamespace(e){return RESERVED_NAMESPACES.includes(e)}function maskKey(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}const IS_WIN32="win32"===process.platform;function restrictFile(e){if(IS_WIN32){const t=process.env.USERNAME||process.env.USER||process.env.USERDOMAIN;if(!t)return void console.error(`[settings] cannot restrict ${e}: no current user to grant (USERNAME unset)`);try{execFileSync("icacls",[e,"/inheritance:r","/grant:r",`${t}:(F)`],{stdio:"ignore"})}catch(t){console.error(`[settings] failed to restrict ACL on ${e}: ${t.message}`)}}else try{fs.chmodSync(e,384)}catch(t){console.error(`[settings] failed to chmod ${e} to 0600: ${t.message}`)}}function createSettingsStore({dir:e,safeStorage:t,prefsDir:n,env:r}={}){if(!e)throw new Error("createSettingsStore requires a storage dir");const o=path.join(e,SETTINGS_FILE),i=(()=>{const e=null==n?"":String(n).trim();return e?path.resolve(e):credentials.aegisHome(r)})(),s=(()=>{try{return prefs.adopt({dir:i,legacyDir:e})}catch(e){return(process.env.AEGISCODE_DEBUG||process.env.AEGIS_HIST_DEBUG)&&process.stderr.write(`aegis-desktop: shared-preference adoption failed: ${e.message}\n`),{adopted:!1,keys:[],reason:`adoption failed: ${e.message}`}}})();function a(){try{return prefs.load({dir:i})}catch{return{}}}function c(e){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);const t=a()[e];return void 0===t?null:t}const u=()=>Boolean(t&&"function"==typeof t.isEncryptionAvailable&&t.isEncryptionAvailable());function _(e){return null==e?null:u()?t.encryptString(String(e)).toString("base64"):Buffer.from(String(e),"utf8").toString("base64")}function l(e){if(!e)return null;try{const n=Buffer.from(String(e),"base64");return u()?t.decryptString(n):n.toString("utf8")}catch{return null}}function d(){try{return JSON.parse(fs.readFileSync(o,"utf8"))||{}}catch{return{}}}function A(e){fs.mkdirSync(path.dirname(o),{recursive:!0});const t=`${o}.tmp-${process.pid}`;fs.writeFileSync(t,JSON.stringify(e,null,2),{mode:384}),fs.renameSync(t,o),restrictFile(o)}function f(e){if(isReservedNamespace(e))throw new Error(`reserved namespace "${e}" is not a provider config — use setAegisKey()/aegisRawKey() for the AEGIS key`)}function E(e){const t=d()[e]||{},n=l(t.key);return{provider:e,baseURL:t.baseURL||"",configured:Boolean(n),keyMask:maskKey(n)}}function S(){const e=l((d().__aegis||{}).key);return{configured:Boolean(e),keyMask:maskKey(e)}}function m(){const e=d().__quickLauncher||{},t="string"==typeof e.shortcut&&e.shortcut.trim()?e.shortcut.trim():"CmdOrCtrl+Shift+Space";return{enabled:Boolean(e.enabled),shortcut:t}}function M(){const e=d().__vaultBackend||{};return{backend:VAULT_BACKEND_VALUES.includes(e.backend)?e.backend:"aegiscloud"}}function g(){const e=a();if("boolean"==typeof e.confirmMode)return{enabled:e.confirmMode,source:"config"};const t=d().__confirmMode||{};return void 0===t.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(t.enabled),source:"config"}}function y(){return!0===(d().__telemetry||{}).enabled}function N(){const e=a();if("boolean"==typeof e.memoryPersist)return{enabled:e.memoryPersist,source:"config"};const t=d().__memoryPersist||{};return void 0===t.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(t.enabled),source:"config"}}function p(){const e=d().__avatar||{};return{enabled:void 0===e.enabled||Boolean(e.enabled),showLevel:void 0===e.showLevel||Boolean(e.showLevel),motion:AVATAR_MOTION_MODES.includes(e.motion)?e.motion:"system"}}function v(){const e=d().__avatar||{};return{...p(),source:void 0===e.enabled?"default":"config"}}function b(e){const t=Number(e);if(!Number.isFinite(t))return 6e4;const n=Math.round(t);return n<15e3||n>18e5?6e4:n}function T(){const e=d().__autoDrain||{};return{enabled:!1!==e.enabled,intervalMs:b(e.intervalMs)}}function R(){const e=d().__autoDrain||{};return{...T(),source:void 0===e.enabled?"default":"config"}}function C(){const e=d().__autoMint||{};return{enabled:!1!==e.enabled,publish:!0===e.publish}}function h(){const e=d().__autoMint||{};return{...C(),source:void 0===e.enabled?"default":"config"}}return{file:o,sharedDir:i,adoption:s,sharedFile:function(){return prefs.prefsFile({dir:i})},getSharedPref:c,setSharedPref:function(e,t){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);return prefs.set({[e]:t},{dir:i}),c(e)},get:E,set:function(e,{baseURL:t,key:n}={}){f(e);let r=t;if("local"===e&&t){const e=localTransport.remoteRefusal(t);if(e)throw e;r=localTransport.normalizeBase(t)}const o=d(),i=o[e]||{};return void 0!==r&&(i.baseURL=r),void 0!==n&&(i.key=n?_(n):null),o[e]=i,A(o),E(e)},rawKey:function(e){return l((d()[e]||{}).key)},remove:function(e){f(e);const t=d();return delete t[e],A(t),{ok:!0}},list:function(){const e=d();return Object.keys(e).filter((e=>!isReservedNamespace(e))).map((e=>E(e)))},maskKey:maskKey,aegisKey:S,aegisRawKey:function(){return l((d().__aegis||{}).key)},aegisKeySavedAt:function(){return(d().__aegis||{}).savedAt||null},setAegisKey:function(e){const t=d();return t.__aegis={...t.__aegis||{},key:e?_(e):null,savedAt:e?(new Date).toISOString():null},A(t),S()},migrateLegacyAegisKey:function(){try{const e=d();if(!e.aegis)return{migrated:!1};const t=e.aegis||{},n=e.__aegis||{},r={...e};return t.key&&!n.key&&(r.__aegis={...n,key:t.key}),delete r.aegis,A(r),{migrated:!0}}catch{return{migrated:!1}}},quickLauncherConfig:m,setQuickLauncherConfig:function({enabled:e,shortcut:t}={}){const n=d();return n.__quickLauncher={enabled:Boolean(e),shortcut:"string"==typeof t&&t.trim()?t.trim():"CmdOrCtrl+Shift+Space"},A(n),m()},vaultBackendConfig:M,setVaultBackendConfig:function(e){if(!VAULT_BACKEND_VALUES.includes(e))return M();const t=d();return t.__vaultBackend={backend:e},A(t),M()},getConfirmMode:function(){return g().enabled},setConfirmMode:function(e){prefs.set({confirmMode:Boolean(e)},{dir:i});const t=d();return void 0!==t.__confirmMode&&(delete t.__confirmMode,A(t)),g().enabled},confirmModeState:g,getTelemetryOptIn:y,setTelemetryOptIn:function(e){const t=d();return t.__telemetry={enabled:Boolean(e)},A(t),y()},getMemoryPersist:function(){return N().enabled},memoryPersistState:N,setMemoryPersist:function(e){prefs.set({memoryPersist:Boolean(e)},{dir:i});const t=d();return void 0!==t.__memoryPersist&&(delete t.__memoryPersist,A(t)),N()},getAvatar:p,avatarState:v,setAvatar:function(e={}){const t=p(),n=e&&"object"==typeof e?e:{},r={enabled:void 0===n.enabled?t.enabled:Boolean(n.enabled),showLevel:void 0===n.showLevel?t.showLevel:Boolean(n.showLevel),motion:AVATAR_MOTION_MODES.includes(n.motion)?n.motion:t.motion},o=d();return o.__avatar=r,A(o),v()},getAutoDrain:T,autoDrainState:R,setAutoDrain:function(e={}){const t=T(),n=e&&"object"==typeof e?e:{},r=d();return r.__autoDrain={enabled:void 0===n.enabled?t.enabled:Boolean(n.enabled),intervalMs:void 0===n.intervalMs?t.intervalMs:b(n.intervalMs)},A(r),R()},getAutoMint:C,autoMintState:h,setAutoMint:function(e={}){const t=C(),n=e&&"object"==typeof e?e:{},r=d();return r.__autoMint={enabled:void 0===n.enabled?t.enabled:Boolean(n.enabled),publish:void 0===n.publish?t.publish:Boolean(n.publish)},A(r),h()},clampAutoDrainInterval:b}}module.exports={SETTINGS_FILE:SETTINGS_FILE,AEGIS_KEY_NAMESPACE:"__aegis",LEGACY_AEGIS_NAMESPACE:"aegis",QUICK_LAUNCHER_NAMESPACE:"__quickLauncher",VAULT_BACKEND_NAMESPACE:"__vaultBackend",CONFIRM_MODE_NAMESPACE:"__confirmMode",MEMORY_PERSIST_NAMESPACE:"__memoryPersist",AVATAR_NAMESPACE:"__avatar",TELEMETRY_NAMESPACE:"__telemetry",AUTO_DRAIN_NAMESPACE:"__autoDrain",AUTO_MINT_NAMESPACE:"__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS:6e4,AUTO_DRAIN_INTERVAL_MIN_MS:15e3,AUTO_DRAIN_INTERVAL_MAX_MS:18e5,AVATAR_MOTION_MODES:AVATAR_MOTION_MODES,DEFAULT_QUICK_LAUNCHER_SHORTCUT:"CmdOrCtrl+Shift+Space",DEFAULT_VAULT_BACKEND:"aegiscloud",VAULT_BACKEND_VALUES:VAULT_BACKEND_VALUES,RESERVED_NAMESPACES:RESERVED_NAMESPACES,isReservedNamespace:isReservedNamespace,maskKey:maskKey,createSettingsStore:createSettingsStore};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),prefs=(()=>{try{return require("../../client/prefs.js")}catch{return require("../vendor/prefs.js")}})(),credentials=(()=>{try{return require("../../client/credentials.js")}catch{return require("../vendor/credentials.js")}})(),localTransport=require("./local/local.js"),LOCAL_NAMESPACE="local",SETTINGS_FILE="settings.json",AEGIS_KEY_NAMESPACE="__aegis",LEGACY_AEGIS_NAMESPACE="aegis",QUICK_LAUNCHER_NAMESPACE="__quickLauncher",DEFAULT_QUICK_LAUNCHER_SHORTCUT="CmdOrCtrl+Shift+Space",VAULT_BACKEND_NAMESPACE="__vaultBackend",DEFAULT_VAULT_BACKEND="aegiscloud",VAULT_BACKEND_VALUES=Object.freeze(["aegiscloud","drive","off"]),CONFIRM_MODE_NAMESPACE="__confirmMode",MEMORY_PERSIST_NAMESPACE="__memoryPersist",AVATAR_NAMESPACE="__avatar",TELEMETRY_NAMESPACE="__telemetry",AUTO_DRAIN_NAMESPACE="__autoDrain",AUTO_MINT_NAMESPACE="__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS=6e4,AUTO_DRAIN_INTERVAL_MIN_MS=15e3,AUTO_DRAIN_INTERVAL_MAX_MS=18e5,RESERVED_NAMESPACES=Object.freeze(["__aegis","aegis","__quickLauncher","__vaultBackend","__confirmMode","__memoryPersist","__avatar","__telemetry","__autoDrain","__autoMint"]),AVATAR_MOTION_MODES=Object.freeze(["system","full","minimal"]);function isReservedNamespace(e){return RESERVED_NAMESPACES.includes(e)}function maskKey(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}const IS_WIN32="win32"===process.platform;function restrictFile(e){if(IS_WIN32){const n=process.env.USERNAME||process.env.USER||process.env.USERDOMAIN;if(!n)return void console.error(`[settings] cannot restrict ${e}: no current user to grant (USERNAME unset)`);try{execFileSync("icacls",[e,"/inheritance:r","/grant:r",`${n}:(F)`],{stdio:"ignore"})}catch(n){console.error(`[settings] failed to restrict ACL on ${e}: ${n.message}`)}}else try{fs.chmodSync(e,384)}catch(n){console.error(`[settings] failed to chmod ${e} to 0600: ${n.message}`)}}function createSettingsStore({dir:e,safeStorage:n,prefsDir:t,env:r}={}){if(!e)throw new Error("createSettingsStore requires a storage dir");const o=path.join(e,SETTINGS_FILE),i=(()=>{const e=null==t?"":String(t).trim();return e?path.resolve(e):credentials.aegisHome(r)})(),s=(()=>{try{return prefs.adopt({dir:i,legacyDir:e})}catch(e){return(process.env.AEGISCODE_DEBUG||process.env.AEGIS_HIST_DEBUG)&&process.stderr.write(`aegis-desktop: shared-preference adoption failed: ${e.message}\n`),{adopted:!1,keys:[],reason:`adoption failed: ${e.message}`}}})();function a(){try{return prefs.load({dir:i})}catch{return{}}}function c(e){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);const n=a()[e];return void 0===n?null:n}const u=()=>Boolean(n&&"function"==typeof n.isEncryptionAvailable&&n.isEncryptionAvailable());function _(e){return null==e?null:u()?n.encryptString(String(e)).toString("base64"):Buffer.from(String(e),"utf8").toString("base64")}function l(e){if(!e)return null;try{const t=Buffer.from(String(e),"base64");return u()?n.decryptString(t):t.toString("utf8")}catch{return null}}function d(){try{return JSON.parse(fs.readFileSync(o,"utf8"))||{}}catch{return{}}}function f(e){fs.mkdirSync(path.dirname(o),{recursive:!0});const n=`${o}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(e,null,2),{mode:384}),fs.renameSync(n,o),restrictFile(o)}function A(e){if(isReservedNamespace(e))throw new Error(`reserved namespace "${e}" is not a provider config — use setAegisKey()/aegisRawKey() for the AEGIS key`)}function E(e){const n=d()[e]||{},t=l(n.key);return{provider:e,baseURL:n.baseURL||"",configured:Boolean(t),keyMask:maskKey(t)}}function S(){const e=l((d().__aegis||{}).key);return{configured:Boolean(e),keyMask:maskKey(e)}}function m(){const e=d().__quickLauncher||{},n="string"==typeof e.shortcut&&e.shortcut.trim()?e.shortcut.trim():"CmdOrCtrl+Shift+Space";return{enabled:Boolean(e.enabled),shortcut:n}}function M(){const e=d().__vaultBackend||{};return{backend:VAULT_BACKEND_VALUES.includes(e.backend)?e.backend:"aegiscloud"}}function p(){const e=a();if("boolean"==typeof e.confirmMode)return{enabled:e.confirmMode,source:"config"};const n=d().__confirmMode||{};return void 0===n.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(n.enabled),source:"config"}}function y(){const e=a().sandboxPolicy;return e&&"object"==typeof e?e:null}function g(){const e=a();return"string"==typeof e.permissionMode?e.permissionMode:null}function N(){return!0===(d().__telemetry||{}).enabled}function b(){const e=a();if("boolean"==typeof e.memoryPersist)return{enabled:e.memoryPersist,source:"config"};const n=d().__memoryPersist||{};return void 0===n.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(n.enabled),source:"config"}}function v(){const e=d().__avatar||{};return{enabled:void 0===e.enabled||Boolean(e.enabled),showLevel:void 0===e.showLevel||Boolean(e.showLevel),motion:AVATAR_MOTION_MODES.includes(e.motion)?e.motion:"system"}}function R(){const e=d().__avatar||{};return{...v(),source:void 0===e.enabled?"default":"config"}}function T(e){const n=Number(e);if(!Number.isFinite(n))return 6e4;const t=Math.round(n);return t<15e3||t>18e5?6e4:t}function h(){const e=d().__autoDrain||{};return{enabled:!1!==e.enabled,intervalMs:T(e.intervalMs)}}function C(){const e=d().__autoDrain||{};return{...h(),source:void 0===e.enabled?"default":"config"}}function I(){const e=d().__autoMint||{};return{enabled:!1!==e.enabled,publish:!0===e.publish}}function L(){const e=d().__autoMint||{};return{...I(),source:void 0===e.enabled?"default":"config"}}return{file:o,sharedDir:i,adoption:s,sharedFile:function(){return prefs.prefsFile({dir:i})},getSharedPref:c,setSharedPref:function(e,n){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);return prefs.set({[e]:n},{dir:i}),c(e)},get:E,set:function(e,{baseURL:n,key:t}={}){A(e);let r=n;if("local"===e&&n){const e=localTransport.remoteRefusal(n);if(e)throw e;r=localTransport.normalizeBase(n)}const o=d(),i=o[e]||{};return void 0!==r&&(i.baseURL=r),void 0!==t&&(i.key=t?_(t):null),o[e]=i,f(o),E(e)},rawKey:function(e){return l((d()[e]||{}).key)},remove:function(e){A(e);const n=d();return delete n[e],f(n),{ok:!0}},list:function(){const e=d();return Object.keys(e).filter((e=>!isReservedNamespace(e))).map((e=>E(e)))},maskKey:maskKey,aegisKey:S,aegisRawKey:function(){return l((d().__aegis||{}).key)},aegisKeySavedAt:function(){return(d().__aegis||{}).savedAt||null},setAegisKey:function(e){const n=d();return n.__aegis={...n.__aegis||{},key:e?_(e):null,savedAt:e?(new Date).toISOString():null},f(n),S()},migrateLegacyAegisKey:function(){try{const e=d();if(!e.aegis)return{migrated:!1};const n=e.aegis||{},t=e.__aegis||{},r={...e};return n.key&&!t.key&&(r.__aegis={...t,key:n.key}),delete r.aegis,f(r),{migrated:!0}}catch{return{migrated:!1}}},quickLauncherConfig:m,setQuickLauncherConfig:function({enabled:e,shortcut:n}={}){const t=d();return t.__quickLauncher={enabled:Boolean(e),shortcut:"string"==typeof n&&n.trim()?n.trim():"CmdOrCtrl+Shift+Space"},f(t),m()},vaultBackendConfig:M,setVaultBackendConfig:function(e){if(!VAULT_BACKEND_VALUES.includes(e))return M();const n=d();return n.__vaultBackend={backend:e},f(n),M()},getConfirmMode:function(){return p().enabled},setConfirmMode:function(e){prefs.set({confirmMode:Boolean(e)},{dir:i});const n=d();return void 0!==n.__confirmMode&&(delete n.__confirmMode,f(n)),p().enabled},confirmModeState:p,getPermissionMode:g,setPermissionMode:function(e){if(null==e||""===e||"off"===e||"none"===e)return prefs.remove("permissionMode",{dir:i}),null;const n=String(e),t=function(){const e=[path.join(__dirname,"..","..","one","src","permissions.js"),path.join(__dirname,"..","vendor","one","src","permissions.js")];for(const n of e)try{const e=require(n);if(e&&Array.isArray(e.PERMISSION_MODES)&&e.PERMISSION_MODES.length)return[...e.PERMISSION_MODES]}catch{}return["acceptEdits","auto","bypassPermissions","manual","dontAsk","plan"]}();if(!t.includes(n))throw new Error(`"${n}" is not one of ${t.join("|")} (or 'off' to clear it)`);return prefs.set({permissionMode:n},{dir:i}),g()},getSandboxPolicy:y,setSandboxPolicy:function(e){return e&&"object"==typeof e?(prefs.set({sandboxPolicy:e},{dir:i}),y()):(prefs.set({sandboxPolicy:null},{dir:i}),null)},getTelemetryOptIn:N,setTelemetryOptIn:function(e){const n=d();return n.__telemetry={enabled:Boolean(e)},f(n),N()},getMemoryPersist:function(){return b().enabled},memoryPersistState:b,setMemoryPersist:function(e){prefs.set({memoryPersist:Boolean(e)},{dir:i});const n=d();return void 0!==n.__memoryPersist&&(delete n.__memoryPersist,f(n)),b()},getAvatar:v,avatarState:R,setAvatar:function(e={}){const n=v(),t=e&&"object"==typeof e?e:{},r={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),showLevel:void 0===t.showLevel?n.showLevel:Boolean(t.showLevel),motion:AVATAR_MOTION_MODES.includes(t.motion)?t.motion:n.motion},o=d();return o.__avatar=r,f(o),R()},getAutoDrain:h,autoDrainState:C,setAutoDrain:function(e={}){const n=h(),t=e&&"object"==typeof e?e:{},r=d();return r.__autoDrain={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),intervalMs:void 0===t.intervalMs?n.intervalMs:T(t.intervalMs)},f(r),C()},getAutoMint:I,autoMintState:L,setAutoMint:function(e={}){const n=I(),t=e&&"object"==typeof e?e:{},r=d();return r.__autoMint={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),publish:void 0===t.publish?n.publish:Boolean(t.publish)},f(r),L()},clampAutoDrainInterval:T}}module.exports={SETTINGS_FILE:SETTINGS_FILE,AEGIS_KEY_NAMESPACE:"__aegis",LEGACY_AEGIS_NAMESPACE:"aegis",QUICK_LAUNCHER_NAMESPACE:"__quickLauncher",VAULT_BACKEND_NAMESPACE:"__vaultBackend",CONFIRM_MODE_NAMESPACE:"__confirmMode",MEMORY_PERSIST_NAMESPACE:"__memoryPersist",AVATAR_NAMESPACE:"__avatar",TELEMETRY_NAMESPACE:"__telemetry",AUTO_DRAIN_NAMESPACE:"__autoDrain",AUTO_MINT_NAMESPACE:"__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS:6e4,AUTO_DRAIN_INTERVAL_MIN_MS:15e3,AUTO_DRAIN_INTERVAL_MAX_MS:18e5,AVATAR_MOTION_MODES:AVATAR_MOTION_MODES,DEFAULT_QUICK_LAUNCHER_SHORTCUT:"CmdOrCtrl+Shift+Space",DEFAULT_VAULT_BACKEND:"aegiscloud",VAULT_BACKEND_VALUES:VAULT_BACKEND_VALUES,RESERVED_NAMESPACES:RESERVED_NAMESPACES,isReservedNamespace:isReservedNamespace,maskKey:maskKey,createSettingsStore:createSettingsStore};