aegisone 1.0.55 → 1.0.57
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.
- package/README.md +1 -1
- package/package.json +2 -1
- package/scripts/postinstall.mjs +4 -0
- package/scripts/predist.mjs +1 -1
- package/vendor/cli/package.json +2 -1
- package/vendor/cli/scripts/postinstall.mjs +4 -0
- package/vendor/cli/vendor/client/install-register.js +3 -0
- package/vendor/cli/vendor/client/prefs.js +1 -1
- package/vendor/cli/vendor/client/session-store.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/cli/vendor/desktop/lib/settings.js +1 -1
- package/vendor/cli/vendor/desktop/main.js +83 -24
- package/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/lib/settings.js +1 -1
- package/vendor/desktop/main.js +83 -24
- package/vendor/desktop/package.json +1 -1
- package/vendor/desktop/preload.js +1 -1
- package/vendor/desktop/renderer/app.js +3 -3
- package/vendor/desktop/renderer/index.html +18 -0
- package/vendor/desktop/vendor/faces/cli/package.json +2 -1
- package/vendor/desktop/vendor/faces/cli/scripts/postinstall.mjs +4 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/install-register.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/session-store.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +3 -3
- package/vendor/desktop/vendor/install-register.js +3 -0
- package/vendor/desktop/vendor/prefs.js +1 -1
- package/vendor/desktop/vendor/session-store.js +1 -1
package/README.md
CHANGED
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aegisone",
|
|
3
3
|
"productName": "AEGISONE",
|
|
4
|
-
"version": "1.0.
|
|
4
|
+
"version": "1.0.57",
|
|
5
5
|
"description": "AEGISONE — one product, two faces. `aegis` opens the window when there is nothing else to do and runs the terminal otherwise; `aegiscode` keeps behaving exactly as it always has.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "AEGIS Code",
|
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
"node": ">=22.0.0"
|
|
29
29
|
},
|
|
30
30
|
"scripts": {
|
|
31
|
+
"postinstall": "node scripts/postinstall.mjs",
|
|
31
32
|
"bump": "node scripts/bump.mjs",
|
|
32
33
|
"compat": "node test/one-compat.test.mjs",
|
|
33
34
|
"size": "node scripts/bundle.mjs --json"
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
4
|
+
import{existsSync as t}from"node:fs";import{createRequire as n}from"node:module";import{dirname as r,join as o}from"node:path";import{fileURLToPath as i}from"node:url";const e=r(i(import.meta.url));(async function(){const r=function(){const n=[o(e,"..","vendor","cli","vendor","client","install-register.js"),o(e,"..","vendor","client","install-register.js"),o(e,"..","..","client","install-register.js")];for(const r of n)if(t(r))return r;return null}();if(!r)return;const i=n(import.meta.url)(r);await i.runPostinstall({app:"npm-postinstall"})})().catch((()=>{}));
|
package/scripts/predist.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
3
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
4
|
-
import e from"node:fs";import s from"node:path";import{spawnSync as r}from"node:child_process";import{fileURLToPath as t,pathToFileURL as o}from"node:url";import{createRequire as n}from"node:module";const i=s.dirname(t(import.meta.url)),a=n(import.meta.url);export const ONE_DIR=s.join(i,"..");export const REPO_DIR=s.join(ONE_DIR,"..");export const CLI_DIR=s.join(REPO_DIR,"cli");export const DESKTOP_DIR=s.join(REPO_DIR,"desktop");export const CLI_VENDOR=s.join(CLI_DIR,"vendor");export const DESKTOP_VENDOR=s.join(DESKTOP_DIR,"vendor");export const ONE_VENDOR=s.join(ONE_DIR,"vendor");export const MANIFEST=[{src:"client/aegis.js",shapes:["mirror","flat"],note:"the thin transport — the one implementation of the wire format"},{src:"client/update.js",shapes:["mirror","flat"],note:"the npm update checker (the desktop own update path)"},{src:"client/foreign-memory.js",shapes:["mirror","flat"],note:"required by mcp/tools.js as ../client/foreign-memory.js"},{src:"client/foreign-sessions.js",shapes:["mirror","flat"],note:"required by desktop/main.js as ./vendor/foreign-sessions.js"},{src:"client/credentials.js",shapes:["mirror","flat"],note:"the account credential store, shared by all three hosts"},{src:"client/session-store.js",shapes:["mirror","flat"],note:"the unified session store — one list in every host"},{src:"client/session-search.js",shapes:["mirror","flat"],note:"the SESSION search ranking: the desktop sheet (Cmd/Ctrl+K) and the terminal /resume picker filter with this one module, pure and fs-free"},{src:"client/credits.js",shapes:["mirror","flat"],note:"the licence/attribution payload: parses LICENSING.md and the two NOTICE files for Help > Credits & licence and /license + /credits"},{src:"client/naming.js",shapes:["mirror","flat"],note:"the conversation-naming ladder — ONE implementation for the terminal and the window (cli/src/naming.js re-exports it)"},{src:"client/prefs.js",shapes:["mirror","flat"],note:"the shared non-secret preference store (D5) — the CLI and the desktop store both read/write it"},{src:"client/env-file.js",shapes:["mirror","flat"],note:"the shared ~/.aegiscode/.env loader, resolved before any key is read"},{src:"client/auto-provision.js",shapes:["mirror","flat"],note:"free device key on first launch; requires ./device-fingerprint.js"},{src:"client/device-fingerprint.js",shapes:["mirror","flat"],note:"the machine identity auto-provision.js and presence.js require"},{src:"client/presence.js",shapes:["mirror","flat"],note:"the heartbeat beacon; requires ./presence-constants.js and ./device-fingerprint.js"},{src:"client/presence-constants.js",shapes:["mirror","flat"],note:"the beacon constants — a package without them loses the beacon silently"},{src:"client/touch.js",shapes:["mirror","flat"],note:"phi(alpha): the digest module fingerprint.js requires as ./touch.js"},{src:"client/fingerprint.js",shapes:["mirror","flat"],note:"phi(alpha): the sealed session record, resolved by src/fingerprint.js"},{src:"client/authorship-key.js",shapes:["mirror","flat"],note:"phi(alpha): the authorship key, required by ./attest.js and ./record-vault.js"},{src:"client/attest.js",shapes:["mirror","flat"],note:"phi(alpha): attestation, requires ./fingerprint.js and ./authorship-key.js"},{src:"client/record-vault.js",shapes:["mirror","flat"],note:"the vault, and its refusal to copy the key with the record"},{src:"client/brain-catalog.js",shapes:["mirror","flat"],note:"the pooled-brain rule, required at load time by the engine and src/models.js"},{src:"client/byok-catalog.js",shapes:["mirror","flat"],note:"the BYOK model additions the server catalog does not name"},{src:"client/catalog-client.js",shapes:["mirror","flat"],note:"the server's cached catalog, layered between the shipped additions and the user's own models"},{src:"client/user-models.js",shapes:["mirror","flat"],note:"the models the USER declares, in one file both hosts read (requires ./credentials.js)"},{src:"client/model-discovery.js",shapes:["mirror","flat"],note:"asks the vendor what it serves, so adding a new model is not a memory test (requires ./user-models.js)"},{src:"client/hooks.js",shapes:["mirror","flat"],note:"the shared hook layer behind /hooks and the repo guard installer"},{src:"client/platform.js",shapes:["mirror","flat"],note:"the ONE place that decides which OS this is (Phase 30.1)"},{src:"client/topup.js",shapes:["mirror","flat"],note:"the token-bank top-up: amount bounds, the balance reading, and the credit watch every host drives"},{src:"client/google-signin.js",shapes:["mirror","flat"],note:"the localhost half of aegis1's desktop Google OAuth round-trip; `connect --google` drives it"},{src:"client/drive-connect.js",shapes:["mirror","flat"],note:"the desktop half of aegis1's Drive OAuth (/connect/drive, /api/drive/token); requires ./aegis.js only via the caller"},{src:"client/drive-upload.js",shapes:["mirror","flat"],note:"the Drive v3 REST wrapper that uploads the memory backup and one conversation per save"},{src:"client/conversation-export.js",shapes:["mirror","flat"],note:"the authorship stamp at the top of every uploaded file, and the two backup scope names"},{src:"mcp/tools.js",shapes:["mirror"],note:"the shared tool registry; requires ../client/foreign-memory.js"},{src:"mcp/server.js",shapes:["mirror"],note:"the stdio MCP server every installed editor config names (compiled, never required)"},{src:"mcp/admission.js",shapes:["mirror"],note:"the admission gate server.js requires at load (`./admission.js`): which harness may call the bridge, and what it may run — omitted from the manifest when 2066f82 added it, so both staged trees shipped a server that could not load"},{src:"hosts/spec.js",shapes:["mirror"],note:"the canonical server spec, staged under its own directory so it finds vendor/mcp/server.js"},{src:"hosts/targets.js",shapes:["mirror"],note:"the editor target registry"},{src:"hosts/install.js",shapes:["mirror"],note:"the merge-only installer behind aegiscode mcp install"},{src:"hosts/openai-shim.js",shapes:["mirror"],note:"the loopback OpenAI-compatible shim"},{src:"desktop/renderer/usage.js",shapes:["mirror"],note:"the pure usage mapping shared by the window and the terminal"},{src:"desktop/lib/local/engine.js",shapes:["mirror"],note:"the agent loop, reused as-is (one loop, not a second one drifting)"},{src:"desktop/lib/local/claude-pro.js",shapes:["mirror"],note:"the Claude Code Pro transport; requires ./../../one/src/child.js at call time"},{src:"one/src/child.js",shapes:["mirror"],note:"the ONE claude-child argv builder (rule 4); resolved by claude-pro.js at call time"},{src:"one/src/permissions.js",shapes:["mirror"],note:"resolvePosture() — the permission half of the argv, resolved at call time"},{src:"desktop/lib/local/local.js",shapes:["mirror"],note:"the local model transport and its fail-closed base-URL check"},{src:"desktop/lib/local/context.js",shapes:["mirror"],note:"the token-budget trimmer local.js requires at load"},{src:"desktop/lib/local/attachments.js",shapes:["mirror"],note:"content-part builder for dropped files; required at load by engine.js and local.js"},{src:"desktop/lib/local/session-rounds.js",shapes:["mirror"],note:"interrupted-turn bookkeeping; required at load by engine.js"},{src:"desktop/lib/local/pro-sessions.js",shapes:["mirror"],note:"durable Claude-Pro conversation session ids; required at load by engine.js"},{src:"desktop/lib/local/tools.js",shapes:["mirror"],note:"the tool implementations (persistent shell, editFile, grep, exec)"},{src:"desktop/lib/local/shell.js",shapes:["mirror"],note:"the persistent shell, required by tools.js"},{src:"desktop/lib/local/sandbox.js",shapes:["mirror"],note:"the outcome bound (agent-safety-plan §1b), required by shell.js + tools.js"},{src:"desktop/lib/local/sandbox-bwrap.js",shapes:["mirror"],note:"bubblewrap mechanism behind sandbox.js (agent-safety-plan §1d)"},{src:"desktop/lib/local/sandbox-seatbelt.js",shapes:["mirror"],note:"Seatbelt mechanism behind sandbox.js (agent-safety-plan §1d)"},{src:"desktop/lib/local/sandbox-appcontainer.js",shapes:["mirror"],note:"AppContainer mechanism behind sandbox.js (agent-safety-plan §1e)"},{src:"desktop/lib/local/perm-rules.js",shapes:["mirror"],note:"stored /permissions rules for the desktop gate (agent-safety-plan §2), required by engine.js"},{src:"desktop/lib/local/perm-write.js",shapes:["mirror"],note:'the durable "always allow this command" answer (agent-safety-plan §3), required by main.js'},{src:"desktop/lib/local/perm-store.js",shapes:["mirror"],note:"the Settings rules editor (agent-safety-plan §4), required by main.js"},{src:"desktop/lib/local/integrity.js",shapes:["mirror"],note:"the desktop second gate; required at load by shell.js and tools.js, and the seal over its own four units"},{src:"desktop/main.js",shapes:["mirror"],bytesOnly:!0,note:"seal unit d1 — hashed by integrity.js as BYTES and never required from the mirror, so its own requires (the whole Electron main-process closure) are not staged behind it"},{src:"desktop/lib/local/spill.js",shapes:["mirror"],note:"oversized-output spill, required at load by tools.js and shell.js"},{src:"desktop/lib/local/exec-plan.js",shapes:["mirror"],note:"exec one-shot eligibility classifier, required at load by engine.js"},{src:"desktop/lib/local/agents.js",shapes:["mirror"],note:"Task subagents"},{src:"desktop/lib/local/prompt.js",shapes:["mirror"],note:"the system prompt builder"},{src:"desktop/lib/settings.js",shapes:["mirror"],note:"the provider-config store (base URL + key per provider)"},{src:"desktop/lib/local/turn-guard.js",shapes:["mirror"],note:"engine.js requires it at load; it requires ./git-scope.js"},{src:"desktop/lib/local/repeat-guard.js",shapes:["mirror"],note:"engine.js requires it at load — identical-call detection, no deps of its own"},{src:"desktop/lib/local/verify-stop.js",shapes:["mirror"],note:"engine.js requires it at load — edited-but-unchecked nudge, no deps of its own"},{src:"desktop/lib/local/check-command.js",shapes:["mirror"],note:"verify-stop.js requires it lazily — which command would check this repo; no deps"},{src:"desktop/lib/local/worktree-lock.js",shapes:["mirror"],note:"engine.js requires it at load"},{src:"desktop/lib/local/git-scope.js",shapes:["mirror"],note:"the write-scope rule turn-guard.js and the queues share"},{src:"desktop/lib/local/queue.js",shapes:["mirror"],note:"the autonomous work queue"},{src:"desktop/lib/local/autonomous.js",shapes:["mirror"],note:"the unattended worker; requires ./queue.js and ./git-scope.js"},{src:"desktop/lib/local/entitlement.js",shapes:["mirror"],note:"the shared Pro gate (account probe injected by the caller)"},{src:"desktop/lib/local/covenant.js",shapes:["mirror"],note:"the pre-action gate engine.js requires unconditionally at load"},{src:"desktop/lib/local/aegis-seal.mjs",shapes:["mirror"],note:"the codec covenant.js requires the first time it decodes"},{src:"covenant/aegis.seal",shapes:["mirror","nested"],note:"the sealed covenant (AES/1 container) — path shape is load-bearing"},{src:"covenant/README.md",shapes:["mirror","nested"],note:"the decode notice shipped beside the artifact"},{src:"tools/agent-gate.mjs",shapes:["mirror","flat"],note:"the in-process half of the lock; without it a packaged app had NO gate"},{src:"one/src/selfhost.js",shapes:["mirror","flat"],note:"the packaged launcher decision — which face this artifact was asked for"}];export function entriesFor(e){const r=[];for(const t of MANIFEST){if(!t.shapes.includes(e))continue;let o;if("mirror"===e)o=s.join(CLI_VENDOR,t.src);else if("flat"===e)o=s.join(DESKTOP_VENDOR,s.basename(t.src));else{if("nested"!==e)throw new Error(`predist: unknown shape ${e}`);o=s.join(DESKTOP_VENDOR,t.src)}r.push({src:t.src,dest:o,from:s.join(REPO_DIR,t.src)})}return r}export const SHAPES=["mirror","flat","nested"];const c=[["cli",CLI_DIR,["bin","src","vendor","scripts","package.json","README.md","LICENSE"]],["desktop",DESKTOP_DIR,["main.js","preload.js","lib","renderer","bin","vendor","package.json","README.md"]]],l=new Set(["node_modules","release",".git",".cache","out"]),d=new Map([["desktop/vendor",new Set(["faces","sandbox"])]]);function p(r,t,o){const n=o||new Set,i=(e,s)=>l.has(e)||e.endsWith(".log")||n.has(s),a=(r,t)=>{if(e.mkdirSync(s.dirname(t),{recursive:!0}),e.copyFileSync(r,t),!e.readFileSync(r).equals(e.readFileSync(t)))throw new Error(`predist: bundle copy differs from source: ${s.relative(REPO_DIR,r)}`)},c=(r,o)=>{const n=e.lstatSync(r);if(!n.isSymbolicLink())if(n.isFile())a(r,s.join(t,o));else for(const t of e.readdirSync(r)){const e=o?s.join(o,t):t;i(t,e)||c(s.join(r,t),e)}};e.lstatSync(r).isFile()?a(r,t):c(r,"")}const h=12e4,u=6e5,m=50,f="AEGISONE_PREDIST_LOCK_TOKEN";let g=null,j=!1,y=0;function b(e){try{return process.kill(e,0),!0}catch(e){return Boolean(e)&&"EPERM"===e.code}}const w=e=>new Promise((s=>setTimeout(s,e)));function v(){if(y>0)return void y--;const s=g,r=j,t=process.env[f];if(g=null,j=!1,s&&r){t&&delete process.env[f];try{e.unlinkSync(s)}catch{}}}export async function acquireStageLock(r){if(g)return y++,v;const t=r&&r.stdout||process.stdout;return await async function(r){const t=function(){const r=s.join(REPO_DIR,".git");let t=r;try{if(!e.lstatSync(r).isDirectory()){const o=/^gitdir:\s*(.+)$/m.exec(e.readFileSync(r,"utf8"));o&&(t=s.resolve(REPO_DIR,o[1].trim()))}}catch{t=r}return s.join(t,"aegisone-predist.lock")}(),o=Date.now()+h,n=process.env[f]||null;let i=null,a=!1;for(;;){if(n)try{const s=String(e.readFileSync(t,"utf8")).split("\n")[1];if(s&&s.trim()===n)return g=t,void(j=!1)}catch{}try{i=`${Date.now().toString(36)}-${process.pid}-${Math.random().toString(36).slice(2,10)}`;const s=e.openSync(t,"wx");return e.writeSync(s,`${process.pid}\n${i}\n`),e.closeSync(s),g=t,j=!0,void(process.env[f]=i)}catch(e){if(!e||"EEXIST"!==e.code)throw e}let s=null,c=0;try{s=e.statSync(t),c=Number(String(e.readFileSync(t,"utf8")).split("\n")[0].trim())}catch{continue}if(Date.now()-s.mtimeMs>u||Number.isFinite(c)&&c>0&&!b(c)){r(`predist: breaking an abandoned staging lock (pid ${c||"unknown"})`);try{e.unlinkSync(t)}catch{}}else{if(Date.now()>o)throw new Error(`predist: another stager (pid ${c||"unknown"}) has held ${t} for over ${Math.round(h/1e3)}s. Staging is destructive — it removes and rewrites cli/vendor, desktop/vendor and one/vendor — so it will not run concurrently with a peer. Wait for it, or delete the lock if that process is gone.`);a||(a=!0,r(`predist: another stager (pid ${c||"unknown"}) is running — waiting for it (concurrent staging would read a vendor tree the peer is rewriting)`)),await w(m+Math.floor(Math.random()*m))}}}((e=>t.write(`${e}\n`))),v}function E(r,t){t&&e.rmSync(t,{recursive:!0,force:!0});const o=[];for(const t of r){if(!e.existsSync(t.from))throw new Error(`predist: missing shared module: ${t.src} (expected at ${t.from})`);if(e.mkdirSync(s.dirname(t.dest),{recursive:!0}),e.copyFileSync(t.from,t.dest),!e.readFileSync(t.from).equals(e.readFileSync(t.dest)))throw new Error(`predist: staged copy differs from source: ${t.src}`);o.push(t)}return o}export async function stage(t){const n=t||{},i=n.io||{},l=i.stdout||process.stdout,h=(i.stderr||process.stderr,Array.isArray(n.shapes)?n.shapes:[...SHAPES,"bundle"]),u=e=>h.includes(e),m=e=>l.write(`${e}\n`),f=await acquireStageLock(i);try{return await async function({want:t,log:n}){const i={mirror:null,flat:null,nested:null,bundle:null};if(t("mirror")){const e=E(entriesFor("mirror"),CLI_VENDOR);n(`predist: staged ${e.length} shared modules into cli/vendor/`);for(const s of e)n(` ${s.src} -> vendor/${s.src}`);i.mirror={staged:e.length}}if(t("nested")&&(i.nested={staged:E(entriesFor("nested"),null).length}),t("flat")){const e=E(entriesFor("flat"),null);for(const s of e)n(`staged ${s.dest}`);i.flat={staged:e.length}}if(t("mirror")&&t("flat"))for(const r of MANIFEST){if(!r.shapes.includes("mirror")||!r.shapes.includes("flat"))continue;const t=s.join(CLI_VENDOR,r.src),o=s.join(DESKTOP_VENDOR,s.basename(r.src));if(!e.readFileSync(t).equals(e.readFileSync(o)))throw new Error(`predist: the two shapes disagree for ${r.src}`)}if(t("mirror")){const r=function(r){const t=s.join(CLI_VENDOR,"mcp","tools.js");delete a.cache[a.resolve(t)];const{createTools:o}=a(t),n=o({apiBase:"http://127.0.0.1",apiKey:"predist-probe",randomUUID:()=>"id"}).toolList().length;if(0===n)throw new Error("predist: staged registry exposes no tools");const i=a("node:vm"),c=s.join(CLI_VENDOR,"mcp","server.js");new i.Script(e.readFileSync(c,"utf8"),{filename:c});const l=s.join(CLI_VENDOR,"hosts"),d=a(s.join(l,"spec.js")),p=a(s.join(l,"install.js")),h=a(s.join(l,"targets.js")),u=d.resolveServer({AEGIS_MCP_SERVER:""});if(!u.exists||u.path!==c)throw new Error(`predist: staged hosts/spec.js resolves the server as ${u.path} (exists: ${u.exists}), expected ${c}. An installed aegiscode would write editor configs pointing at a file the package never shipped. Candidates were:\n ${u.candidates.join("\n ")}`);const m=h.getTarget("vscode"),f=p.planTarget(m,"user",{ctx:p.hostCtx({home:s.join(CLI_VENDOR,".predist-home"),env:{},cwd:REPO_DIR}),specOpts:{env:{AEGIS_MCP_SERVER:""}}}),g=JSON.stringify(f.after||"");if(f.error||!f.changed||!g.includes(JSON.stringify(c).slice(1,-1)))throw new Error(`predist: a planned vscode install does not name the staged server (error: ${f.error&&f.error.message}, changed: ${f.changed})`);if("function"!=typeof a(s.join(l,"openai-shim.js")).createShimServer)throw new Error("predist: staged hosts/openai-shim.js exposes no createShimServer");return{count:n,targets:h.targetIds().length,staged:r.length}}(entriesFor("mirror"));n(`predist: staged registry loads standalone (${r.count} tools)`),n(`predist: editor layer verified (${r.targets} host targets, server resolves to vendor/mcp/server.js, shim loads)`);const t=await async function(){const e=s.join(CLI_VENDOR,"tools","agent-gate.mjs");if("function"!=typeof(await import(o(e).href)).run)throw new Error("predist: staged tools/agent-gate.mjs exposes no run()");return e}();n(`predist: ${s.relative(REPO_DIR,t)} loads standalone and exposes run()`),i.mirror.proof=r}if(t("flat")){const r=function(r){const t=new Set(r.map((e=>s.basename(e.dest))));for(const o of r){const r=e.readFileSync(o.dest,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1");for(const e of r.matchAll(/require\(\s*'((?:\.\.?\/)[^']+)'\s*\)/g)){const r=e[1];if(s.basename(r).replace(/\.[cm]?js$/,""),r.replace(/^\.\//,"").startsWith("../"))throw new Error(`predist: flat-staged ${s.basename(o.dest)} requires '${r}', which escapes vendor/ — flattening only works for same-directory requires (add the target to the manifest, or stop staging this file flat)`);const n=r.replace(/^\.\//,"");if(!t.has(n))throw new Error(`predist: flat-staged ${s.basename(o.dest)} requires '${r}', which is not staged into desktop/vendor/ — the packaged app would throw MODULE_NOT_FOUND before the window could open`)}}const o=a(s.join(DESKTOP_VENDOR,"aegis.js"));if(!o||0===Object.keys(o).length)throw new Error("predist: staged desktop/vendor/aegis.js loads but exports nothing");return{files:r.length,exports:Object.keys(o).length}}(entriesFor("flat"));n(`predist: flattened tree is self-contained (${r.files} files, ${r.exports} transport exports) — no staged module escapes vendor/`),i.flat.proof=r}if(t("bundle")){for(const[r,t,o]of c){const i=s.join(ONE_VENDOR,r);e.rmSync(i,{recursive:!0,force:!0});for(const n of o){const o=s.join(t,n);if(!e.existsSync(o)){if("LICENSE"===n||"README.md"===n)continue;throw new Error(`predist: bundle source missing: ${s.relative(REPO_DIR,o)}`)}p(o,s.join(i,n),d.get(`${r}/${n}`))}n(`staged the ${r} face into one/vendor/${r}/`)}const t=function(){const t=s.join(ONE_VENDOR,"cli"),o=s.join(t,"src","deps.js"),n=r(process.execPath,["-e","const d=require(process.argv[1]);console.log(JSON.stringify(d.paths))",o],{cwd:t,encoding:"utf8"});if(0!==n.status)throw new Error(`predist: the bundled CLI does not load: ${n.stderr||n.stdout}`);const i=JSON.parse(n.stdout),a=[];let l=0;for(const[e,r]of Object.entries(i)){const t=s.relative(ONE_VENDOR,r);t.startsWith("..")||s.isAbsolute(t)?a.push(`${e} -> ${r}`):"cli"!==t.split(s.sep)[0]&&l++}if(a.length)throw new Error(`predist: the bundled CLI resolves these shared modules OUTSIDE the bundle (${ONE_VENDOR}) — the product tarball would depend on a repo checkout:\n `+a.join("\n "));if(!e.existsSync(s.join(t,"bin","aegiscode.js")))throw new Error("predist: the bundle has no cli/bin/aegiscode.js");const d=[];for(const[r,t,o]of c)for(const n of o){const o=s.join(ONE_VENDOR,r,n);let i=null,a=null;try{i=e.lstatSync(s.join(t,n))}catch{continue}try{a=e.lstatSync(o)}catch{d.push(`${r}/${n} -> missing`);continue}i.isFile()&&!a.isFile()&&d.push(`${r}/${n} -> not a regular file`),i.isDirectory()&&!a.isDirectory()&&d.push(`${r}/${n} -> not a directory`)}if(d.length)throw new Error(`predist: the bundle staged these in the wrong shape:\n ${d.join("\n ")}`);return{modules:Object.keys(i).length,inSiblingFace:l}}();n(`predist: the bundled CLI resolves ${t.modules} shared modules from inside one/vendor/ (${t.inSiblingFace} through the bundled desktop face) — no repo checkout needed`),i.bundle=t;const o=s.join(DESKTOP_VENDOR,"faces");e.rmSync(o,{recursive:!0,force:!0}),p(s.join(ONE_VENDOR,"cli"),s.join(o,"cli"));const a=s.join(o,"cli","bin","aegiscode.js");if(!e.existsSync(a))throw new Error(`predist: the packaged terminal face has no entry point at ${s.relative(REPO_DIR,a)} — the artifact would open a window for every \`aegiscode\`/\`--tui\` invocation`);n(`staged the terminal face into desktop/vendor/faces/cli/ (${s.basename(a)})`),i.faces={entry:s.relative(REPO_DIR,a)}}return i}({want:u,log:m})}finally{f()}}export async function main(e,s){const r=s||{},t=Array.isArray(e)?e:[],o=t.includes("--quiet")?{write:()=>!0}:r.stdout||process.stdout,n=r.stderr||process.stderr;let i;t.includes("--mirror-only")?i=["mirror"]:t.includes("--flat-only")?i=["flat","nested"]:t.includes("--bundle-only")&&(i=["bundle"]);try{return await stage({shapes:i,io:{stdout:o,stderr:n}}),0}catch(e){return n.write(`${e&&e.message}\n`),1}}!function(){const e=process.argv[1];let r=!1;if(e)try{r=s.resolve(e)===t(import.meta.url)}catch{r=!1}r&&main(process.argv.slice(2)).then((e=>{process.exitCode=e}))}();
|
|
4
|
+
import e from"node:fs";import s from"node:path";import{spawnSync as r}from"node:child_process";import{fileURLToPath as t,pathToFileURL as o}from"node:url";import{createRequire as n}from"node:module";const i=s.dirname(t(import.meta.url)),a=n(import.meta.url);export const ONE_DIR=s.join(i,"..");export const REPO_DIR=s.join(ONE_DIR,"..");export const CLI_DIR=s.join(REPO_DIR,"cli");export const DESKTOP_DIR=s.join(REPO_DIR,"desktop");export const CLI_VENDOR=s.join(CLI_DIR,"vendor");export const DESKTOP_VENDOR=s.join(DESKTOP_DIR,"vendor");export const ONE_VENDOR=s.join(ONE_DIR,"vendor");export const MANIFEST=[{src:"client/aegis.js",shapes:["mirror","flat"],note:"the thin transport — the one implementation of the wire format"},{src:"client/update.js",shapes:["mirror","flat"],note:"the npm update checker (the desktop own update path)"},{src:"client/foreign-memory.js",shapes:["mirror","flat"],note:"required by mcp/tools.js as ../client/foreign-memory.js"},{src:"client/foreign-sessions.js",shapes:["mirror","flat"],note:"required by desktop/main.js as ./vendor/foreign-sessions.js"},{src:"client/credentials.js",shapes:["mirror","flat"],note:"the account credential store, shared by all three hosts"},{src:"client/session-store.js",shapes:["mirror","flat"],note:"the unified session store — one list in every host"},{src:"client/session-search.js",shapes:["mirror","flat"],note:"the SESSION search ranking: the desktop sheet (Cmd/Ctrl+K) and the terminal /resume picker filter with this one module, pure and fs-free"},{src:"client/credits.js",shapes:["mirror","flat"],note:"the licence/attribution payload: parses LICENSING.md and the two NOTICE files for Help > Credits & licence and /license + /credits"},{src:"client/naming.js",shapes:["mirror","flat"],note:"the conversation-naming ladder — ONE implementation for the terminal and the window (cli/src/naming.js re-exports it)"},{src:"client/prefs.js",shapes:["mirror","flat"],note:"the shared non-secret preference store (D5) — the CLI and the desktop store both read/write it"},{src:"client/env-file.js",shapes:["mirror","flat"],note:"the shared ~/.aegiscode/.env loader, resolved before any key is read"},{src:"client/auto-provision.js",shapes:["mirror","flat"],note:"free device key on first launch; requires ./device-fingerprint.js"},{src:"client/device-fingerprint.js",shapes:["mirror","flat"],note:"the machine identity auto-provision.js and presence.js require"},{src:"client/install-register.js",shapes:["mirror","flat"],note:"register-at-install; the shared body behind both postinstall hooks"},{src:"client/presence.js",shapes:["mirror","flat"],note:"the heartbeat beacon; requires ./presence-constants.js and ./device-fingerprint.js"},{src:"client/presence-constants.js",shapes:["mirror","flat"],note:"the beacon constants — a package without them loses the beacon silently"},{src:"client/touch.js",shapes:["mirror","flat"],note:"phi(alpha): the digest module fingerprint.js requires as ./touch.js"},{src:"client/fingerprint.js",shapes:["mirror","flat"],note:"phi(alpha): the sealed session record, resolved by src/fingerprint.js"},{src:"client/authorship-key.js",shapes:["mirror","flat"],note:"phi(alpha): the authorship key, required by ./attest.js and ./record-vault.js"},{src:"client/attest.js",shapes:["mirror","flat"],note:"phi(alpha): attestation, requires ./fingerprint.js and ./authorship-key.js"},{src:"client/record-vault.js",shapes:["mirror","flat"],note:"the vault, and its refusal to copy the key with the record"},{src:"client/brain-catalog.js",shapes:["mirror","flat"],note:"the pooled-brain rule, required at load time by the engine and src/models.js"},{src:"client/byok-catalog.js",shapes:["mirror","flat"],note:"the BYOK model additions the server catalog does not name"},{src:"client/catalog-client.js",shapes:["mirror","flat"],note:"the server's cached catalog, layered between the shipped additions and the user's own models"},{src:"client/user-models.js",shapes:["mirror","flat"],note:"the models the USER declares, in one file both hosts read (requires ./credentials.js)"},{src:"client/model-discovery.js",shapes:["mirror","flat"],note:"asks the vendor what it serves, so adding a new model is not a memory test (requires ./user-models.js)"},{src:"client/hooks.js",shapes:["mirror","flat"],note:"the shared hook layer behind /hooks and the repo guard installer"},{src:"client/platform.js",shapes:["mirror","flat"],note:"the ONE place that decides which OS this is (Phase 30.1)"},{src:"client/topup.js",shapes:["mirror","flat"],note:"the token-bank top-up: amount bounds, the balance reading, and the credit watch every host drives"},{src:"client/google-signin.js",shapes:["mirror","flat"],note:"the localhost half of aegis1's desktop Google OAuth round-trip; `connect --google` drives it"},{src:"client/drive-connect.js",shapes:["mirror","flat"],note:"the desktop half of aegis1's Drive OAuth (/connect/drive, /api/drive/token); requires ./aegis.js only via the caller"},{src:"client/drive-upload.js",shapes:["mirror","flat"],note:"the Drive v3 REST wrapper that uploads the memory backup and one conversation per save"},{src:"client/conversation-export.js",shapes:["mirror","flat"],note:"the authorship stamp at the top of every uploaded file, and the two backup scope names"},{src:"mcp/tools.js",shapes:["mirror"],note:"the shared tool registry; requires ../client/foreign-memory.js"},{src:"mcp/server.js",shapes:["mirror"],note:"the stdio MCP server every installed editor config names (compiled, never required)"},{src:"mcp/admission.js",shapes:["mirror"],note:"the admission gate server.js requires at load (`./admission.js`): which harness may call the bridge, and what it may run — omitted from the manifest when 2066f82 added it, so both staged trees shipped a server that could not load"},{src:"hosts/spec.js",shapes:["mirror"],note:"the canonical server spec, staged under its own directory so it finds vendor/mcp/server.js"},{src:"hosts/targets.js",shapes:["mirror"],note:"the editor target registry"},{src:"hosts/install.js",shapes:["mirror"],note:"the merge-only installer behind aegiscode mcp install"},{src:"hosts/openai-shim.js",shapes:["mirror"],note:"the loopback OpenAI-compatible shim"},{src:"desktop/renderer/usage.js",shapes:["mirror"],note:"the pure usage mapping shared by the window and the terminal"},{src:"desktop/lib/local/engine.js",shapes:["mirror"],note:"the agent loop, reused as-is (one loop, not a second one drifting)"},{src:"desktop/lib/local/claude-pro.js",shapes:["mirror"],note:"the Claude Code Pro transport; requires ./../../one/src/child.js at call time"},{src:"one/src/child.js",shapes:["mirror"],note:"the ONE claude-child argv builder (rule 4); resolved by claude-pro.js at call time"},{src:"one/src/permissions.js",shapes:["mirror"],note:"resolvePosture() — the permission half of the argv, resolved at call time"},{src:"desktop/lib/local/local.js",shapes:["mirror"],note:"the local model transport and its fail-closed base-URL check"},{src:"desktop/lib/local/context.js",shapes:["mirror"],note:"the token-budget trimmer local.js requires at load"},{src:"desktop/lib/local/attachments.js",shapes:["mirror"],note:"content-part builder for dropped files; required at load by engine.js and local.js"},{src:"desktop/lib/local/session-rounds.js",shapes:["mirror"],note:"interrupted-turn bookkeeping; required at load by engine.js"},{src:"desktop/lib/local/pro-sessions.js",shapes:["mirror"],note:"durable Claude-Pro conversation session ids; required at load by engine.js"},{src:"desktop/lib/local/tools.js",shapes:["mirror"],note:"the tool implementations (persistent shell, editFile, grep, exec)"},{src:"desktop/lib/local/shell.js",shapes:["mirror"],note:"the persistent shell, required by tools.js"},{src:"desktop/lib/local/sandbox.js",shapes:["mirror"],note:"the outcome bound (agent-safety-plan §1b), required by shell.js + tools.js"},{src:"desktop/lib/local/sandbox-bwrap.js",shapes:["mirror"],note:"bubblewrap mechanism behind sandbox.js (agent-safety-plan §1d)"},{src:"desktop/lib/local/sandbox-seatbelt.js",shapes:["mirror"],note:"Seatbelt mechanism behind sandbox.js (agent-safety-plan §1d)"},{src:"desktop/lib/local/sandbox-appcontainer.js",shapes:["mirror"],note:"AppContainer mechanism behind sandbox.js (agent-safety-plan §1e)"},{src:"desktop/lib/local/perm-rules.js",shapes:["mirror"],note:"stored /permissions rules for the desktop gate (agent-safety-plan §2), required by engine.js"},{src:"desktop/lib/local/perm-write.js",shapes:["mirror"],note:'the durable "always allow this command" answer (agent-safety-plan §3), required by main.js'},{src:"desktop/lib/local/perm-store.js",shapes:["mirror"],note:"the Settings rules editor (agent-safety-plan §4), required by main.js"},{src:"desktop/lib/local/integrity.js",shapes:["mirror"],note:"the desktop second gate; required at load by shell.js and tools.js, and the seal over its own four units"},{src:"desktop/main.js",shapes:["mirror"],bytesOnly:!0,note:"seal unit d1 — hashed by integrity.js as BYTES and never required from the mirror, so its own requires (the whole Electron main-process closure) are not staged behind it"},{src:"desktop/lib/local/spill.js",shapes:["mirror"],note:"oversized-output spill, required at load by tools.js and shell.js"},{src:"desktop/lib/local/exec-plan.js",shapes:["mirror"],note:"exec one-shot eligibility classifier, required at load by engine.js"},{src:"desktop/lib/local/agents.js",shapes:["mirror"],note:"Task subagents"},{src:"desktop/lib/local/prompt.js",shapes:["mirror"],note:"the system prompt builder"},{src:"desktop/lib/settings.js",shapes:["mirror"],note:"the provider-config store (base URL + key per provider)"},{src:"desktop/lib/local/turn-guard.js",shapes:["mirror"],note:"engine.js requires it at load; it requires ./git-scope.js"},{src:"desktop/lib/local/repeat-guard.js",shapes:["mirror"],note:"engine.js requires it at load — identical-call detection, no deps of its own"},{src:"desktop/lib/local/verify-stop.js",shapes:["mirror"],note:"engine.js requires it at load — edited-but-unchecked nudge, no deps of its own"},{src:"desktop/lib/local/check-command.js",shapes:["mirror"],note:"verify-stop.js requires it lazily — which command would check this repo; no deps"},{src:"desktop/lib/local/worktree-lock.js",shapes:["mirror"],note:"engine.js requires it at load"},{src:"desktop/lib/local/git-scope.js",shapes:["mirror"],note:"the write-scope rule turn-guard.js and the queues share"},{src:"desktop/lib/local/queue.js",shapes:["mirror"],note:"the autonomous work queue"},{src:"desktop/lib/local/autonomous.js",shapes:["mirror"],note:"the unattended worker; requires ./queue.js and ./git-scope.js"},{src:"desktop/lib/local/entitlement.js",shapes:["mirror"],note:"the shared Pro gate (account probe injected by the caller)"},{src:"desktop/lib/local/covenant.js",shapes:["mirror"],note:"the pre-action gate engine.js requires unconditionally at load"},{src:"desktop/lib/local/aegis-seal.mjs",shapes:["mirror"],note:"the codec covenant.js requires the first time it decodes"},{src:"covenant/aegis.seal",shapes:["mirror","nested"],note:"the sealed covenant (AES/1 container) — path shape is load-bearing"},{src:"covenant/README.md",shapes:["mirror","nested"],note:"the decode notice shipped beside the artifact"},{src:"tools/agent-gate.mjs",shapes:["mirror","flat"],note:"the in-process half of the lock; without it a packaged app had NO gate"},{src:"one/src/selfhost.js",shapes:["mirror","flat"],note:"the packaged launcher decision — which face this artifact was asked for"}];export function entriesFor(e){const r=[];for(const t of MANIFEST){if(!t.shapes.includes(e))continue;let o;if("mirror"===e)o=s.join(CLI_VENDOR,t.src);else if("flat"===e)o=s.join(DESKTOP_VENDOR,s.basename(t.src));else{if("nested"!==e)throw new Error(`predist: unknown shape ${e}`);o=s.join(DESKTOP_VENDOR,t.src)}r.push({src:t.src,dest:o,from:s.join(REPO_DIR,t.src)})}return r}export const SHAPES=["mirror","flat","nested"];const c=[["cli",CLI_DIR,["bin","src","vendor","scripts","package.json","README.md","LICENSE"]],["desktop",DESKTOP_DIR,["main.js","preload.js","lib","renderer","bin","vendor","package.json","README.md"]]],l=new Set(["node_modules","release",".git",".cache","out"]),d=new Map([["desktop/vendor",new Set(["faces","sandbox"])]]);function p(r,t,o){const n=o||new Set,i=(e,s)=>l.has(e)||e.endsWith(".log")||n.has(s),a=(r,t)=>{if(e.mkdirSync(s.dirname(t),{recursive:!0}),e.copyFileSync(r,t),!e.readFileSync(r).equals(e.readFileSync(t)))throw new Error(`predist: bundle copy differs from source: ${s.relative(REPO_DIR,r)}`)},c=(r,o)=>{const n=e.lstatSync(r);if(!n.isSymbolicLink())if(n.isFile())a(r,s.join(t,o));else for(const t of e.readdirSync(r)){const e=o?s.join(o,t):t;i(t,e)||c(s.join(r,t),e)}};e.lstatSync(r).isFile()?a(r,t):c(r,"")}const h=12e4,u=6e5,m=50,f="AEGISONE_PREDIST_LOCK_TOKEN";let g=null,j=!1,b=0;function y(e){try{return process.kill(e,0),!0}catch(e){return Boolean(e)&&"EPERM"===e.code}}const w=e=>new Promise((s=>setTimeout(s,e)));function v(){if(b>0)return void b--;const s=g,r=j,t=process.env[f];if(g=null,j=!1,s&&r){t&&delete process.env[f];try{e.unlinkSync(s)}catch{}}}export async function acquireStageLock(r){if(g)return b++,v;const t=r&&r.stdout||process.stdout;return await async function(r){const t=function(){const r=s.join(REPO_DIR,".git");let t=r;try{if(!e.lstatSync(r).isDirectory()){const o=/^gitdir:\s*(.+)$/m.exec(e.readFileSync(r,"utf8"));o&&(t=s.resolve(REPO_DIR,o[1].trim()))}}catch{t=r}return s.join(t,"aegisone-predist.lock")}(),o=Date.now()+h,n=process.env[f]||null;let i=null,a=!1;for(;;){if(n)try{const s=String(e.readFileSync(t,"utf8")).split("\n")[1];if(s&&s.trim()===n)return g=t,void(j=!1)}catch{}try{i=`${Date.now().toString(36)}-${process.pid}-${Math.random().toString(36).slice(2,10)}`;const s=e.openSync(t,"wx");return e.writeSync(s,`${process.pid}\n${i}\n`),e.closeSync(s),g=t,j=!0,void(process.env[f]=i)}catch(e){if(!e||"EEXIST"!==e.code)throw e}let s=null,c=0;try{s=e.statSync(t),c=Number(String(e.readFileSync(t,"utf8")).split("\n")[0].trim())}catch{continue}if(Date.now()-s.mtimeMs>u||Number.isFinite(c)&&c>0&&!y(c)){r(`predist: breaking an abandoned staging lock (pid ${c||"unknown"})`);try{e.unlinkSync(t)}catch{}}else{if(Date.now()>o)throw new Error(`predist: another stager (pid ${c||"unknown"}) has held ${t} for over ${Math.round(h/1e3)}s. Staging is destructive — it removes and rewrites cli/vendor, desktop/vendor and one/vendor — so it will not run concurrently with a peer. Wait for it, or delete the lock if that process is gone.`);a||(a=!0,r(`predist: another stager (pid ${c||"unknown"}) is running — waiting for it (concurrent staging would read a vendor tree the peer is rewriting)`)),await w(m+Math.floor(Math.random()*m))}}}((e=>t.write(`${e}\n`))),v}function k(r,t){t&&e.rmSync(t,{recursive:!0,force:!0});const o=[];for(const t of r){if(!e.existsSync(t.from))throw new Error(`predist: missing shared module: ${t.src} (expected at ${t.from})`);if(e.mkdirSync(s.dirname(t.dest),{recursive:!0}),e.copyFileSync(t.from,t.dest),!e.readFileSync(t.from).equals(e.readFileSync(t.dest)))throw new Error(`predist: staged copy differs from source: ${t.src}`);o.push(t)}return o}export async function stage(t){const n=t||{},i=n.io||{},l=i.stdout||process.stdout,h=(i.stderr||process.stderr,Array.isArray(n.shapes)?n.shapes:[...SHAPES,"bundle"]),u=e=>h.includes(e),m=e=>l.write(`${e}\n`),f=await acquireStageLock(i);try{return await async function({want:t,log:n}){const i={mirror:null,flat:null,nested:null,bundle:null};if(t("mirror")){const e=k(entriesFor("mirror"),CLI_VENDOR);n(`predist: staged ${e.length} shared modules into cli/vendor/`);for(const s of e)n(` ${s.src} -> vendor/${s.src}`);i.mirror={staged:e.length}}if(t("nested")&&(i.nested={staged:k(entriesFor("nested"),null).length}),t("flat")){const e=k(entriesFor("flat"),null);for(const s of e)n(`staged ${s.dest}`);i.flat={staged:e.length}}if(t("mirror")&&t("flat"))for(const r of MANIFEST){if(!r.shapes.includes("mirror")||!r.shapes.includes("flat"))continue;const t=s.join(CLI_VENDOR,r.src),o=s.join(DESKTOP_VENDOR,s.basename(r.src));if(!e.readFileSync(t).equals(e.readFileSync(o)))throw new Error(`predist: the two shapes disagree for ${r.src}`)}if(t("mirror")){const r=function(r){const t=s.join(CLI_VENDOR,"mcp","tools.js");delete a.cache[a.resolve(t)];const{createTools:o}=a(t),n=o({apiBase:"http://127.0.0.1",apiKey:"predist-probe",randomUUID:()=>"id"}).toolList().length;if(0===n)throw new Error("predist: staged registry exposes no tools");const i=a("node:vm"),c=s.join(CLI_VENDOR,"mcp","server.js");new i.Script(e.readFileSync(c,"utf8"),{filename:c});const l=s.join(CLI_VENDOR,"hosts"),d=a(s.join(l,"spec.js")),p=a(s.join(l,"install.js")),h=a(s.join(l,"targets.js")),u=d.resolveServer({AEGIS_MCP_SERVER:""});if(!u.exists||u.path!==c)throw new Error(`predist: staged hosts/spec.js resolves the server as ${u.path} (exists: ${u.exists}), expected ${c}. An installed aegiscode would write editor configs pointing at a file the package never shipped. Candidates were:\n ${u.candidates.join("\n ")}`);const m=h.getTarget("vscode"),f=p.planTarget(m,"user",{ctx:p.hostCtx({home:s.join(CLI_VENDOR,".predist-home"),env:{},cwd:REPO_DIR}),specOpts:{env:{AEGIS_MCP_SERVER:""}}}),g=JSON.stringify(f.after||"");if(f.error||!f.changed||!g.includes(JSON.stringify(c).slice(1,-1)))throw new Error(`predist: a planned vscode install does not name the staged server (error: ${f.error&&f.error.message}, changed: ${f.changed})`);if("function"!=typeof a(s.join(l,"openai-shim.js")).createShimServer)throw new Error("predist: staged hosts/openai-shim.js exposes no createShimServer");return{count:n,targets:h.targetIds().length,staged:r.length}}(entriesFor("mirror"));n(`predist: staged registry loads standalone (${r.count} tools)`),n(`predist: editor layer verified (${r.targets} host targets, server resolves to vendor/mcp/server.js, shim loads)`);const t=await async function(){const e=s.join(CLI_VENDOR,"tools","agent-gate.mjs");if("function"!=typeof(await import(o(e).href)).run)throw new Error("predist: staged tools/agent-gate.mjs exposes no run()");return e}();n(`predist: ${s.relative(REPO_DIR,t)} loads standalone and exposes run()`),i.mirror.proof=r}if(t("flat")){const r=function(r){const t=new Set(r.map((e=>s.basename(e.dest))));for(const o of r){const r=e.readFileSync(o.dest,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1");for(const e of r.matchAll(/require\(\s*'((?:\.\.?\/)[^']+)'\s*\)/g)){const r=e[1];if(s.basename(r).replace(/\.[cm]?js$/,""),r.replace(/^\.\//,"").startsWith("../"))throw new Error(`predist: flat-staged ${s.basename(o.dest)} requires '${r}', which escapes vendor/ — flattening only works for same-directory requires (add the target to the manifest, or stop staging this file flat)`);const n=r.replace(/^\.\//,"");if(!t.has(n))throw new Error(`predist: flat-staged ${s.basename(o.dest)} requires '${r}', which is not staged into desktop/vendor/ — the packaged app would throw MODULE_NOT_FOUND before the window could open`)}}const o=a(s.join(DESKTOP_VENDOR,"aegis.js"));if(!o||0===Object.keys(o).length)throw new Error("predist: staged desktop/vendor/aegis.js loads but exports nothing");return{files:r.length,exports:Object.keys(o).length}}(entriesFor("flat"));n(`predist: flattened tree is self-contained (${r.files} files, ${r.exports} transport exports) — no staged module escapes vendor/`),i.flat.proof=r}if(t("bundle")){for(const[r,t,o]of c){const i=s.join(ONE_VENDOR,r);e.rmSync(i,{recursive:!0,force:!0});for(const n of o){const o=s.join(t,n);if(!e.existsSync(o)){if("LICENSE"===n||"README.md"===n)continue;throw new Error(`predist: bundle source missing: ${s.relative(REPO_DIR,o)}`)}p(o,s.join(i,n),d.get(`${r}/${n}`))}n(`staged the ${r} face into one/vendor/${r}/`)}const t=function(){const t=s.join(ONE_VENDOR,"cli"),o=s.join(t,"src","deps.js"),n=r(process.execPath,["-e","const d=require(process.argv[1]);console.log(JSON.stringify(d.paths))",o],{cwd:t,encoding:"utf8"});if(0!==n.status)throw new Error(`predist: the bundled CLI does not load: ${n.stderr||n.stdout}`);const i=JSON.parse(n.stdout),a=[];let l=0;for(const[e,r]of Object.entries(i)){const t=s.relative(ONE_VENDOR,r);t.startsWith("..")||s.isAbsolute(t)?a.push(`${e} -> ${r}`):"cli"!==t.split(s.sep)[0]&&l++}if(a.length)throw new Error(`predist: the bundled CLI resolves these shared modules OUTSIDE the bundle (${ONE_VENDOR}) — the product tarball would depend on a repo checkout:\n `+a.join("\n "));if(!e.existsSync(s.join(t,"bin","aegiscode.js")))throw new Error("predist: the bundle has no cli/bin/aegiscode.js");const d=[];for(const[r,t,o]of c)for(const n of o){const o=s.join(ONE_VENDOR,r,n);let i=null,a=null;try{i=e.lstatSync(s.join(t,n))}catch{continue}try{a=e.lstatSync(o)}catch{d.push(`${r}/${n} -> missing`);continue}i.isFile()&&!a.isFile()&&d.push(`${r}/${n} -> not a regular file`),i.isDirectory()&&!a.isDirectory()&&d.push(`${r}/${n} -> not a directory`)}if(d.length)throw new Error(`predist: the bundle staged these in the wrong shape:\n ${d.join("\n ")}`);return{modules:Object.keys(i).length,inSiblingFace:l}}();n(`predist: the bundled CLI resolves ${t.modules} shared modules from inside one/vendor/ (${t.inSiblingFace} through the bundled desktop face) — no repo checkout needed`),i.bundle=t;const o=s.join(DESKTOP_VENDOR,"faces");e.rmSync(o,{recursive:!0,force:!0}),p(s.join(ONE_VENDOR,"cli"),s.join(o,"cli"));const a=s.join(o,"cli","bin","aegiscode.js");if(!e.existsSync(a))throw new Error(`predist: the packaged terminal face has no entry point at ${s.relative(REPO_DIR,a)} — the artifact would open a window for every \`aegiscode\`/\`--tui\` invocation`);n(`staged the terminal face into desktop/vendor/faces/cli/ (${s.basename(a)})`),i.faces={entry:s.relative(REPO_DIR,a)}}return i}({want:u,log:m})}finally{f()}}export async function main(e,s){const r=s||{},t=Array.isArray(e)?e:[],o=t.includes("--quiet")?{write:()=>!0}:r.stdout||process.stdout,n=r.stderr||process.stderr;let i;t.includes("--mirror-only")?i=["mirror"]:t.includes("--flat-only")?i=["flat","nested"]:t.includes("--bundle-only")&&(i=["bundle"]);try{return await stage({shapes:i,io:{stdout:o,stderr:n}}),0}catch(e){return n.write(`${e&&e.message}\n`),1}}!function(){const e=process.argv[1];let r=!1;if(e)try{r=s.resolve(e)===t(import.meta.url)}catch{r=!1}r&&main(process.argv.slice(2)).then((e=>{process.exitCode=e}))}();
|
package/vendor/cli/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aegiscode",
|
|
3
3
|
"productName": "AEGIS Code",
|
|
4
|
-
"version": "7.0.
|
|
4
|
+
"version": "7.0.49",
|
|
5
5
|
"description": "aegiscode — the command-line version of AEGIS One. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "AEGIS Code",
|
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
},
|
|
29
29
|
"scripts": {
|
|
30
30
|
"start": "node bin/aegiscode.js",
|
|
31
|
+
"postinstall": "node scripts/postinstall.mjs",
|
|
31
32
|
"check": "node scripts/check.mjs",
|
|
32
33
|
"test": "node scripts/runtests.mjs"
|
|
33
34
|
},
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
4
|
+
import{existsSync as t}from"node:fs";import{createRequire as n}from"node:module";import{dirname as r,join as o}from"node:path";import{fileURLToPath as e}from"node:url";const i=r(e(import.meta.url));(async function(){const r=function(){const n=[o(i,"..","vendor","client","install-register.js"),o(i,"..","..","client","install-register.js"),o(i,"..","vendor","client","install-register.js")];for(const r of n)if(t(r))return r;return null}();if(!r)return;const e=n(import.meta.url)(r);await e.runPostinstall({app:"npm-postinstall"})})().catch((()=>{}));
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";const path=require("node:path"),credentials=require("./credentials.js"),{createClient:createClient}=require("./aegis.js"),{autoProvisionApiKey:autoProvisionApiKey,provisionFailureText:provisionFailureText}=require("./auto-provision.js"),INSTALL_RETRY_DELAYS_MS=[1500];function installRegisterDisabled(e){const t=e||process.env;return!(!t||!truthy(t.AEGIS_SKIP_INSTALL_REGISTER)&&!truthy(t.AEGIS_SKIP_POSTINSTALL)&&!truthy(t.CI))}function truthy(e){const t=String(null==e?"":e).trim().toLowerCase();return"1"===t||"true"===t||"yes"===t||"on"===t}async function registerAtInstall(e={}){const t=e.env||process.env,r=e.dir||credentials.aegisHome(t),i={registered:!1,already:!1,ok:!1,key:""};try{if(installRegisterDisabled(t))return{...i,note:"skipped: install-time registration is disabled"};const s=credentials.keyStatus({env:t,dir:r});if(s&&s.configured)return{...i,already:!0,ok:!0,note:"a key is already configured"};const n=t&&"string"==typeof t.AEGIS_API_BASE?t.AEGIS_API_BASE.trim():"",a=credentials.clientOptions({channel:e.channel||"cli",env:t,dir:r});n&&(a.apiBase=n);const o=createClient(a),l={saveApiKey:e=>credentials.saveApiKey(e,r)},c=await autoProvisionApiKey(o,l,{app:e.app||"install",retryDelaysMs:INSTALL_RETRY_DELAYS_MS});return c.key?{registered:!0,already:!1,ok:!!c.ok,key:c.key,trialGranted:c.trialGranted,reusedAccount:c.reusedAccount}:{...i,error:c.error,note:provisionFailureText(c)}}catch(e){return{...i,error:e,note:e&&e.message?e.message:String(e)}}}function installRegisterLine(e){if(!e)return"";if(e.already||!1===e.registered&&e.ok)return"";if(!e.registered)return"";const t=e.ok?"saved":"COULD NOT BE SAVED";return e.reusedAccount?`aegis: this machine was already registered — existing account returned (${t})`:`aegis: registered this machine${!0===e.trialGranted?" with the 30-day welcome trial":!1===e.trialGranted?" (welcome trial withheld this hour — too many new devices from this network)":""} — account key ${t}`}async function runPostinstall(e={}){const{app:t="install",stdout:r=process.stdout,stderr:i=process.stderr}=e;try{const s=await registerAtInstall({app:t}),n=installRegisterLine(s);return n&&r.write(`${n}\n`),e.verbose&&!s.registered&&!s.already&&s.note&&i.write(`aegis: install-time registration skipped — ${s.note}\n`),s}catch(t){return e.verbose&&i.write(`aegis: install-time registration errored — ${t&&t.message}\n`),{registered:!1,already:!1,ok:!1,key:"",error:t}}}module.exports={registerAtInstall:registerAtInstall,installRegisterLine:installRegisterLine,installRegisterDisabled:installRegisterDisabled,runPostinstall:runPostinstall,INSTALL_RETRY_DELAYS_MS:INSTALL_RETRY_DELAYS_MS};
|
|
@@ -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"),{aegisHome:aegisHome}=require("./credentials.js"),PREFS_FILE="preferences.json",PREFS_VERSION=1,SHARED_PREF_KEYS=Object.freeze(["themeIndex","model","modelClass","currentModelId","models","effort","vim","memoryPersist","confirmMode","permissionMode","sandboxPolicy"]),LEGACY_MEMORY_PERSIST_NAMESPACE="__memoryPersist",LEGACY_CONFIRM_MODE_NAMESPACE="__confirmMode",SECRET_KEY_RE=/(^|[^a-z0-9])(api[_-]?key|apikey|key|keys|token|secret|password|passwd|credential|credentials|authorization|bearer|private[_-]?key|access[_-]?key|session[_-]?key)([^a-z0-9]|$)/i,SECRET_VALUE_RES=[/\baegis_[A-Za-z0-9_\-]{12,}/,/\bsk-[A-Za-z0-9_\-]{12,}/,/\bghp_[A-Za-z0-9_\-]{20,}/,/\bxox[baprs]-[A-Za-z0-9\-]{10,}/,/\beyJ[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{8,}/,/^[A-Za-z0-9+/]{48,}={0,2}$/];function prefsDir(e){const r=e||{};return r.dir&&String(r.dir).trim()?path.resolve(String(r.dir).trim()):aegisHome(r.env)}function prefsFile(e){const r=e||{};return r.file&&String(r.file).trim()?path.resolve(String(r.file).trim()):path.join(prefsDir(r),PREFS_FILE)}function scanForSecrets(e,r="",t=[]){if(null==e)return t;if("string"==typeof e)return SECRET_VALUE_RES.some((r=>r.test(e)))&&t.push(r||"(root)"),t;if("object"!=typeof e)return t;if(Array.isArray(e))return e.forEach(((e,o)=>scanForSecrets(e,`${r}[${o}]`,t))),t;for(const[o,s]of Object.entries(e)){const e=r?`${r}.${o}`:o;SECRET_KEY_RE.test(o)&&null!=s&&""!==s&&!1!==s?t.push(e):scanForSecrets(s,e,t)}return t}function assertNoSecrets(e,r="shared preference store"){const t=scanForSecrets(e);if(t.length)throw new Error(`${r} must not carry key material — refusing to write (found: ${t.join(", ")}). Secrets belong in the host-local credential store, where the OS can protect them.`);return e}function readJson(e,r){try{const t=JSON.parse(fs.readFileSync(e,"utf8"));return t&&"object"==typeof t&&!Array.isArray(t)?t:r}catch{return r}}function load(e){return readJson(prefsFile(e),{})}function write(e,r){assertNoSecrets(e);const t=prefsFile(r);fs.mkdirSync(path.dirname(t),{recursive:!0});const o=`${t}.tmp-${process.pid}`;fs.writeFileSync(o,JSON.stringify(e,null,2)+"\n",{mode:384}),fs.renameSync(o,t);try{fs.chmodSync(t,384)}catch{}return e}function set(e,r){const t={...load(r),...e||{}};for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return void 0===t.version&&(t.version=1),write(t,r)}function get(e,r,t){const o=load(r)[e];return void 0===o?t:o}function has(e,r){return void 0!==load(r)[e]}function remove(e,r){const t=load(r);return delete t[e],write(t,r)}function extractNonSecretHalf(e){const r={},t=(e||{})[LEGACY_MEMORY_PERSIST_NAMESPACE];t&&"object"==typeof t&&"boolean"==typeof t.enabled&&(r.memoryPersist=t.enabled);const o=(e||{})[LEGACY_CONFIRM_MODE_NAMESPACE];return o&&"object"==typeof o&&"boolean"==typeof o.enabled&&(r.confirmMode=o.enabled),r}function adopt(e){const r=e||{},t=prefsFile(r),o=r.legacyDir,s=o?path.join(String(o),"settings.json"):null;if(s&&path.resolve(s)===t)return{adopted:!1,keys:[],from:s,reason:"shared store is the legacy file"};if(!s||!fs.existsSync(s))return{adopted:!1,keys:[],from:s,reason:"no legacy settings file"};const n=load(r),
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),PREFS_FILE="preferences.json",PREFS_VERSION=1,SHARED_PREF_KEYS=Object.freeze(["themeIndex","model","modelClass","currentModelId","models","effort","vim","memoryPersist","confirmMode","permissionMode","sandboxPolicy","devMode","accountUsername"]),LEGACY_MEMORY_PERSIST_NAMESPACE="__memoryPersist",LEGACY_CONFIRM_MODE_NAMESPACE="__confirmMode",SECRET_KEY_RE=/(^|[^a-z0-9])(api[_-]?key|apikey|key|keys|token|secret|password|passwd|credential|credentials|authorization|bearer|private[_-]?key|access[_-]?key|session[_-]?key)([^a-z0-9]|$)/i,SECRET_VALUE_RES=[/\baegis_[A-Za-z0-9_\-]{12,}/,/\bsk-[A-Za-z0-9_\-]{12,}/,/\bghp_[A-Za-z0-9_\-]{20,}/,/\bxox[baprs]-[A-Za-z0-9\-]{10,}/,/\beyJ[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{8,}/,/^[A-Za-z0-9+/]{48,}={0,2}$/];function prefsDir(e){const r=e||{};return r.dir&&String(r.dir).trim()?path.resolve(String(r.dir).trim()):aegisHome(r.env)}function prefsFile(e){const r=e||{};return r.file&&String(r.file).trim()?path.resolve(String(r.file).trim()):path.join(prefsDir(r),PREFS_FILE)}function scanForSecrets(e,r="",t=[]){if(null==e)return t;if("string"==typeof e)return SECRET_VALUE_RES.some((r=>r.test(e)))&&t.push(r||"(root)"),t;if("object"!=typeof e)return t;if(Array.isArray(e))return e.forEach(((e,o)=>scanForSecrets(e,`${r}[${o}]`,t))),t;for(const[o,s]of Object.entries(e)){const e=r?`${r}.${o}`:o;SECRET_KEY_RE.test(o)&&null!=s&&""!==s&&!1!==s?t.push(e):scanForSecrets(s,e,t)}return t}function assertNoSecrets(e,r="shared preference store"){const t=scanForSecrets(e);if(t.length)throw new Error(`${r} must not carry key material — refusing to write (found: ${t.join(", ")}). Secrets belong in the host-local credential store, where the OS can protect them.`);return e}function readJson(e,r){try{const t=JSON.parse(fs.readFileSync(e,"utf8"));return t&&"object"==typeof t&&!Array.isArray(t)?t:r}catch{return r}}function load(e){return readJson(prefsFile(e),{})}function write(e,r){assertNoSecrets(e);const t=prefsFile(r);fs.mkdirSync(path.dirname(t),{recursive:!0});const o=`${t}.tmp-${process.pid}`;fs.writeFileSync(o,JSON.stringify(e,null,2)+"\n",{mode:384}),fs.renameSync(o,t);try{fs.chmodSync(t,384)}catch{}return e}function set(e,r){const t={...load(r),...e||{}};for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return void 0===t.version&&(t.version=1),write(t,r)}function get(e,r,t){const o=load(r)[e];return void 0===o?t:o}function has(e,r){return void 0!==load(r)[e]}function remove(e,r){const t=load(r);return delete t[e],write(t,r)}function extractNonSecretHalf(e){const r={},t=(e||{})[LEGACY_MEMORY_PERSIST_NAMESPACE];t&&"object"==typeof t&&"boolean"==typeof t.enabled&&(r.memoryPersist=t.enabled);const o=(e||{})[LEGACY_CONFIRM_MODE_NAMESPACE];return o&&"object"==typeof o&&"boolean"==typeof o.enabled&&(r.confirmMode=o.enabled),r}function adopt(e){const r=e||{},t=prefsFile(r),o=r.legacyDir,s=o?path.join(String(o),"settings.json"):null;if(s&&path.resolve(s)===t)return{adopted:!1,keys:[],from:s,reason:"shared store is the legacy file"};if(!s||!fs.existsSync(s))return{adopted:!1,keys:[],from:s,reason:"no legacy settings file"};const n=load(r),a=extractNonSecretHalf(readJson(s,{})),i=Object.keys(a).filter((e=>void 0===n[e]));if(!i.length)return{adopted:!1,keys:[],from:s,reason:Object.keys(a).length?"shared store already carries these preferences":"legacy store has no shared preferences"};const c={};for(const e of i)c[e]=a[e];return c.adopted={from:s,at:(new Date).toISOString(),names:i.slice().sort()},write({...n,...c},r),{adopted:!0,keys:i.slice().sort(),from:s}}module.exports={PREFS_FILE:PREFS_FILE,PREFS_VERSION:1,SHARED_PREF_KEYS:SHARED_PREF_KEYS,LEGACY_MEMORY_PERSIST_NAMESPACE:LEGACY_MEMORY_PERSIST_NAMESPACE,prefsDir:prefsDir,prefsFile:prefsFile,load:load,set:set,get:get,has:has,remove:remove,scanForSecrets:scanForSecrets,assertNoSecrets:assertNoSecrets,extractNonSecretHalf:extractNonSecretHalf,adopt:adopt};
|
|
@@ -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"),{aegisHome:aegisHome}=require("./credentials.js"),STORE_FILE="sessions.json",STORE_VERSION=2,MAX_MESSAGES_PER_SESSION=2e3;function storeDir(e){return e||aegisHome()}function storeFile(e){return path.join(storeDir(e),STORE_FILE)}function nextSeq(e){const t=("number"==typeof e.__seq?e.__seq:0)+1;return e.__seq=t,t}function toEpochMs(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.trim()){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function load(e){try{const t=JSON.parse(fs.readFileSync(storeFile(e),"utf8"));if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}return{}}function atomicWrite(e,t){fs.mkdirSync(path.dirname(e),{recursive:!0});const n=`${e}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),fs.renameSync(n,e);try{fs.chmodSync(e,384)}catch{}}const LOCK_STALE_MS=3e4,LOCK_WAIT_MS=(()=>{const e=Number(process.env.AEGIS_STORE_LOCK_WAIT_MS);return Number.isFinite(e)&&e>0?e:15e3})(),SLEEP_CELL=new Int32Array(new SharedArrayBuffer(4));function lockFile(e){return`${storeFile(e)}.lock`}function acquireLock(e){const t=lockFile(e);try{fs.mkdirSync(path.dirname(t),{recursive:!0})}catch{return!1}const n=Date.now()+LOCK_WAIT_MS,s=Math.max(200,Math.ceil(LOCK_WAIT_MS/5)+200);for(let e=0;e<s;e++)try{const e=fs.openSync(t,"wx");return fs.writeSync(e,String(process.pid)),fs.closeSync(e),!0}catch{let e=null;try{e=Date.now()-fs.statSync(t).mtimeMs}catch{continue}if(lockAbandoned(t,e)){try{fs.unlinkSync(t)}catch{}continue}if(Date.now()>=n)return!1;Atomics.wait(SLEEP_CELL,0,0,5)}return!1}function pidAlive(e){try{return process.kill(e,0),!0}catch(e){return e&&"EPERM"===e.code}}function lockAbandoned(e,t){let n=0;try{n=Number(String(fs.readFileSync(e,"utf8")).trim())}catch{n=0}return Number.isInteger(n)&&n>0?!pidAlive(n):t>LOCK_STALE_MS}function releaseLock(e){try{fs.unlinkSync(lockFile(e))}catch{}}function mutate(e,t){if(!acquireLock(e))throw new Error(`session store is locked by another writer: ${lockFile(e)} (waited ${LOCK_WAIT_MS}ms — refusing to write unlocked and overwrite it)`);try{const n=load(e),s=t(n);return save(e,n),s}finally{releaseLock(e)}}function save(e,t){atomicWrite(storeFile(e),t)}function trimMessages(e){return Array.isArray(e)?e.length<=MAX_MESSAGES_PER_SESSION?e:e.slice(e.length-MAX_MESSAGES_PER_SESSION):[]}function upsertSession(e,t){const n=t&&t.id;if(!n)throw new Error("session.id is required");return mutate(e,(e=>{const s=e[n]||{messages:[]};
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),STORE_FILE="sessions.json",STORE_VERSION=2,MAX_MESSAGES_PER_SESSION=2e3;function storeDir(e){return e||aegisHome()}function storeFile(e){return path.join(storeDir(e),STORE_FILE)}function nextSeq(e){const t=("number"==typeof e.__seq?e.__seq:0)+1;return e.__seq=t,t}function toEpochMs(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.trim()){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function load(e){try{const t=JSON.parse(fs.readFileSync(storeFile(e),"utf8"));if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}return{}}function atomicWrite(e,t){fs.mkdirSync(path.dirname(e),{recursive:!0});const n=`${e}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),fs.renameSync(n,e);try{fs.chmodSync(e,384)}catch{}}const LOCK_STALE_MS=3e4,LOCK_WAIT_MS=(()=>{const e=Number(process.env.AEGIS_STORE_LOCK_WAIT_MS);return Number.isFinite(e)&&e>0?e:15e3})(),SLEEP_CELL=new Int32Array(new SharedArrayBuffer(4));function lockFile(e){return`${storeFile(e)}.lock`}function acquireLock(e){const t=lockFile(e);try{fs.mkdirSync(path.dirname(t),{recursive:!0})}catch{return!1}const n=Date.now()+LOCK_WAIT_MS,s=Math.max(200,Math.ceil(LOCK_WAIT_MS/5)+200);for(let e=0;e<s;e++)try{const e=fs.openSync(t,"wx");return fs.writeSync(e,String(process.pid)),fs.closeSync(e),!0}catch{let e=null;try{e=Date.now()-fs.statSync(t).mtimeMs}catch{continue}if(lockAbandoned(t,e)){try{fs.unlinkSync(t)}catch{}continue}if(Date.now()>=n)return!1;Atomics.wait(SLEEP_CELL,0,0,5)}return!1}function pidAlive(e){try{return process.kill(e,0),!0}catch(e){return e&&"EPERM"===e.code}}function lockAbandoned(e,t){let n=0;try{n=Number(String(fs.readFileSync(e,"utf8")).trim())}catch{n=0}return Number.isInteger(n)&&n>0?!pidAlive(n):t>LOCK_STALE_MS}function releaseLock(e){try{fs.unlinkSync(lockFile(e))}catch{}}function mutate(e,t){if(!acquireLock(e))throw new Error(`session store is locked by another writer: ${lockFile(e)} (waited ${LOCK_WAIT_MS}ms — refusing to write unlocked and overwrite it)`);try{const n=load(e),s=t(n);return save(e,n),s}finally{releaseLock(e)}}function save(e,t){atomicWrite(storeFile(e),t)}function trimMessages(e){return Array.isArray(e)?e.length<=MAX_MESSAGES_PER_SESSION?e:e.slice(e.length-MAX_MESSAGES_PER_SESSION):[]}function upsertSession(e,t){const n=t&&t.id;if(!n)throw new Error("session.id is required");return mutate(e,(e=>{const s=e[n]||{messages:[]};e[n]={...s,...t,id:n,version:2};const r=t&&!0===t.seed,i="string"==typeof s.title&&s.title;return!0===s.named&&i?(e[n].title=s.title,e[n].named=!0):r&&i&&s.title&&(e[n].title=s.title),delete e[n].seed,!1!==t.pending&&(e[n].pending=!0),e[n].updatedAt||(e[n].updatedAt=Date.now()),e[n].seq=nextSeq(e),e[n]}))}function appendMessage(e,t,n){if(!t)throw new Error("sessionId is required");return mutate(e,(e=>{const s=e[t]||{id:t,messages:[]},r=Array.isArray(s.messages)?s.messages:[];return s.messages=trimMessages(r.concat(n)),s.updatedAt=Date.now(),s.pending=!0,s.seq=nextSeq(e),e[t]=s,s}))}function recordExchange(e,t){const n=t||{};if(!n.sessionId)return null;const s=n.sessionId;return mutate(e,(e=>{const t=e[s]||{id:s,messages:[]},r=Array.isArray(t.messages)?t.messages:[],i=n.ts||(new Date).toISOString(),o={role:"user",content:null==n.prompt?"":String(n.prompt),ts:i},a={role:"assistant",content:null==n.reply?"":String(n.reply),ts:i};return n.tokens&&(a.tokens=n.tokens),"number"==typeof n.costUsd&&(a.costUsd=n.costUsd),n.status&&(a.status=n.status),n.model&&(a.model=n.model),n.provider&&(a.provider=n.provider),n.origin&&(o.origin=n.origin,a.origin=n.origin),t.messages=trimMessages(r.concat([o,a])),t.title=t.title||String(n.prompt||"").slice(0,60),n.cwd&&(t.cwd=n.cwd),t.origin=n.origin||t.origin||"unknown",t.updatedAt=Date.now(),t.pending=!0===n.pending,t.seq=nextSeq(e),e[s]=t,t}))}function setTitle(e,t,n,s){const r=String(null==n?"":n).trim().slice(0,200);if(!t||!r)return null;const i=s&&!0===s.named;return mutate(e,(e=>{const n=e[t];return n?(n.title=r,i&&(n.named=!0),n.updatedAt=Date.now(),n.seq=nextSeq(e),n):null}))}function listSessions(e){const t=load(e);return Object.values(t).filter((e=>e&&e.id)).sort(((e,t)=>(t.updatedAt||0)-(e.updatedAt||0)||(t.seq||0)-(e.seq||0)))}function getSession(e,t){return load(e)[t]||null}function deleteSession(e,t){return mutate(e,(e=>(delete e[t],{ok:!0})))}function markSynced(e,t,n){return mutate(e,(e=>{const s=e[t];return s?(s.pending=!1,s.lastSyncedAt=Date.now(),n&&n.remoteId&&(s.remoteId=n.remoteId),s.seq=nextSeq(e),s):null}))}function markPending(e,t){return mutate(e,(e=>{const n=e[t];return n?(n.pending=!0,n.seq=nextSeq(e),n):null}))}function listPending(e){return listSessions(e).filter((e=>!1!==e.pending))}function mergeRemoteSessions(e,t){const n=Array.isArray(t)?t:[];return n.length?mutate(e,(e=>{let t=0;for(const s of n){const n=s&&(s.session_id||s.id);if(!n)continue;const r=e[n],i=toEpochMs(s.updated_at??s.updatedAt);r&&(r.pending||(r.updatedAt||0)>=i)||(e[n]={id:n,title:s.title||r&&r.title||"",messages:Array.isArray(s.messages)?s.messages:[],updatedAt:i||Date.now(),pending:!1,lastSyncedAt:Date.now(),remoteId:s.session_id||s.id,origin:s.source||r&&r.origin||"cloud",version:2},e[n].seq=nextSeq(e),t+=1)}return t})):0}function listSummaries(e,t=8){return listSessions(e).slice(0,t).map((e=>{const t=Array.isArray(e.messages)?e.messages:[],n=t.find((e=>e&&"user"===e.role));return{id:e.id,cwd:(e.cwd||"").split(/[\\/]/).filter(Boolean).pop()||"~",summary:String(e.title||n&&n.content||"").slice(0,60),time:new Date(e.updatedAt||Date.now()).toISOString(),own:!0,origin:e.origin||"unknown",messages:t.length,pending:!0===e.pending,dir:String(e.cwd||"")}}))}function readTranscript(e,t){const n=getSession(e,t);return n?(Array.isArray(n.messages)?n.messages:[]).filter((e=>e&&("user"===e.role||"assistant"===e.role))).map((e=>({role:e.role,text:null==e.content?"":String(e.content)}))):[]}function adopt(e,t){const n=storeFile(t);if(!(()=>{try{return fs.existsSync(n)}catch{return!1}})())return{adopted:!1,sessions:0,from:n,reason:"no legacy store"};const s=(()=>{try{const e=JSON.parse(fs.readFileSync(n,"utf8"));return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}})(),r=Object.values(s).filter((e=>e&&e.id));if(!r.length)return{adopted:!1,sessions:0,from:n,reason:"legacy store empty"};let i=0;return mutate(e,(e=>{for(const t of r)e[t.id]||(e[t.id]={...t,adoptedFrom:n,version:2},e[t.id].seq=nextSeq(e),i+=1);return e.__seq=Math.max(e.__seq||0,s.__seq||0),e.version=2,null})),i?{adopted:!0,sessions:i,from:n}:{adopted:!1,sessions:0,from:n,reason:"already adopted"}}function toMarkdown(e){const t=e&&(e.title||e.id)||"session",n=e&&Array.isArray(e.messages)?e.messages:[],s=[`# ${t}`,""];for(const e of n){const t=e&&e.role||"unknown",n=t.charAt(0).toUpperCase()+t.slice(1),r=e&&(e.content||e.text)||"";s.push(`## ${n}`,"",r,"")}return s.join("\n")}function toJson(e){return JSON.stringify(e,null,2)}module.exports={STORE_FILE:STORE_FILE,STORE_VERSION:2,MAX_MESSAGES_PER_SESSION:MAX_MESSAGES_PER_SESSION,storeDir:storeDir,storeFile:storeFile,lockFile:lockFile,LOCK_STALE_MS:LOCK_STALE_MS,LOCK_WAIT_MS:LOCK_WAIT_MS,toEpochMs:toEpochMs,load:load,save:save,upsertSession:upsertSession,appendMessage:appendMessage,recordExchange:recordExchange,setTitle:setTitle,listSessions:listSessions,getSession:getSession,deleteSession:deleteSession,markSynced:markSynced,markPending:markPending,listPending:listPending,mergeRemoteSessions:mergeRemoteSessions,listSummaries:listSummaries,readTranscript:readTranscript,adopt:adopt,toMarkdown:toMarkdown,toJson:toJson};
|
|
@@ -134,7 +134,7 @@ const UNITS = Object.freeze([
|
|
|
134
134
|
* (`tools/desktop-seal.mjs` in the source tree, `tools/obfuscate-faces.mjs`
|
|
135
135
|
* after obfuscation), never by hand.
|
|
136
136
|
*/
|
|
137
|
-
const SEALED = '
|
|
137
|
+
const SEALED = 'fc6c814a2883e78a441c3bccd268b120013bb8e93aeaf40d5bcd7dbd782408fc';
|
|
138
138
|
|
|
139
139
|
/**
|
|
140
140
|
* Ask the question. Never throws — a check that can break the program it is
|
|
@@ -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",FONT_SCALE_NAMESPACE="__fontScale",ACCENT_NAMESPACE="__accent",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(e){return Number.isFinite(e)?Math.min(1.3,Math.max(.85,Math.round(100*e)/100)):1}function M(){return m((d().__fontScale||{}).scale)}const p=["default","cobalt","amber"];function g(e){const n="string"==typeof e?e.trim().toLowerCase():"";return p.includes(n)?n:"default"}function y(){return g((d().__accent||{}).name)}function N(){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 b(){const e=d().__vaultBackend||{};return{backend:VAULT_BACKEND_VALUES.includes(e.backend)?e.backend:"aegiscloud"}}function v(){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 C(){const e=a().sandboxPolicy;return e&&"object"==typeof e?e:null}function T(){const e=a();return"string"==typeof e.permissionMode?e.permissionMode:null}function h(){return!0===(d().__telemetry||{}).enabled}function R(){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 I(){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 L(){const e=d().__avatar||{};return{...I(),source:void 0===e.enabled?"default":"config"}}function D(e){const n=Number(e);if(!Number.isFinite(n))return 6e4;const t=Math.round(n);return t<15e3||t>18e5?6e4:t}function P(){const e=d().__autoDrain||{};return{enabled:!1!==e.enabled,intervalMs:D(e.intervalMs)}}function O(){const e=d().__autoDrain||{};return{...P(),source:void 0===e.enabled?"default":"config"}}function U(){const e=d().__autoMint||{};return{enabled:!1!==e.enabled,publish:!0===e.publish}}function k(){const e=d().__autoMint||{};return{...U(),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:N,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),N()},vaultBackendConfig:b,setVaultBackendConfig:function(e){if(!VAULT_BACKEND_VALUES.includes(e))return b();const n=d();return n.__vaultBackend={backend:e},f(n),b()},getConfirmMode:function(){return v().enabled},setConfirmMode:function(e){prefs.set({confirmMode:Boolean(e)},{dir:i});const n=d();return void 0!==n.__confirmMode&&(delete n.__confirmMode,f(n)),v().enabled},confirmModeState:v,getFontScale:M,setFontScale:function(e){const n=d();return n.__fontScale={scale:m(e)},f(n),M()},clampFontScale:m,getAccent:y,setAccent:function(e){const n=d();return n.__accent={name:g(e)},f(n),y()},clampAccent:g,ACCENT_SKINS:p,getPermissionMode:T,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}),T()},getSandboxPolicy:C,setSandboxPolicy:function(e){return e&&"object"==typeof e?(prefs.set({sandboxPolicy:e},{dir:i}),C()):(prefs.set({sandboxPolicy:null},{dir:i}),null)},getTelemetryOptIn:h,setTelemetryOptIn:function(e){const n=d();return n.__telemetry={enabled:Boolean(e)},f(n),h()},getMemoryPersist:function(){return R().enabled},memoryPersistState:R,setMemoryPersist:function(e){prefs.set({memoryPersist:Boolean(e)},{dir:i});const n=d();return void 0!==n.__memoryPersist&&(delete n.__memoryPersist,f(n)),R()},getAvatar:I,avatarState:L,setAvatar:function(e={}){const n=I(),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),L()},getAutoDrain:P,autoDrainState:O,setAutoDrain:function(e={}){const n=P(),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:D(t.intervalMs)},f(r),O()},getAutoMint:U,autoMintState:k,setAutoMint:function(e={}){const n=U(),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),k()},clampAutoDrainInterval:D}}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",FONT_SCALE_NAMESPACE="__fontScale",ACCENT_NAMESPACE="__accent",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 l(e){return null==e?null:u()?n.encryptString(String(e)).toString("base64"):Buffer.from(String(e),"utf8").toString("base64")}function _(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=_(n.key);return{provider:e,baseURL:n.baseURL||"",configured:Boolean(t),keyMask:maskKey(t)}}function S(){const e=_((d().__aegis||{}).key);return{configured:Boolean(e),keyMask:maskKey(e)}}function m(e){return Number.isFinite(e)?Math.min(1.3,Math.max(.85,Math.round(100*e)/100)):1}function M(){return m((d().__fontScale||{}).scale)}const p=["default","cobalt","amber"];function g(e){const n="string"==typeof e?e.trim().toLowerCase():"";return p.includes(n)?n:"default"}function y(){return g((d().__accent||{}).name)}function N(){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 b(){const e=d().__vaultBackend||{};return{backend:VAULT_BACKEND_VALUES.includes(e.backend)?e.backend:"aegiscloud"}}function v(){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 C(){const e=a().sandboxPolicy;return e&&"object"==typeof e?e:null}function T(){return!0===a().devMode}function h(){const e=a().accountUsername;return"string"==typeof e?e:null}function R(){const e=a();return"string"==typeof e.permissionMode?e.permissionMode:null}function I(){return!0===(d().__telemetry||{}).enabled}function L(){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 D(){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 P(){const e=d().__avatar||{};return{...D(),source:void 0===e.enabled?"default":"config"}}function O(e){const n=Number(e);if(!Number.isFinite(n))return 6e4;const t=Math.round(n);return t<15e3||t>18e5?6e4:t}function U(){const e=d().__autoDrain||{};return{enabled:!1!==e.enabled,intervalMs:O(e.intervalMs)}}function k(){const e=d().__autoDrain||{};return{...U(),source:void 0===e.enabled?"default":"config"}}function B(){const e=d().__autoMint||{};return{enabled:!1!==e.enabled,publish:!0===e.publish}}function K(){const e=d().__autoMint||{};return{...B(),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)},getDevMode:T,setDevMode:function(e){return prefs.set({devMode:Boolean(e)},{dir:i}),T()},getAccountUsername:h,setAccountUsername:function(e){return prefs.set({accountUsername:"string"==typeof e?e:null},{dir:i}),h()},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?l(t):null),o[e]=i,f(o),E(e)},rawKey:function(e){return _((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 _((d().__aegis||{}).key)},aegisKeySavedAt:function(){return(d().__aegis||{}).savedAt||null},setAegisKey:function(e){const n=d();return n.__aegis={...n.__aegis||{},key:e?l(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:N,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),N()},vaultBackendConfig:b,setVaultBackendConfig:function(e){if(!VAULT_BACKEND_VALUES.includes(e))return b();const n=d();return n.__vaultBackend={backend:e},f(n),b()},getConfirmMode:function(){return v().enabled},setConfirmMode:function(e){prefs.set({confirmMode:Boolean(e)},{dir:i});const n=d();return void 0!==n.__confirmMode&&(delete n.__confirmMode,f(n)),v().enabled},confirmModeState:v,getFontScale:M,setFontScale:function(e){const n=d();return n.__fontScale={scale:m(e)},f(n),M()},clampFontScale:m,getAccent:y,setAccent:function(e){const n=d();return n.__accent={name:g(e)},f(n),y()},clampAccent:g,ACCENT_SKINS:p,getPermissionMode:R,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}),R()},getSandboxPolicy:C,setSandboxPolicy:function(e){return e&&"object"==typeof e?(prefs.set({sandboxPolicy:e},{dir:i}),C()):(prefs.set({sandboxPolicy:null},{dir:i}),null)},getTelemetryOptIn:I,setTelemetryOptIn:function(e){const n=d();return n.__telemetry={enabled:Boolean(e)},f(n),I()},getMemoryPersist:function(){return L().enabled},memoryPersistState:L,setMemoryPersist:function(e){prefs.set({memoryPersist:Boolean(e)},{dir:i});const n=d();return void 0!==n.__memoryPersist&&(delete n.__memoryPersist,f(n)),L()},getAvatar:D,avatarState:P,setAvatar:function(e={}){const n=D(),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),P()},getAutoDrain:U,autoDrainState:k,setAutoDrain:function(e={}){const n=U(),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:O(t.intervalMs)},f(r),k()},getAutoMint:B,autoMintState:K,setAutoMint:function(e={}){const n=B(),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),K()},clampAutoDrainInterval:O}}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};
|
|
@@ -607,10 +607,20 @@ function abortedTurnPayload(err) {
|
|
|
607
607
|
* provider that is genuinely down still names itself on the next turn the
|
|
608
608
|
* user actually sends. `AEGIS_DEBUG` is the same switch `bin/aegis.js` uses
|
|
609
609
|
* for its launch errors, so there is one way to ask this app to talk.
|
|
610
|
+
*
|
|
611
|
+
* Also gates the foreground lane's own classified lines (a user-pressed
|
|
612
|
+
* Ctrl-X, a genuine provider failure on the turn someone is actually
|
|
613
|
+
* waiting on) — those are not background noise, but printing them for every
|
|
614
|
+
* install made a regular user's shell narrate internal stack traces it had
|
|
615
|
+
* no way to turn off. `settings.getDevMode()` (Settings → Developer panel,
|
|
616
|
+
* shown only to the one account that opts in) is the GUI door to the same
|
|
617
|
+
* switch, so turning it on does not require relaunching from a terminal
|
|
618
|
+
* with an env var set.
|
|
610
619
|
*/
|
|
611
|
-
function backgroundLaneLogs() {
|
|
620
|
+
function backgroundLaneLogs(settings) {
|
|
612
621
|
const v = process.env.AEGIS_DEBUG;
|
|
613
|
-
|
|
622
|
+
if (v === '1' || v === 'true' || v === 'yes') return true;
|
|
623
|
+
return Boolean(settings && typeof settings.getDevMode === 'function' && settings.getDevMode());
|
|
614
624
|
}
|
|
615
625
|
|
|
616
626
|
/**
|
|
@@ -1721,6 +1731,29 @@ function createConfirmModeDispatch(settings) {
|
|
|
1721
1731
|
};
|
|
1722
1732
|
}
|
|
1723
1733
|
|
|
1734
|
+
/**
|
|
1735
|
+
* Developer mode: `aegis:getDevMode` / `aegis:setDevMode`. Same shape as
|
|
1736
|
+
* createConfirmModeDispatch — the Settings → Developer panel's one switch,
|
|
1737
|
+
* which `backgroundLaneLogs()` reads alongside `AEGIS_DEBUG` so this account
|
|
1738
|
+
* can turn the console back on without an env var.
|
|
1739
|
+
*/
|
|
1740
|
+
function createDevModeDispatch(settings) {
|
|
1741
|
+
if (!settings) throw new Error('createDevModeDispatch requires a settings store');
|
|
1742
|
+
return {
|
|
1743
|
+
getDevMode: () => ({ enabled: settings.getDevMode() }),
|
|
1744
|
+
setDevMode: (payload) => {
|
|
1745
|
+
const enabled = payload && payload.enabled;
|
|
1746
|
+
if (typeof enabled !== 'boolean') return { enabled: settings.getDevMode() };
|
|
1747
|
+
return { enabled: settings.setDevMode(enabled) };
|
|
1748
|
+
},
|
|
1749
|
+
getAccountUsername: () => ({ username: settings.getAccountUsername() }),
|
|
1750
|
+
setAccountUsername: (payload) => {
|
|
1751
|
+
const username = payload && typeof payload.username === 'string' ? payload.username : null;
|
|
1752
|
+
return { username: settings.setAccountUsername(username) };
|
|
1753
|
+
},
|
|
1754
|
+
};
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1724
1757
|
/**
|
|
1725
1758
|
* Plan mode: `aegis:getPermissionMode` / `aegis:setPermissionMode`. Same shape
|
|
1726
1759
|
* as createConfirmModeDispatch, registered through the same generic
|
|
@@ -3378,7 +3411,7 @@ function createHeartbeatRetry(push, opts = {}) {
|
|
|
3378
3411
|
* used for that gate. Falls back to `sessionsDir` for callers that don't pass
|
|
3379
3412
|
* it, i.e. tests that use one directory for everything.
|
|
3380
3413
|
*/
|
|
3381
|
-
function registerModelIpc(ipcMain, engine, sessionsDir, aegis, onReplyFinished, heartbeatOpts, settingsDir) {
|
|
3414
|
+
function registerModelIpc(ipcMain, engine, sessionsDir, aegis, onReplyFinished, heartbeatOpts, settingsDir, settings) {
|
|
3382
3415
|
const modelDispatch = createModelDispatch(engine);
|
|
3383
3416
|
const syncDispatch = createSyncDispatch(sessionStore, sessionsDir, aegis, settingsDir, modelDispatch);
|
|
3384
3417
|
|
|
@@ -3440,26 +3473,46 @@ function registerModelIpc(ipcMain, engine, sessionsDir, aegis, onReplyFinished,
|
|
|
3440
3473
|
const lane = opts.class || 'model';
|
|
3441
3474
|
const turn = handler({ ...opts, onStream: forward });
|
|
3442
3475
|
if (!bestEffort) {
|
|
3443
|
-
//
|
|
3444
|
-
// rejection
|
|
3445
|
-
//
|
|
3446
|
-
//
|
|
3447
|
-
//
|
|
3448
|
-
//
|
|
3449
|
-
//
|
|
3450
|
-
//
|
|
3451
|
-
//
|
|
3452
|
-
//
|
|
3453
|
-
//
|
|
3454
|
-
//
|
|
3455
|
-
//
|
|
3456
|
-
//
|
|
3476
|
+
// Nothing on this path may reject: `ipcMain.handle` prints every
|
|
3477
|
+
// rejection with a full stack ("Error occurred in handler for
|
|
3478
|
+
// 'model:chat':") and no flag suppresses that — it is baked into
|
|
3479
|
+
// Electron, not this app. A user-pressed stop and a genuine 400/402
|
|
3480
|
+
// from the provider both used to take that exit, so either one put
|
|
3481
|
+
// a provider stack trace (local file paths included) in front of
|
|
3482
|
+
// every install's terminal, dev or not. Both are reclassified into
|
|
3483
|
+
// a resolved payload instead; the renderer turns `aborted` back
|
|
3484
|
+
// into an AbortError and `providerFailed` back into a plain Error
|
|
3485
|
+
// (see `models.chat` in app.js), so every existing catch — the
|
|
3486
|
+
// `isCancellation` → `salvageTurn` path, and the plain
|
|
3487
|
+
// "Error: <message>" bubble — runs exactly as before, minus the
|
|
3488
|
+
// stack. `backgroundLaneLogs(settings)` is what still SHOWS that
|
|
3489
|
+
// stack, for the one account that turns Settings → Developer mode
|
|
3490
|
+
// on (or launches with `AEGIS_DEBUG=1`).
|
|
3457
3491
|
return withReplyNotify(turn, event, onReplyFinished).catch((err) => {
|
|
3458
|
-
if (
|
|
3459
|
-
|
|
3460
|
-
|
|
3461
|
-
|
|
3462
|
-
|
|
3492
|
+
if (isAbortShapedError(err)) {
|
|
3493
|
+
if (backgroundLaneLogs(settings)) {
|
|
3494
|
+
console.warn(
|
|
3495
|
+
`[model] ${lane} turn stopped before it finished: ${errorText(err)} [ABORT_ERR]`
|
|
3496
|
+
);
|
|
3497
|
+
}
|
|
3498
|
+
return abortedTurnPayload(err);
|
|
3499
|
+
}
|
|
3500
|
+
const status = err && typeof err.status === 'number' ? err.status : 0;
|
|
3501
|
+
const code = (err && err.code) || '';
|
|
3502
|
+
if (backgroundLaneLogs(settings)) {
|
|
3503
|
+
console.error(
|
|
3504
|
+
`[model] ${lane} turn failed: ${errorText(err)}` +
|
|
3505
|
+
`${status ? ` (status ${status})` : ''}${code ? ` [${code}]` : ''}`,
|
|
3506
|
+
err && err.stack ? err.stack : ''
|
|
3507
|
+
);
|
|
3508
|
+
}
|
|
3509
|
+
return {
|
|
3510
|
+
providerFailed: true,
|
|
3511
|
+
status,
|
|
3512
|
+
code: code || undefined,
|
|
3513
|
+
message: errorText(err),
|
|
3514
|
+
choices: [{ message: { content: '' } }],
|
|
3515
|
+
};
|
|
3463
3516
|
});
|
|
3464
3517
|
}
|
|
3465
3518
|
return turn.then(
|
|
@@ -3478,7 +3531,7 @@ function registerModelIpc(ipcMain, engine, sessionsDir, aegis, onReplyFinished,
|
|
|
3478
3531
|
// stalling on boot is a fact about the provider, not about this
|
|
3479
3532
|
// app, and saying it in the terminal made a healthy launch read as
|
|
3480
3533
|
// a failure. AEGIS_DEBUG=1 restores the line for diagnosis.
|
|
3481
|
-
if (backgroundLaneLogs()) {
|
|
3534
|
+
if (backgroundLaneLogs(settings)) {
|
|
3482
3535
|
console.warn(
|
|
3483
3536
|
`[model] background ${lane} turn produced no answer: ${errorText(err)}` +
|
|
3484
3537
|
`${status ? ` (status ${status})` : ''}${code ? ` [${code}]` : ''}`
|
|
@@ -5876,7 +5929,8 @@ function bootstrap() {
|
|
|
5876
5929
|
aegis,
|
|
5877
5930
|
handleReplyFinished,
|
|
5878
5931
|
undefined,
|
|
5879
|
-
settingsDir
|
|
5932
|
+
settingsDir,
|
|
5933
|
+
settings
|
|
5880
5934
|
);
|
|
5881
5935
|
|
|
5882
5936
|
// Tool-call approval toggle (Settings → "Confirm before running tools"):
|
|
@@ -5897,6 +5951,10 @@ function bootstrap() {
|
|
|
5897
5951
|
registerConfirmModeIpc(ipcMain, createPermissionModeDispatch(settings));
|
|
5898
5952
|
registerConfirmModeIpc(ipcMain, createFontScaleDispatch(settings));
|
|
5899
5953
|
registerConfirmModeIpc(ipcMain, createAccentDispatch(settings));
|
|
5954
|
+
// Settings → Developer panel: aegis:getDevMode/setDevMode toggle the console
|
|
5955
|
+
// logging backgroundLaneLogs() gates below, aegis:get/setAccountUsername
|
|
5956
|
+
// persist the sign-in slug the panel checks to decide whether to show itself.
|
|
5957
|
+
registerConfirmModeIpc(ipcMain, createDevModeDispatch(settings));
|
|
5900
5958
|
|
|
5901
5959
|
// Vault backend preference (Settings/the authorship panel → Google Drive /
|
|
5902
5960
|
// AE / No sync): aegis:getVaultBackend / aegis:setVaultBackend. Registered
|
|
@@ -6754,6 +6812,7 @@ module.exports = {
|
|
|
6754
6812
|
createQuickLauncherDispatch,
|
|
6755
6813
|
registerQuickLauncherIpc,
|
|
6756
6814
|
createConfirmModeDispatch,
|
|
6815
|
+
createDevModeDispatch,
|
|
6757
6816
|
createVaultBackendDispatch,
|
|
6758
6817
|
createPermRulesDispatch,
|
|
6759
6818
|
createSandboxPolicyDispatch,
|
|
@@ -134,7 +134,7 @@ const UNITS = Object.freeze([
|
|
|
134
134
|
* (`tools/desktop-seal.mjs` in the source tree, `tools/obfuscate-faces.mjs`
|
|
135
135
|
* after obfuscation), never by hand.
|
|
136
136
|
*/
|
|
137
|
-
const SEALED = '
|
|
137
|
+
const SEALED = 'fc6c814a2883e78a441c3bccd268b120013bb8e93aeaf40d5bcd7dbd782408fc';
|
|
138
138
|
|
|
139
139
|
/**
|
|
140
140
|
* Ask the question. Never throws — a check that can break the program it is
|
|
@@ -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",FONT_SCALE_NAMESPACE="__fontScale",ACCENT_NAMESPACE="__accent",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(e){return Number.isFinite(e)?Math.min(1.3,Math.max(.85,Math.round(100*e)/100)):1}function M(){return m((d().__fontScale||{}).scale)}const p=["default","cobalt","amber"];function g(e){const n="string"==typeof e?e.trim().toLowerCase():"";return p.includes(n)?n:"default"}function y(){return g((d().__accent||{}).name)}function N(){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 b(){const e=d().__vaultBackend||{};return{backend:VAULT_BACKEND_VALUES.includes(e.backend)?e.backend:"aegiscloud"}}function v(){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 C(){const e=a().sandboxPolicy;return e&&"object"==typeof e?e:null}function T(){const e=a();return"string"==typeof e.permissionMode?e.permissionMode:null}function h(){return!0===(d().__telemetry||{}).enabled}function R(){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 I(){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 L(){const e=d().__avatar||{};return{...I(),source:void 0===e.enabled?"default":"config"}}function D(e){const n=Number(e);if(!Number.isFinite(n))return 6e4;const t=Math.round(n);return t<15e3||t>18e5?6e4:t}function P(){const e=d().__autoDrain||{};return{enabled:!1!==e.enabled,intervalMs:D(e.intervalMs)}}function O(){const e=d().__autoDrain||{};return{...P(),source:void 0===e.enabled?"default":"config"}}function U(){const e=d().__autoMint||{};return{enabled:!1!==e.enabled,publish:!0===e.publish}}function k(){const e=d().__autoMint||{};return{...U(),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:N,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),N()},vaultBackendConfig:b,setVaultBackendConfig:function(e){if(!VAULT_BACKEND_VALUES.includes(e))return b();const n=d();return n.__vaultBackend={backend:e},f(n),b()},getConfirmMode:function(){return v().enabled},setConfirmMode:function(e){prefs.set({confirmMode:Boolean(e)},{dir:i});const n=d();return void 0!==n.__confirmMode&&(delete n.__confirmMode,f(n)),v().enabled},confirmModeState:v,getFontScale:M,setFontScale:function(e){const n=d();return n.__fontScale={scale:m(e)},f(n),M()},clampFontScale:m,getAccent:y,setAccent:function(e){const n=d();return n.__accent={name:g(e)},f(n),y()},clampAccent:g,ACCENT_SKINS:p,getPermissionMode:T,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}),T()},getSandboxPolicy:C,setSandboxPolicy:function(e){return e&&"object"==typeof e?(prefs.set({sandboxPolicy:e},{dir:i}),C()):(prefs.set({sandboxPolicy:null},{dir:i}),null)},getTelemetryOptIn:h,setTelemetryOptIn:function(e){const n=d();return n.__telemetry={enabled:Boolean(e)},f(n),h()},getMemoryPersist:function(){return R().enabled},memoryPersistState:R,setMemoryPersist:function(e){prefs.set({memoryPersist:Boolean(e)},{dir:i});const n=d();return void 0!==n.__memoryPersist&&(delete n.__memoryPersist,f(n)),R()},getAvatar:I,avatarState:L,setAvatar:function(e={}){const n=I(),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),L()},getAutoDrain:P,autoDrainState:O,setAutoDrain:function(e={}){const n=P(),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:D(t.intervalMs)},f(r),O()},getAutoMint:U,autoMintState:k,setAutoMint:function(e={}){const n=U(),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),k()},clampAutoDrainInterval:D}}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",FONT_SCALE_NAMESPACE="__fontScale",ACCENT_NAMESPACE="__accent",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 l(e){return null==e?null:u()?n.encryptString(String(e)).toString("base64"):Buffer.from(String(e),"utf8").toString("base64")}function _(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=_(n.key);return{provider:e,baseURL:n.baseURL||"",configured:Boolean(t),keyMask:maskKey(t)}}function S(){const e=_((d().__aegis||{}).key);return{configured:Boolean(e),keyMask:maskKey(e)}}function m(e){return Number.isFinite(e)?Math.min(1.3,Math.max(.85,Math.round(100*e)/100)):1}function M(){return m((d().__fontScale||{}).scale)}const p=["default","cobalt","amber"];function g(e){const n="string"==typeof e?e.trim().toLowerCase():"";return p.includes(n)?n:"default"}function y(){return g((d().__accent||{}).name)}function N(){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 b(){const e=d().__vaultBackend||{};return{backend:VAULT_BACKEND_VALUES.includes(e.backend)?e.backend:"aegiscloud"}}function v(){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 C(){const e=a().sandboxPolicy;return e&&"object"==typeof e?e:null}function T(){return!0===a().devMode}function h(){const e=a().accountUsername;return"string"==typeof e?e:null}function R(){const e=a();return"string"==typeof e.permissionMode?e.permissionMode:null}function I(){return!0===(d().__telemetry||{}).enabled}function L(){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 D(){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 P(){const e=d().__avatar||{};return{...D(),source:void 0===e.enabled?"default":"config"}}function O(e){const n=Number(e);if(!Number.isFinite(n))return 6e4;const t=Math.round(n);return t<15e3||t>18e5?6e4:t}function U(){const e=d().__autoDrain||{};return{enabled:!1!==e.enabled,intervalMs:O(e.intervalMs)}}function k(){const e=d().__autoDrain||{};return{...U(),source:void 0===e.enabled?"default":"config"}}function B(){const e=d().__autoMint||{};return{enabled:!1!==e.enabled,publish:!0===e.publish}}function K(){const e=d().__autoMint||{};return{...B(),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)},getDevMode:T,setDevMode:function(e){return prefs.set({devMode:Boolean(e)},{dir:i}),T()},getAccountUsername:h,setAccountUsername:function(e){return prefs.set({accountUsername:"string"==typeof e?e:null},{dir:i}),h()},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?l(t):null),o[e]=i,f(o),E(e)},rawKey:function(e){return _((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 _((d().__aegis||{}).key)},aegisKeySavedAt:function(){return(d().__aegis||{}).savedAt||null},setAegisKey:function(e){const n=d();return n.__aegis={...n.__aegis||{},key:e?l(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:N,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),N()},vaultBackendConfig:b,setVaultBackendConfig:function(e){if(!VAULT_BACKEND_VALUES.includes(e))return b();const n=d();return n.__vaultBackend={backend:e},f(n),b()},getConfirmMode:function(){return v().enabled},setConfirmMode:function(e){prefs.set({confirmMode:Boolean(e)},{dir:i});const n=d();return void 0!==n.__confirmMode&&(delete n.__confirmMode,f(n)),v().enabled},confirmModeState:v,getFontScale:M,setFontScale:function(e){const n=d();return n.__fontScale={scale:m(e)},f(n),M()},clampFontScale:m,getAccent:y,setAccent:function(e){const n=d();return n.__accent={name:g(e)},f(n),y()},clampAccent:g,ACCENT_SKINS:p,getPermissionMode:R,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}),R()},getSandboxPolicy:C,setSandboxPolicy:function(e){return e&&"object"==typeof e?(prefs.set({sandboxPolicy:e},{dir:i}),C()):(prefs.set({sandboxPolicy:null},{dir:i}),null)},getTelemetryOptIn:I,setTelemetryOptIn:function(e){const n=d();return n.__telemetry={enabled:Boolean(e)},f(n),I()},getMemoryPersist:function(){return L().enabled},memoryPersistState:L,setMemoryPersist:function(e){prefs.set({memoryPersist:Boolean(e)},{dir:i});const n=d();return void 0!==n.__memoryPersist&&(delete n.__memoryPersist,f(n)),L()},getAvatar:D,avatarState:P,setAvatar:function(e={}){const n=D(),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),P()},getAutoDrain:U,autoDrainState:k,setAutoDrain:function(e={}){const n=U(),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:O(t.intervalMs)},f(r),k()},getAutoMint:B,autoMintState:K,setAutoMint:function(e={}){const n=B(),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),K()},clampAutoDrainInterval:O}}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};
|