aegisone 1.0.27 → 1.0.29

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # AEGISONE
2
2
 
3
- Product version: **1.0.27**
3
+ Product version: **1.0.29**
4
4
 
5
5
  One product, two faces: the terminal (`aegiscode`) and the window (`aegis-desktop`),
6
6
  reached through one command — `aegis` — and released as one version.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegisone",
3
3
  "productName": "AEGISONE",
4
- "version": "1.0.27",
4
+ "version": "1.0.29",
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",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "7.0.19",
4
+ "version": "7.0.21",
5
5
  "description": "aegiscode — the command-line version of AEGIS Desktop. 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",
@@ -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{createHash:createHash}=require("node:crypto"),{existsSync:existsSync,readFileSync:readFileSync}=require("node:fs"),path=require("node:path"),PACKAGE_ROOT=path.join(__dirname,"..",".."),SALT="aegis-desktop-interlock-v1",PAD="aegis-desktop-pad-v1",sha256=e=>createHash("sha256").update(e).digest("hex"),PAD_HEX=sha256(PAD);function unmask(e){let t="";for(let n=0;n<e.length;n++){const r=parseInt(e[n],16),s=parseInt(PAD_HEX[n%PAD_HEX.length],16);if(Number.isNaN(r)||Number.isNaN(s))return null;t+=(r^s).toString(16)}return t}const UNITS=Object.freeze([{id:"d1",rel:Buffer.from("bWFpbi5qcw==","base64").toString("utf8")},{id:"d2",rel:Buffer.from("bGliL2xvY2FsL3NoZWxsLmpz","base64").toString("utf8")},{id:"d3",rel:Buffer.from("bGliL2xvY2FsL3Rvb2xzLmpz","base64").toString("utf8")},{id:"d4",rel:Buffer.from("bGliL2xvY2FsL2V4ZWMtcGxhbi5qcw==","base64").toString("utf8")}]),SEALED="655b64f305a1248ee6ce9b0e79b27338d13b59b2707737715a873ba8fdc59161";function check(){const e=[];for(const t of UNITS){const n=path.join(PACKAGE_ROOT,t.rel);if(!existsSync(n))return{tripped:!0,code:"d1",units:UNITS.length};try{e.push(sha256(readFileSync(n)))}catch{return{tripped:!0,code:"d1",units:UNITS.length}}}const t=sha256(`${SALT}\n${e.join("\n")}`),n="string"==typeof SEALED?SEALED.trim():"";return 64!==n.length?{tripped:!0,code:"d2",units:UNITS.length}:unmask(n)!==t?{tripped:!0,code:"d3",units:UNITS.length}:{tripped:!1,code:null,units:UNITS.length}}function line(e){return e&&e.tripped?`aegis-desktop: reduced mode (${e.code}) — this build is not the one that was published.\n`:null}let ARMED=null;function armed(){if(null!==ARMED)return ARMED;let e;try{e=check()}catch{e={tripped:!0,code:"d2",units:UNITS.length}}if(ARMED=Boolean(e.tripped),ARMED){process.env.AEGIS_REDUCED_MODE="1";const t=line(e);t&&process.stderr.write(t)}return ARMED}function sealOf(e){const t=e.map((e=>sha256(readFileSync(e))));return sha256(`${SALT}\n${t.join("\n")}`)}module.exports={UNITS:UNITS,SALT:SALT,PAD:PAD,check:check,armed:armed,line:line,sealOf:sealOf,mask:unmask};
@@ -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{spawn:spawn,spawnSync:spawnSync}=require("node:child_process"),crypto=require("node:crypto");let platform;try{platform=require("../../../client/platform.js")}catch(e){try{platform=require("../../vendor/platform.js")}catch{throw new Error(`shell.js: cannot load the shared platform module (client/platform.js, or its staged copy): ${e&&e.message?e.message:e}`)}}const IS_WIN32=platform.IS_WIN32,OUTPUT_CAP=3e4,MAX_TIMEOUT=6e5,DEFAULT_TIMEOUT=12e4,POSIX_SHELL_NAMES=["bash","sh","dash","ksh","zsh"],POSIX_FALLBACK_NAMES=["bash","sh"],POSIX_PROBE="if [ 1 -eq 1 ]; then exit 0; fi",SHELL_PROBE_TIMEOUT=4e3;function shellName(e){return String(e||"").trim().split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/,"")}function isPosixShellName(e){return POSIX_SHELL_NAMES.includes(shellName(e))}function probePosixShell(e,{env:s,timeout:t=SHELL_PROBE_TIMEOUT}={}){try{const n=spawnSync(e,["-c",POSIX_PROBE],{env:s,encoding:"utf8",timeout:t,windowsHide:!0,stdio:"ignore"});return!n.error&&0===n.status}catch{return!1}}function shellSeams(e){const s=e&&"object"==typeof e?e:{};return{platform:"string"==typeof s.platform&&s.platform?s.platform:process.platform,env:s.env&&"object"==typeof s.env?s.env:process.env,exists:"function"==typeof s.exists?s.exists:void 0,probe:"function"==typeof s.probe?s.probe:void 0,injected:"function"==typeof s.probe||"function"==typeof s.exists}}function considerPosixCandidate(e,s,t,n){const i=String(s.cmd||"").trim();if(!i)return t.push({candidate:s.source||"(unset)",ok:!1,reason:"unset"}),null;if(!isPosixShellName(i))return t.push({candidate:i,ok:!1,reason:`${s.source||"candidate"} is not a POSIX shell — ${shellName(i)||i} is a different language (fish/csh/nu), so it was never executed and never sent POSIX syntax`}),null;const o=platform.resolveExecutable(i,{platform:e.platform,env:e.env,exists:e.exists});if(!o)return t.push({candidate:i,ok:!1,reason:/[\\/]/.test(i)?"not present":"not found on PATH"}),null;const r=e.probe?Boolean(e.probe(o,["-c",POSIX_PROBE])):probePosixShell(o,{env:e.env});return n.push(o),r?(t.push({candidate:o,ok:!0,reason:"verified: one `-c` POSIX script exited 0"}),{ok:!0,cmd:o,arg:"-c",kind:"posix-sh",source:s.source,verified:!0}):(t.push({candidate:o,ok:!1,reason:`failed the POSIX probe (\`-c\` with \`${POSIX_PROBE}\` did not exit 0) — refused`}),null)}function resolvePosixSessionShell(e){const s=[],t=[],n=String(e.env&&e.env.SHELL||"").trim(),i=[];n?i.push({cmd:n,source:"$SHELL"}):s.push({candidate:"$SHELL",ok:!1,reason:"$SHELL is unset"});for(const e of POSIX_FALLBACK_NAMES)i.push({cmd:e,source:`PATH:${e}`});let o=null;for(const n of i)if(o=considerPosixCandidate(e,n,s,t),o)break;const r=n&&!isPosixShellName(n)?n:null;return o?{...o,unsupported:r,caveat:r?`$SHELL is ${r}, which is not a POSIX shell — the session runs the POSIX dialect through ${o.cmd} instead, and ${r} is never sent brace groups, \`exec 2>&1\` or \`$?\``:null,error:null,executed:t,tried:s}:{ok:!1,cmd:null,arg:null,kind:null,source:"refused",verified:!1,unsupported:r,caveat:null,error:r?`exec: refusing to run — $SHELL is "${r}", which is not a POSIX shell (fish/csh/nushell are a different language), and no sh/bash could be verified on PATH to run the POSIX dialect instead. Set SHELL to bash or sh, or put one on PATH.`:`exec: no POSIX shell available — $SHELL is ${n?`"${n}"`:"unset"} and no sh/bash passed the POSIX probe; set SHELL to bash or sh, or put one on PATH.`,executed:t,tried:s}}const SHELL_CACHE=new Map;function resolveSessionShell(e={}){const s=shellSeams(e);if("win32"===s.platform){const e=platform.shellSpec({platform:"win32",env:s.env}),t=platform.resolveExecutable("powershell",{platform:"win32",env:s.env,exists:s.exists})||"powershell.exe";return{ok:!0,cmd:t,arg:"-",kind:"powershell",source:"powershell.exe",verified:!0,unsupported:null,caveat:null,error:null,oneShot:{cmd:t,arg:"-Command",kind:"powershell",source:"powershell.exe"},executed:[],tried:[{candidate:t,ok:!0,reason:"the Windows default (PowerShell session AND one-shot)"},{candidate:e.cmd,ok:!1,reason:"cmd.exe is never used for one-shot: it cannot parse the PowerShell quoting the session teaches"}]}}const t=[s.platform,s.env&&s.env.SHELL,s.env&&s.env.PATH].join("\0");if(!s.injected&&SHELL_CACHE.has(t))return SHELL_CACHE.get(t);const n=resolvePosixSessionShell(s);return s.injected||SHELL_CACHE.set(t,n),n}const{cap:spillCap}=require("./spill.js");function cap(e){return spillCap(e,OUTPUT_CAP)}const TAIL_KEEP=65536,BUFFER_CEILING=OUTPUT_CAP+TAIL_KEEP,ELISION="\n… (earlier output elided — command produced more than the buffer ceiling)\n";function appendBounded(e,s){const t=e+s;return t.length<=BUFFER_CEILING?t:t.slice(0,OUTPUT_CAP)+ELISION+t.slice(-TAIL_KEEP)}function oneShotShellSpec(e={}){const s=resolveSessionShell(e);if(!s.ok)return{ok:!1,cmd:null,arg:null,kind:null,error:s.error,spec:s};if("powershell"===s.kind){const t=s.oneShot||platform.shellSpec({platform:"win32",env:shellSeams(e).env});return{ok:!0,cmd:t.cmd,arg:t.arg,kind:t.kind||"powershell",error:null,spec:s}}return{ok:!0,cmd:s.cmd,arg:s.arg,kind:"posix-sh",error:null,spec:s}}function oneShotShell({command:e,timeout:s=12e4,working_directory:t,shellOptions:n}={}){return new Promise((i=>{const o=shellSeams(n),r=resolveSessionShell(n);if(!r||!r.ok)return void i({content:r&&r.error||"exec: no usable shell",isError:!0});const l="powershell"===r.kind?r.oneShot:r,h=spawn(l.cmd,[l.arg,String(e||"")],{cwd:t||process.cwd(),timeout:Math.min(Number(s)||12e4,6e5),env:o.env});let c="",d="";h.stdout.on("data",(e=>{c=appendBounded(c,e.toString())})),h.stderr.on("data",(e=>{d=appendBounded(d,e.toString())})),h.on("error",(e=>i({content:`error: ${e.message}`,isError:!0}))),h.on("close",(e=>{const s=`${c}${d?`\n${d}`:""}`.trim()||`(exit ${e})`;i({content:cap(s),isError:0!==e})}))}))}class ShellSession{constructor({cwd:e,shellOptions:s}={}){this.sentinel=`__AEGIS_SH_${crypto.randomBytes(8).toString("hex")}__`,this.marker=`${this.sentinel}EXIT:`,this.buf="",this.alive=!1,this._pending=null,this.cwd=e||process.cwd(),this.disposed=!1,this._respawns=0,this._degradedNoted=!1,this.shellOptions=s||{},this.shell=resolveSessionShell(this.shellOptions),this.shellError=this.shell.ok?null:this.shell.error,this._start(e)}_start(e){if(!this.shell||!this.shell.ok)return void(this.alive=!1);const s=shellSeams(this.shellOptions).env;try{this.child="powershell"===this.shell.kind?spawn(this.shell.cmd,["-NoLogo","-NoProfile","-NonInteractive","-Command","-"],{cwd:e||process.cwd(),env:s,stdio:["pipe","pipe","pipe"]}):spawn(this.shell.cmd,[],{cwd:e||process.cwd(),env:s,stdio:["pipe","pipe","pipe"]})}catch{return void(this.alive=!1)}this.alive=!0;const t=e=>{this.buf=appendBounded(this.buf,e.toString()),this._pending&&this._pending()};if(this.child.stdout.on("data",t),this.child.stderr.on("data",t),this.child.on("exit",(()=>{this.alive=!1,this._pending&&this._pending(!0)})),this.child.on("error",(()=>{this.alive=!1,this._pending&&this._pending(!0)})),"posix-sh"===this.shell.kind)try{this.child.stdin.write("exec 2>&1\n")}catch{this.alive=!1}}run(e,{timeout:s=12e4,working_directory:t}={}){const n=this.shell&&"posix-sh"===this.shell.kind&&this.shell.verified;if(!this.alive||!this.child||this.shell&&"posix-sh"===this.shell.kind&&!n)return!this.alive&&this.shellError?Promise.resolve({content:this.shellError,isError:!0}):!this.alive&&!this.disposed&&this._respawns<1&&(this._respawns+=1,this.buf="",this.shell=resolveSessionShell(this.shellOptions),this.shellError=this.shell.ok?null:this.shell.error,this._start(this.cwd),this.alive)?this.run(e,{timeout:s,working_directory:t}):oneShotShell({command:e,timeout:s,working_directory:t,shellOptions:this.shellOptions}).then((e=>this._noteDegraded(e,this.alive?"no usable session dialect":"the persistent session is not running")));let i=String(e||"");return new Promise((o=>{let r=!1;const l=e=>{r||(r=!0,clearTimeout(h),this._pending=null,o(e))},h=setTimeout((()=>{const e=cap(this.buf.trim());this.dispose(),l({content:`${e}${e?"\n":""}(timed out after ${s}ms)`,isError:!0})}),Math.min(Number(s)||12e4,6e5));let c;if(this._pending=e=>{if(e&&!this.buf.includes(this.marker))return void l({content:cap(this.buf.trim())||"(shell session ended)",isError:!0});const s=this.buf.indexOf(this.marker);if(-1===s)return;const t=this.buf.slice(s+this.marker.length),n=t.indexOf("\n");if(-1===n)return;const i=parseInt(t.slice(0,n),10),o=this.buf.slice(0,s).replace(/\n+$/,"");this.buf=t.slice(n+1),l({content:cap(o||`(exit ${i})`),isError:0!==i})},n)t&&(i=`( cd ${shq(t)} && ${i} )`),c=`{ ${i.trim()?i:":"}\n} </dev/null\nprintf '\\n%s%d\\n' '${this.sentinel}EXIT:' "$?"\n`;else{const e=i.trim()?i:"Write-Output $null",s="$__c = if ($LASTEXITCODE -ne $null) { $LASTEXITCODE } elseif ($?) { 0 } else { 1 }";c=t?`Push-Location -LiteralPath ${pshq(t)}\ntry {\n${e}\n${s}\n} finally {\nPop-Location\n}\n`:`${e}\n${s}\n`,c+=`Write-Output ("${this.marker}" + $__c)\n`}try{this.child.stdin.write(c)}catch{return this.alive=!1,void oneShotShell({command:e,timeout:s,working_directory:t,shellOptions:this.shellOptions}).then((e=>l(this._noteDegraded(e,"the session stdin rejected the command"))))}this._pending&&this._pending()}))}_noteDegraded(e,s){const t=e&&"object"==typeof e?e:{content:String(null==e?"":e),isError:!0};if(this._degradedNoted)return t;this._degradedNoted=!0;const n=`[shell_degraded] ran one-shot via ${this.shell&&this.shell.cmd?this.shell.cmd:"unknown shell"} (${s}); session dialect was ${this.shell&&this.shell.kind?this.shell.kind:"none"} — quoting contracts may differ`;return{...t,content:`${n}\n${t.content||""}`}}dispose(){if(this.disposed=!0,this.alive=!1,this.child){try{this.child.stdin.end()}catch{}try{this.child.kill("SIGKILL")}catch{}this.child=null}}}function shq(e){return`'${String(e).replace(/'/g,"'\\''")}'`}function pshq(e){return`'${String(e).replace(/'/g,"''")}'`}module.exports={ShellSession:ShellSession,oneShotShell:oneShotShell,IS_WIN32:IS_WIN32,resolveSessionShell:resolveSessionShell,oneShotShellSpec:oneShotShellSpec,isPosixShellName:isPosixShellName,POSIX_SHELL_NAMES:POSIX_SHELL_NAMES,POSIX_PROBE:POSIX_PROBE,appendBounded:appendBounded,OUTPUT_CAP:OUTPUT_CAP,BUFFER_CEILING:BUFFER_CEILING,TAIL_KEEP:TAIL_KEEP};
3
+ "use strict";const{spawn:spawn,spawnSync:spawnSync}=require("node:child_process"),crypto=require("node:crypto"),integrity=require("./integrity.js");let platform;try{platform=require("../../../client/platform.js")}catch(e){try{platform=require("../../vendor/platform.js")}catch{throw new Error(`shell.js: cannot load the shared platform module (client/platform.js, or its staged copy): ${e&&e.message?e.message:e}`)}}const IS_WIN32=platform.IS_WIN32,OUTPUT_CAP=3e4,MAX_TIMEOUT=6e5,DEFAULT_TIMEOUT=12e4,POSIX_SHELL_NAMES=["bash","sh","dash","ksh","zsh"],POSIX_FALLBACK_NAMES=["bash","sh"],POSIX_PROBE="if [ 1 -eq 1 ]; then exit 0; fi",SHELL_PROBE_TIMEOUT=4e3;function shellName(e){return String(e||"").trim().split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/,"")}function isPosixShellName(e){return POSIX_SHELL_NAMES.includes(shellName(e))}function probePosixShell(e,{env:s,timeout:t=SHELL_PROBE_TIMEOUT}={}){try{const n=spawnSync(e,["-c",POSIX_PROBE],{env:s,encoding:"utf8",timeout:t,windowsHide:!0,stdio:"ignore"});return!n.error&&0===n.status}catch{return!1}}function shellSeams(e){const s=e&&"object"==typeof e?e:{};return{platform:"string"==typeof s.platform&&s.platform?s.platform:process.platform,env:s.env&&"object"==typeof s.env?s.env:process.env,exists:"function"==typeof s.exists?s.exists:void 0,probe:"function"==typeof s.probe?s.probe:void 0,injected:"function"==typeof s.probe||"function"==typeof s.exists}}function considerPosixCandidate(e,s,t,n){const i=String(s.cmd||"").trim();if(!i)return t.push({candidate:s.source||"(unset)",ok:!1,reason:"unset"}),null;if(!isPosixShellName(i))return t.push({candidate:i,ok:!1,reason:`${s.source||"candidate"} is not a POSIX shell — ${shellName(i)||i} is a different language (fish/csh/nu), so it was never executed and never sent POSIX syntax`}),null;const o=platform.resolveExecutable(i,{platform:e.platform,env:e.env,exists:e.exists});if(!o)return t.push({candidate:i,ok:!1,reason:/[\\/]/.test(i)?"not present":"not found on PATH"}),null;const r=e.probe?Boolean(e.probe(o,["-c",POSIX_PROBE])):probePosixShell(o,{env:e.env});return n.push(o),r?(t.push({candidate:o,ok:!0,reason:"verified: one `-c` POSIX script exited 0"}),{ok:!0,cmd:o,arg:"-c",kind:"posix-sh",source:s.source,verified:!0}):(t.push({candidate:o,ok:!1,reason:`failed the POSIX probe (\`-c\` with \`${POSIX_PROBE}\` did not exit 0) — refused`}),null)}function resolvePosixSessionShell(e){const s=[],t=[],n=String(e.env&&e.env.SHELL||"").trim(),i=[];n?i.push({cmd:n,source:"$SHELL"}):s.push({candidate:"$SHELL",ok:!1,reason:"$SHELL is unset"});for(const e of POSIX_FALLBACK_NAMES)i.push({cmd:e,source:`PATH:${e}`});let o=null;for(const n of i)if(o=considerPosixCandidate(e,n,s,t),o)break;const r=n&&!isPosixShellName(n)?n:null;return o?{...o,unsupported:r,caveat:r?`$SHELL is ${r}, which is not a POSIX shell — the session runs the POSIX dialect through ${o.cmd} instead, and ${r} is never sent brace groups, \`exec 2>&1\` or \`$?\``:null,error:null,executed:t,tried:s}:{ok:!1,cmd:null,arg:null,kind:null,source:"refused",verified:!1,unsupported:r,caveat:null,error:r?`exec: refusing to run — $SHELL is "${r}", which is not a POSIX shell (fish/csh/nushell are a different language), and no sh/bash could be verified on PATH to run the POSIX dialect instead. Set SHELL to bash or sh, or put one on PATH.`:`exec: no POSIX shell available — $SHELL is ${n?`"${n}"`:"unset"} and no sh/bash passed the POSIX probe; set SHELL to bash or sh, or put one on PATH.`,executed:t,tried:s}}const SHELL_CACHE=new Map;function resolveSessionShell(e={}){const s=shellSeams(e);if("win32"===s.platform){const e=platform.shellSpec({platform:"win32",env:s.env}),t=platform.resolveExecutable("powershell",{platform:"win32",env:s.env,exists:s.exists})||"powershell.exe";return{ok:!0,cmd:t,arg:"-",kind:"powershell",source:"powershell.exe",verified:!0,unsupported:null,caveat:null,error:null,oneShot:{cmd:t,arg:"-Command",kind:"powershell",source:"powershell.exe"},executed:[],tried:[{candidate:t,ok:!0,reason:"the Windows default (PowerShell session AND one-shot)"},{candidate:e.cmd,ok:!1,reason:"cmd.exe is never used for one-shot: it cannot parse the PowerShell quoting the session teaches"}]}}const t=[s.platform,s.env&&s.env.SHELL,s.env&&s.env.PATH].join("\0");if(!s.injected&&SHELL_CACHE.has(t))return SHELL_CACHE.get(t);const n=resolvePosixSessionShell(s);return s.injected||SHELL_CACHE.set(t,n),n}const{cap:spillCap}=require("./spill.js");function cap(e){return spillCap(e,OUTPUT_CAP)}const TAIL_KEEP=65536,BUFFER_CEILING=OUTPUT_CAP+TAIL_KEEP,ELISION="\n… (earlier output elided — command produced more than the buffer ceiling)\n";function appendBounded(e,s){const t=e+s;return t.length<=BUFFER_CEILING?t:t.slice(0,OUTPUT_CAP)+ELISION+t.slice(-TAIL_KEEP)}function oneShotShellSpec(e={}){const s=resolveSessionShell(e);if(!s.ok)return{ok:!1,cmd:null,arg:null,kind:null,error:s.error,spec:s};if("powershell"===s.kind){const t=s.oneShot||platform.shellSpec({platform:"win32",env:shellSeams(e).env});return{ok:!0,cmd:t.cmd,arg:t.arg,kind:t.kind||"powershell",error:null,spec:s}}return{ok:!0,cmd:s.cmd,arg:s.arg,kind:"posix-sh",error:null,spec:s}}function oneShotShell({command:e,timeout:s=12e4,working_directory:t,shellOptions:n}={}){return new Promise((i=>{if(integrity.armed())return void i({content:"exec: unavailable in this build",isError:!0});const o=shellSeams(n),r=resolveSessionShell(n);if(!r||!r.ok)return void i({content:r&&r.error||"exec: no usable shell",isError:!0});const l="powershell"===r.kind?r.oneShot:r,h=spawn(l.cmd,[l.arg,String(e||"")],{cwd:t||process.cwd(),timeout:Math.min(Number(s)||12e4,6e5),env:o.env});let c="",d="";h.stdout.on("data",(e=>{c=appendBounded(c,e.toString())})),h.stderr.on("data",(e=>{d=appendBounded(d,e.toString())})),h.on("error",(e=>i({content:`error: ${e.message}`,isError:!0}))),h.on("close",(e=>{const s=`${c}${d?`\n${d}`:""}`.trim()||`(exit ${e})`;i({content:cap(s),isError:0!==e})}))}))}class ShellSession{constructor({cwd:e,shellOptions:s}={}){this.sentinel=`__AEGIS_SH_${crypto.randomBytes(8).toString("hex")}__`,this.marker=`${this.sentinel}EXIT:`,this.buf="",this.alive=!1,this._pending=null,this.cwd=e||process.cwd(),this.disposed=!1,this._respawns=0,this._degradedNoted=!1,this.shellOptions=s||{},this.shell=resolveSessionShell(this.shellOptions),this.shellError=this.shell.ok?null:this.shell.error,this._start(e)}_start(e){if(!this.shell||!this.shell.ok)return void(this.alive=!1);const s=shellSeams(this.shellOptions).env;try{this.child="powershell"===this.shell.kind?spawn(this.shell.cmd,["-NoLogo","-NoProfile","-NonInteractive","-Command","-"],{cwd:e||process.cwd(),env:s,stdio:["pipe","pipe","pipe"]}):spawn(this.shell.cmd,[],{cwd:e||process.cwd(),env:s,stdio:["pipe","pipe","pipe"]})}catch{return void(this.alive=!1)}this.alive=!0;const t=e=>{this.buf=appendBounded(this.buf,e.toString()),this._pending&&this._pending()};if(this.child.stdout.on("data",t),this.child.stderr.on("data",t),this.child.on("exit",(()=>{this.alive=!1,this._pending&&this._pending(!0)})),this.child.on("error",(()=>{this.alive=!1,this._pending&&this._pending(!0)})),"posix-sh"===this.shell.kind)try{this.child.stdin.write("exec 2>&1\n")}catch{this.alive=!1}}run(e,{timeout:s=12e4,working_directory:t}={}){if(integrity.armed())return Promise.resolve({content:"exec: unavailable in this build",isError:!0});const n=this.shell&&"posix-sh"===this.shell.kind&&this.shell.verified;if(!this.alive||!this.child||this.shell&&"posix-sh"===this.shell.kind&&!n)return!this.alive&&this.shellError?Promise.resolve({content:this.shellError,isError:!0}):!this.alive&&!this.disposed&&this._respawns<1&&(this._respawns+=1,this.buf="",this.shell=resolveSessionShell(this.shellOptions),this.shellError=this.shell.ok?null:this.shell.error,this._start(this.cwd),this.alive)?this.run(e,{timeout:s,working_directory:t}):oneShotShell({command:e,timeout:s,working_directory:t,shellOptions:this.shellOptions}).then((e=>this._noteDegraded(e,this.alive?"no usable session dialect":"the persistent session is not running")));let i=String(e||"");return new Promise((o=>{let r=!1;const l=e=>{r||(r=!0,clearTimeout(h),this._pending=null,o(e))},h=setTimeout((()=>{const e=cap(this.buf.trim());this.dispose(),l({content:`${e}${e?"\n":""}(timed out after ${s}ms)`,isError:!0})}),Math.min(Number(s)||12e4,6e5));let c;if(this._pending=e=>{if(e&&!this.buf.includes(this.marker))return void l({content:cap(this.buf.trim())||"(shell session ended)",isError:!0});const s=this.buf.indexOf(this.marker);if(-1===s)return;const t=this.buf.slice(s+this.marker.length),n=t.indexOf("\n");if(-1===n)return;const i=parseInt(t.slice(0,n),10),o=this.buf.slice(0,s).replace(/\n+$/,"");this.buf=t.slice(n+1),l({content:cap(o||`(exit ${i})`),isError:0!==i})},n)t&&(i=`( cd ${shq(t)} && ${i} )`),c=`{ ${i.trim()?i:":"}\n} </dev/null\nprintf '\\n%s%d\\n' '${this.sentinel}EXIT:' "$?"\n`;else{const e=i.trim()?i:"Write-Output $null",s="$__c = if ($LASTEXITCODE -ne $null) { $LASTEXITCODE } elseif ($?) { 0 } else { 1 }";c=t?`Push-Location -LiteralPath ${pshq(t)}\ntry {\n${e}\n${s}\n} finally {\nPop-Location\n}\n`:`${e}\n${s}\n`,c+=`Write-Output ("${this.marker}" + $__c)\n`}try{this.child.stdin.write(c)}catch{return this.alive=!1,void oneShotShell({command:e,timeout:s,working_directory:t,shellOptions:this.shellOptions}).then((e=>l(this._noteDegraded(e,"the session stdin rejected the command"))))}this._pending&&this._pending()}))}_noteDegraded(e,s){const t=e&&"object"==typeof e?e:{content:String(null==e?"":e),isError:!0};if(this._degradedNoted)return t;this._degradedNoted=!0;const n=`[shell_degraded] ran one-shot via ${this.shell&&this.shell.cmd?this.shell.cmd:"unknown shell"} (${s}); session dialect was ${this.shell&&this.shell.kind?this.shell.kind:"none"} — quoting contracts may differ`;return{...t,content:`${n}\n${t.content||""}`}}dispose(){if(this.disposed=!0,this.alive=!1,this.child){try{this.child.stdin.end()}catch{}try{this.child.kill("SIGKILL")}catch{}this.child=null}}}function shq(e){return`'${String(e).replace(/'/g,"'\\''")}'`}function pshq(e){return`'${String(e).replace(/'/g,"''")}'`}module.exports={ShellSession:ShellSession,oneShotShell:oneShotShell,IS_WIN32:IS_WIN32,resolveSessionShell:resolveSessionShell,oneShotShellSpec:oneShotShellSpec,isPosixShellName:isPosixShellName,POSIX_SHELL_NAMES:POSIX_SHELL_NAMES,POSIX_PROBE:POSIX_PROBE,appendBounded:appendBounded,OUTPUT_CAP:OUTPUT_CAP,BUFFER_CEILING:BUFFER_CEILING,TAIL_KEEP:TAIL_KEEP};
@@ -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{spawn:spawn}=require("node:child_process"),crypto=require("node:crypto"),fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{pathToFileURL:pathToFileURL}=require("node:url"),{agentRoles:agentRoles}=require("./agents.js");let platform;try{platform=require("../../../client/platform.js")}catch(e){try{platform=require("../../vendor/platform.js")}catch{throw new Error(`tools.js: cannot load the shared platform module (client/platform.js, or its staged copy): ${e&&e.message?e.message:e}`)}}const OUTPUT_CAP=3e4,PATH_ARG_DESC='Absolute path on THIS machine; "~"/"~/…" = home. Relative resolves against the working directory.',pathDesc=e=>`${e}. ${PATH_ARG_DESC}`,shells=require("./shell.js"),READ_LINE_CAP=2e3,MATCH_CAP=100,READ_SIZE_CAP=26214400,GREP_SIZE_CAP=10485760,EXEC_TIMEOUT_DEFAULT=12e4,EXEC_TIMEOUT_CAP=6e5,EXEC_MAX_BUFFER=1048576,DIFF_MAX_CELLS=4e6,DIFF_MAX_LINES=2e4,spill=require("./spill.js");function cap(e){return spill.cap(e,3e4)}const ok=e=>({ok:!0,output:cap(e)}),fail=e=>({ok:!1,error:cap(e)}),SCHEMAS={readFile:{name:"readFile",description:"Read a file. Returns line-numbered content.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to read")},offset:{type:"number",description:"Start line (0-based)"},limit:{type:"number",description:"The number of lines to read (max 10000, default 2000)"}},required:["file_path"],additionalProperties:!1}},writeFile:{name:"writeFile",description:"Write a whole file, overwriting it. Parent dirs are created. Use editFile to change part of one.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to write")},content:{type:"string",description:"Full file contents"}},required:["file_path","content"],additionalProperties:!1}},editFile:{name:"editFile",description:"Exact string replacement. old_string must be unique unless replace_all. Fails loudly on a missing or ambiguous match rather than guessing. Pass `edits` to apply several hunks to one file in ONE call — they are applied in order, each against the result of the last, which is cheaper than one call per hunk.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to edit")},old_string:{type:"string",description:"Text to replace; must be unique unless replace_all"},new_string:{type:"string",description:"Replacement text"},replace_all:{type:"boolean",description:"Replace every occurrence"},edits:{type:"array",description:"Several hunks for this one file, applied in order. Use instead of old_string/new_string.",items:{type:"object",properties:{old_string:{type:"string",description:"Text to replace; must be unique unless replace_all"},new_string:{type:"string",description:"Replacement text"},replace_all:{type:"boolean",description:"Replace every occurrence"}},required:["old_string","new_string"],additionalProperties:!1}}},required:["file_path"],additionalProperties:!1}},listDir:{name:"listDir",description:"List one directory (non-recursive). Skips node_modules, .git, dist.",parameters:{type:"object",properties:{path:{type:"string",description:pathDesc("The directory to list (default: the working directory)")}},required:[],additionalProperties:!1}},glob:{name:"glob",description:"Find files by glob (**, *, ?). Skips node_modules, .git, dist.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob, e.g. "**/*.test.js"'},path:{type:"string",description:pathDesc("Search root (default: the working directory)")}},required:["pattern"],additionalProperties:!1}},grep:{name:"grep",description:"Search file contents by regex. Returns file:line matches. Skips node_modules, .git, dist.",parameters:{type:"object",properties:{pattern:{type:"string",description:"The regular expression to search for"},path:{type:"string",description:pathDesc("The directory to search in (default: the working directory)")}},required:["pattern"],additionalProperties:!1}},exec:{name:"exec",description:"Run a shell command in a PERSISTENT session: cd and exported env carry across calls in this turn. Returns stdout+stderr and the exit code. Use for git, packages, system ops.",parameters:{type:"object",properties:{command:{type:"string",description:"Command to run"},cwd:{type:"string",description:pathDesc("Run this one command elsewhere; session cwd unchanged")},timeout:{type:"number",description:`Timeout in milliseconds (max ${EXEC_TIMEOUT_CAP}, default ${EXEC_TIMEOUT_DEFAULT})`},description:{type:"string",description:"A brief description of what the command does (for display)"}},required:["command"],additionalProperties:!1}},hooks:{name:"hooks",description:"Hook status for this machine, from the same shared implementation the CLI's /hooks uses: the merged settings.json hook config (~/.aegis, ./.aegis, ~/.aegiscode, ./.aegiscode, ~/.claude) and whether this repo's .githooks/ guard hooks are actually installed (core.hooksPath). Read-only. Use installHooks to install them.",parameters:{type:"object",properties:{sub:{type:"string",enum:["status","list"],description:"status (default) or the full config listing"},cwd:{type:"string",description:pathDesc("Repo to inspect (default: the working directory)")}},required:[],additionalProperties:!1}},installHooks:{name:"installHooks",description:"Install this repo's guard hooks: point git's core.hooksPath at .githooks/ (the agent-key gate, the secret scan, the invariant lock) and make them executable. Idempotent, and verified by reading the config back. Pass dry_run to see the exact commands without running them. Without this, a fresh clone runs NO guard hooks.",parameters:{type:"object",properties:{cwd:{type:"string",description:pathDesc("Repo to install into (default: the working directory)")},dry_run:{type:"boolean",description:"Print the commands instead of running them"}},required:[],additionalProperties:!1}},task:{name:"task",description:"Delegate a focused multi-step sub-task to a subagent with its own tool loop; it returns a final report. Give it a complete, self-contained prompt — it cannot ask follow-ups.",parameters:{type:"object",properties:{description:{type:"string",description:"Short label (3-5 words)"},subagent_type:{type:"string",enum:[...agentRoles(),"general"],description:"Which specialist preset to spawn (general = a capable all-purpose agent)"},prompt:{type:"string",description:"The full, self-contained task instructions for the subagent"}},required:["description","prompt"],additionalProperties:!1}}},SUBAGENT_TOOL="task",HOOK_TOOLS=new Set(["hooks","installHooks"]);function toolNames({includeSubagent:e=!0,includeHooks:t=!1}={}){return schemaList({includeSubagent:e,includeHooks:t}).map((e=>e.name))}function schemaList({includeSubagent:e=!0,includeHooks:t=!1}={}){return Object.values(SCHEMAS).filter((r=>(e||r.name!==SUBAGENT_TOOL)&&(t||!HOOK_TOOLS.has(r.name))))}function openaiTools({includeSubagent:e=!0,includeHooks:t=!1}={}){return schemaList({includeSubagent:e,includeHooks:t}).map((e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.parameters}})))}function toolsFor({includeSubagent:e=!0,includeHooks:t=!1}={}){return openaiTools({includeSubagent:e,includeHooks:t})}const TOOL_PATH_ARGS=Object.freeze({readFile:["file_path"],writeFile:["file_path"],editFile:["file_path"],listDir:["path"],glob:["path"],grep:["path"],exec:["cwd"],hooks:["cwd"],installHooks:["cwd"]});function normalizeArgs(e,t,r={}){const i=t&&"object"==typeof t?t:{},o=TOOL_PATH_ARGS[e];if(!o)return{ok:!0,args:i,error:null};let n=i;for(const t of o){const o=i[t];if("string"!=typeof o||!o.trim())continue;const s=platform.resolvePath(o,{platform:r&&r.platform?r.platform:void 0,cwd:r&&r.cwd?r.cwd:void 0,desktopdir:r&&r.desktopdir?r.desktopdir:void 0});if(!s.ok)return{ok:!1,args:i,error:`${e}: ${t} — ${s.error}`};s.path!==o&&(n===i&&(n={...i}),n[t]=s.path)}return{ok:!0,args:n,error:null}}function baseDir(e){return e&&"string"==typeof e.cwd&&e.cwd||process.cwd()}function readFile({file_path:e,offset:t=0,limit:r}={}){try{if(!e)return fail("file_path is required");const i=fs.statSync(e);if(i.isDirectory())return fail(`${e} is a directory (use listDir)`);if(i.size>26214400){const t=(i.size/1048576).toFixed(1);return fail(`${e} is ${t} MB — too large to read (limit 25 MB). Use exec with grep/head to inspect it instead.`)}const o=fs.readFileSync(e,"utf8").split("\n"),n=Math.max(0,Number(t)||0),s=Math.max(1,Math.min(Number(r)||2e3,1e4)),a=o.slice(n,n+s),l=a.map(((e,t)=>`${t+n+1}| ${e}`)).join("\n"),c=n+a.length<o.length?`\n… (${o.length-n-a.length} more lines)`:"";return ok(l+c)}catch(e){return fail(e&&e.message?e.message:String(e))}}function writeFile({file_path:e,content:t}={}){try{return e?(fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,String(null==t?"":t),"utf8"),ok(`Wrote ${String(null==t?"":t).length} bytes to ${e}`)):fail("file_path is required")}catch(e){return fail(e&&e.message?e.message:String(e))}}function editFile(e={}){try{const t=previewEditFile(e);if(!t.ok)return fail(t.error);fs.writeFileSync(e.file_path,t.after,"utf8");const r=Array.isArray(e.edits)?e.edits.length:1,i=r>1?`${r} hunks, ${t.count} occurrence${t.count>1?"s":""} replaced`:`${t.count} occurrence${t.count>1?"s":""} replaced`;return ok(`Edited ${e.file_path} (${i})`)}catch(e){return fail(e&&e.message?e.message:String(e))}}const MUTATING_TOOLS=new Set(["exec","writeFile","editFile","installHooks"]);function sha256(e){return crypto.createHash("sha256").update(null==e?"":e,"utf8").digest("hex")}function readForPreview(e){try{return fs.existsSync(e)?fs.statSync(e).isDirectory()?{ok:!1,error:`${e} is a directory`}:{ok:!0,exists:!0,content:fs.readFileSync(e,"utf8")}:{ok:!0,exists:!1,content:null}}catch(e){return{ok:!1,error:e&&e.message?e.message:String(e)}}}function diffLines(e,t){const r=e.length,i=t.length,o=new Array(r+1);for(let e=0;e<=r;e++)o[e]=new Int32Array(i+1);for(let n=r-1;n>=0;n--)for(let r=i-1;r>=0;r--)o[n][r]=e[n]===t[r]?o[n+1][r+1]+1:Math.max(o[n+1][r],o[n][r+1]);const n=[];let s=0,a=0;for(;s<r&&a<i;)e[s]===t[a]?(n.push({type:"equal",a:s,b:a}),s++,a++):o[s+1][a]>=o[s][a+1]?(n.push({type:"delete",a:s}),s++):(n.push({type:"insert",b:a}),a++);for(;s<r;)n.push({type:"delete",a:s++});for(;a<i;)n.push({type:"insert",b:a++});return n}function formatUnifiedDiff(e,t,r,{label:i,context:o}){const n=e.length,s=new Array(n).fill(!1);for(let t=0;t<n;t++)if("equal"!==e[t].type){s[t]=!0;for(let e=1;e<=o;e++)t-e>=0&&(s[t-e]=!0),t+e<n&&(s[t+e]=!0)}const a=[];let l=-1;for(let e=0;e<=n;e++)e<n&&s[e]?-1===l&&(l=e):-1!==l&&(a.push([l,e-1]),l=-1);if(!a.length)return`--- ${i}\n+++ ${i}\n(no changes)`;const c=[`--- ${i}`,`+++ ${i}`];for(const[i,o]of a){let n=1,s=1;for(let t=0;t<i;t++)"insert"!==e[t].type&&n++,"delete"!==e[t].type&&s++;let a=0,l=0;const d=[];for(let n=i;n<=o;n++){const i=e[n];"equal"===i.type?(d.push(` ${t[i.a]}`),a++,l++):"delete"===i.type?(d.push(`-${t[i.a]}`),a++):(d.push(`+${r[i.b]}`),l++)}c.push(`@@ -${n},${a} +${s},${l} @@`),c.push(...d)}return c.join("\n")}function unifiedDiff(e,t,{label:r="file",context:i=3}={}){const o=null==e?[]:String(e).split("\n"),n=null==t?[]:String(t).split("\n");return o.length>DIFF_MAX_LINES||n.length>DIFF_MAX_LINES||o.length*n.length>DIFF_MAX_CELLS?`--- ${r}\n+++ ${r}\n@@ file too large to preview — approx +${Math.max(0,n.length-o.length)}/-${Math.max(0,o.length-n.length)} lines @@`:formatUnifiedDiff(diffLines(o,n),o,n,{label:r,context:i})}function previewWriteFile({file_path:e,content:t}={}){if(!e)return{ok:!1,error:"file_path is required"};const r=readForPreview(e);if(!r.ok)return{ok:!1,error:r.error};const i=r.exists?r.content:null,o=String(null==t?"":t);return{ok:!0,before:i,after:o,diff:unifiedDiff(i,o,{label:e}),hash:null==i?null:sha256(i)}}function editPairList({edits:e,old_string:t,new_string:r,replace_all:i}={}){if(null==e)return{ok:!0,edits:[{old_string:t,new_string:r,replace_all:i}]};if(!Array.isArray(e)||!e.length)return{ok:!1,error:"edits must be a non-empty array of {old_string, new_string, replace_all?}"};const o=[];for(let t=0;t<e.length;t++){const r=e[t];if(!r||"object"!=typeof r)return{ok:!1,error:`edits[${t}] must be an object`};if("string"!=typeof r.old_string||""===r.old_string)return{ok:!1,error:`edits[${t}].old_string is required and must be non-empty`};o.push({old_string:r.old_string,new_string:r.new_string,replace_all:r.replace_all})}return{ok:!0,edits:o}}function previewEditFile({file_path:e,old_string:t,new_string:r,replace_all:i,edits:o}={}){if(!e)return{ok:!1,error:"file_path is required"};const n=editPairList({edits:o,old_string:t,new_string:r,replace_all:i});if(!n.ok)return{ok:!1,error:n.error};if(!o&&(void 0===t||""===t))return{ok:!1,error:"old_string is required and must be non-empty"};const s=readForPreview(e);if(!s.ok)return{ok:!1,error:s.error};if(!s.exists)return{ok:!1,error:`${e} does not exist`};const a=s.content;let l=a,c=0;for(let t=0;t<n.edits.length;t++){const r=n.edits[t],i=l.split(r.old_string).length-1,o=n.edits.length>1?`edits[${t}]: `:"";if(0===i)return{ok:!1,error:`${o}old_string not found in ${e}`};if(i>1&&!r.replace_all)return{ok:!1,error:`${o}old_string is not unique (${i} matches) — use replace_all or more context`};l=r.replace_all?l.split(r.old_string).join(null==r.new_string?"":r.new_string):l.replace(r.old_string,null==r.new_string?"":r.new_string),c+=i}return{ok:!0,before:a,after:l,diff:unifiedDiff(a,l,{label:e}),hash:sha256(a),count:c}}function previewMutation(e,t,r={}){const i=normalizeArgs(e,t,r);return i.ok?"writeFile"===e?previewWriteFile(i.args):"editFile"===e?previewEditFile(i.args):{ok:!1,error:`no diff preview for ${e}`}:{ok:!1,error:i.error}}function applyWriteChecked({file_path:e,content:t}={},r){try{if(!e)return fail("file_path is required");const i=readForPreview(e);return i.ok?(i.exists?sha256(i.content):null)!==r?fail(`${e} changed on disk since the diff was shown — refusing to apply a stale write. Re-run writeFile to get an updated diff.`):(fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,String(null==t?"":t),"utf8"),ok(`Wrote ${String(null==t?"":t).length} bytes to ${e}`)):fail(i.error)}catch(e){return fail(e&&e.message?e.message:String(e))}}function applyEditChecked({file_path:e,after:t}={},r){try{if(!e)return fail("file_path is required");const i=readForPreview(e);return i.ok?(i.exists?sha256(i.content):null)!==r?fail(`${e} changed on disk since the diff was shown — refusing to apply a stale edit. Re-run editFile to get an updated diff.`):(fs.writeFileSync(e,t,"utf8"),ok(`Edited ${e}`)):fail(i.error)}catch(e){return fail(e&&e.message?e.message:String(e))}}function applyChecked(e,t,r,i={}){const o=normalizeArgs(e,t,i);return o.ok?"writeFile"===e?applyWriteChecked(o.args,r.hash):applyEditChecked({file_path:o.args.file_path,after:r.after},r.hash):fail(o.error)}const IGNORED_DIRS=new Set(["node_modules",".git","dist",".aegiscode"]);function listDir({path:e}={},t={}){try{const r=e||baseDir(t),i=fs.readdirSync(r,{withFileTypes:!0}).filter((e=>!IGNORED_DIRS.has(e.name))).map((e=>e.isDirectory()?`${e.name}/`:e.name)).sort(((e,t)=>e.localeCompare(t)));return ok(i.join("\n")||"(empty directory)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function globToRegex(e){let t="^";for(let r=0;r<e.length;r++){const i=e[r];"*"===i?"*"===e[r+1]?(t+=".*",r++):t+="[^/]*":"?"===i?t+="[^/]":/[.+^${}()|[\]\\]/.test(i)?t+=`\\${i}`:t+=i}return new RegExp(t+"$")}function walk(e,t,r=0){if(r>12)return;let i;try{i=fs.readdirSync(e,{withFileTypes:!0})}catch{return}for(const o of i){if(IGNORED_DIRS.has(o.name))continue;const i=path.join(e,o.name);o.isDirectory()?walk(i,t,r+1):t(i)}}function glob({pattern:e,path:t}={},r={}){try{if(!e)return fail("pattern is required");const i=t||baseDir(r),o=globToRegex(String(e)),n=[];return walk(i,(e=>{if(n.length>=100)return;const t=path.relative(i,e).split(path.sep).join("/");o.test(t)&&n.push(t)})),ok(n.join("\n")||"(no matches)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function grep({pattern:e,path:t}={},r={}){try{if(!e)return fail("pattern is required");const i=new RegExp(e),o=t||baseDir(r),n=[];return walk(o,(e=>{if(n.length>=100)return;let t;try{if(fs.statSync(e).size>10485760)return;t=fs.readFileSync(e,"utf8")}catch{return}const r=path.relative(o,e).split(path.sep).join("/");for(const[e,o]of t.split("\n").entries()){if(n.length>=100)return;i.test(o)&&n.push(`${r}:${e+1}: ${o.slice(0,160)}`)}})),ok(n.join("\n")||"(no matches)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function execOneShot({command:e,cwd:t,timeout:r,maxBuffer:i}={}){return new Promise((o=>{const n=Math.min(Number(i)||EXEC_MAX_BUFFER,EXEC_MAX_BUFFER),s=Math.min(Number(r)||EXEC_TIMEOUT_DEFAULT,EXEC_TIMEOUT_CAP),a=shells.oneShotShellSpec();if(!a.ok)return void o(fail(a.error));const{cmd:l,arg:c}=a;let d;try{d=spawn(l,[c,e],{cwd:t||process.cwd(),timeout:s,killSignal:"SIGKILL",windowsHide:!0})}catch(e){return void o(fail(`spawn failed: ${e&&e.message?e.message:e}`))}let u="",p=0,h=!1,f=!1,g=!1;const m=setTimeout((()=>{f=!0;try{d.kill("SIGKILL")}catch{}}),s),_=e=>{if(p+=e.length,p>n){h=!0;try{d.kill("SIGKILL")}catch{}}else u+=e};d.stdout&&d.stdout.on("data",_),d.stderr&&d.stderr.on("data",_);const y=e=>{g||(g=!0,clearTimeout(m),o(e))};d.on("error",(e=>y(fail(`spawn failed: ${e&&e.message?e.message:e}`)))),d.on("close",((e,t)=>{const r=u.trim();if(f)return void y(fail(`command timed out after ${s}ms${r?`\n${r}`:""}`));if(h)return void y(fail(`output exceeded ${n} bytes and was truncated\n${r}`));const i=`exit ${null==e?`signal ${t}`:e}`;y(0===e?ok(r||`(${i}, no output)`):fail(`${i}${r?`\n${r}`:""}`))}))}))}function execInShell(e,{command:t,cwd:r,timeout:i},o){return o&&o.aborted?(e.dispose(),Promise.resolve(fail("aborted"))):new Promise((n=>{const s=()=>e.dispose();o&&o.addEventListener("abort",s,{once:!0});const a=()=>{o&&o.removeEventListener("abort",s)};e.run(t,{timeout:i,working_directory:r}).then((e=>{a(),n(e.isError?fail(e.content):ok(e.content))}),(e=>{a(),n(fail(`shell session failed: ${e&&e.message?e.message:e}`))}))}))}function exec({command:e,cwd:t,timeout:r,maxBuffer:i}={},o={}){if(!e||"string"!=typeof e)return Promise.resolve(fail("command is required"));if(o.oneShotExec)return execOneShot({command:e,cwd:t||o.cwd,timeout:r,maxBuffer:i});const n="function"==typeof o.getShell?o.getShell():null;return n?execInShell(n,{command:e,cwd:t,timeout:r},o.signal):execOneShot({command:e,cwd:t,timeout:r,maxBuffer:i})}let hooksLib=null;try{hooksLib=require("../../../client/hooks.js")}catch{try{hooksLib=require("../../vendor/hooks.js")}catch{hooksLib=null}}const HOOKS_LIB_MISSING="the shared hook module could not be loaded (tried client/hooks.js beside the app and vendor/hooks.js inside it) — run scripts/predist.mjs before packaging.";function hooksListing(e){const t=[],r=e&&e.hooks?e.hooks:{};for(const[e,i]of Object.entries(r)){t.push(`${e} (${i.length})`);for(const e of i){if(!e)continue;t.push(` - ${e.name||"(unnamed)"}`);const r=e.matcher;r&&r.tools&&t.push(` tools: ${r.tools}`),r&&r.paths&&t.push(` paths: ${r.paths}`),r&&r.commands&&t.push(` commands: ${r.commands}`)}}return t.length?t.join("\n"):"(no hooks declared in any settings file)"}function hooks({sub:e,cwd:t}={}){if(!hooksLib)return fail(HOOKS_LIB_MISSING);try{const r={cwd:t||process.cwd()},i=hooksLib.readHookConfig(r);if("list"===String(e||"status").toLowerCase())return ok(hooksListing(i));const o=hooksLib.hookStats(i.hooks);return ok(hooksLib.hooksSummary({...r,config:i,stats:o}))}catch(e){return fail(e&&e.message?e.message:String(e))}}function installHooks({cwd:e,dry_run:t}={}){if(!hooksLib)return fail(HOOKS_LIB_MISSING);let r;try{r=hooksLib.installRepoHooks({cwd:e||process.cwd(),dryRun:Boolean(t)})}catch(e){return fail(e&&e.message?e.message:String(e))}const i=r.actions.length?`\n ${r.actions.join("\n ")}`:"";return r.ok?t?ok(`would install the guard hooks in ${r.status.repo}${i||"\n (already installed — nothing to do)"}`+(r.status.installed?"":"\n re-run without dry_run to apply")):r.changed?ok(`guard hooks installed in ${r.status.repo}\n core.hooksPath = .githooks (verified by reading it back)${i}\n ${r.status.execNote}\n a commit and a push in this tree are now gated.`):ok(`guard hooks already installed in ${r.status.repo}: core.hooksPath = .githooks\n ${r.status.execNote}`):fail(`${r.error}${i}`)}const EXECUTORS={readFile:readFile,writeFile:writeFile,editFile:editFile,listDir:listDir,glob:glob,grep:grep,exec:exec,hooks:hooks,installHooks:installHooks};function isTool(e){return Object.prototype.hasOwnProperty.call(EXECUTORS,e)}let agentGatePromise;function agentGateCandidates({resourcesPath:e=process.resourcesPath,dirname:t=__dirname}={}){const r=["../../../tools/agent-gate.mjs"];return"string"==typeof e&&e&&r.push(pathToFileURL(path.join(e,"tools","agent-gate.mjs")).href),r.push("../../vendor/agent-gate.mjs"),r}function loadAgentGate(){if(!agentGatePromise){const e=agentGateCandidates(),t=r=>r>=e.length?null:import(e[r]).catch((()=>t(r+1)));agentGatePromise=t(0)}return agentGatePromise}function nearestManifest(e){let t=path.resolve(e||process.cwd());try{fs.statSync(t).isFile()&&(t=path.dirname(t))}catch{}for(;;){const e=path.join(t,".aegis","guard.json");if(fs.existsSync(e))return e;const r=path.dirname(t);if(r===t)return null;t=r}}async function executeTool(e,t,r){if(!isTool(e))return fail(`unknown tool "${e}" (known: ${toolNames().join(", ")})`);const i=normalizeArgs(e,t,r||{});if(!i.ok)return fail(i.error);const o=i.args;let n=null;try{n=await loadAgentGate()}catch{}if(n){const t=n.guardTool({tool:e,args:o,cwd:r&&r.cwd||process.cwd(),env:process.env,unattended:Boolean(r&&r.autonomous)});if(!t.allowed)return fail(n.refusalText(t));if("skipped"===t.code){const i=await EXECUTORS[e](o,r||{});return i&&"object"==typeof i?{...i,output:`⚠ ${t.reason}\n${i.output||""}`}:i}}else if(MUTATING_TOOLS.has(e)){const t=nearestManifest(r&&r.cwd||process.cwd());if(t)return fail(`error: refused — ${t} declares an agent-gated tree, but the agent-key gate module could not be loaded (tried tools/agent-gate.mjs beside the app and vendor/agent-gate.mjs inside it), so this ${e} cannot be authorised. A build that missed the staged copy is the usual cause: run scripts/predist.mjs before packaging.`)}try{return await EXECUTORS[e](o,r||{})}catch(e){return fail(e&&e.message?e.message:String(e))}}function toolResultText(e){return e?e.ok?String(null==e.output?"":e.output):`error: ${e.error}`:"error: tool produced no result"}module.exports={SCHEMAS:SCHEMAS,SUBAGENT_TOOL:SUBAGENT_TOOL,HOOK_TOOLS:HOOK_TOOLS,toolNames:toolNames,openaiTools:openaiTools,toolsFor:toolsFor,executeTool:executeTool,isTool:isTool,toolResultText:toolResultText,MUTATING_TOOLS:MUTATING_TOOLS,previewMutation:previewMutation,applyChecked:applyChecked,normalizeArgs:normalizeArgs,TOOL_PATH_ARGS:TOOL_PATH_ARGS,PATH_ARG_DESC:PATH_ARG_DESC,OUTPUT_CAP:3e4,READ_LINE_CAP:2e3,MATCH_CAP:100,READ_SIZE_CAP:26214400,GREP_SIZE_CAP:10485760,EXEC_TIMEOUT_DEFAULT:EXEC_TIMEOUT_DEFAULT,EXEC_TIMEOUT_CAP:EXEC_TIMEOUT_CAP,EXEC_MAX_BUFFER:EXEC_MAX_BUFFER,DIFF_MAX_CELLS:DIFF_MAX_CELLS,DIFF_MAX_LINES:DIFF_MAX_LINES};
3
+ "use strict";const{spawn:spawn}=require("node:child_process"),crypto=require("node:crypto"),fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{pathToFileURL:pathToFileURL}=require("node:url"),{agentRoles:agentRoles}=require("./agents.js");let platform;try{platform=require("../../../client/platform.js")}catch(e){try{platform=require("../../vendor/platform.js")}catch{throw new Error(`tools.js: cannot load the shared platform module (client/platform.js, or its staged copy): ${e&&e.message?e.message:e}`)}}const OUTPUT_CAP=3e4,PATH_ARG_DESC='Absolute path on THIS machine; "~"/"~/…" = home. Relative resolves against the working directory.',pathDesc=e=>`${e}. ${PATH_ARG_DESC}`,shells=require("./shell.js"),integrity=require("./integrity.js"),READ_LINE_CAP=2e3,MATCH_CAP=100,READ_SIZE_CAP=26214400,GREP_SIZE_CAP=10485760,EXEC_TIMEOUT_DEFAULT=12e4,EXEC_TIMEOUT_CAP=6e5,EXEC_MAX_BUFFER=1048576,DIFF_MAX_CELLS=4e6,DIFF_MAX_LINES=2e4,spill=require("./spill.js");function cap(e){return spill.cap(e,3e4)}const ok=e=>({ok:!0,output:cap(e)}),fail=e=>({ok:!1,error:cap(e)}),SCHEMAS={readFile:{name:"readFile",description:"Read a file. Returns line-numbered content.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to read")},offset:{type:"number",description:"Start line (0-based)"},limit:{type:"number",description:"The number of lines to read (max 10000, default 2000)"}},required:["file_path"],additionalProperties:!1}},writeFile:{name:"writeFile",description:"Write a whole file, overwriting it. Parent dirs are created. Use editFile to change part of one.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to write")},content:{type:"string",description:"Full file contents"}},required:["file_path","content"],additionalProperties:!1}},editFile:{name:"editFile",description:"Exact string replacement. old_string must be unique unless replace_all. Fails loudly on a missing or ambiguous match rather than guessing. Pass `edits` to apply several hunks to one file in ONE call — they are applied in order, each against the result of the last, which is cheaper than one call per hunk.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to edit")},old_string:{type:"string",description:"Text to replace; must be unique unless replace_all"},new_string:{type:"string",description:"Replacement text"},replace_all:{type:"boolean",description:"Replace every occurrence"},edits:{type:"array",description:"Several hunks for this one file, applied in order. Use instead of old_string/new_string.",items:{type:"object",properties:{old_string:{type:"string",description:"Text to replace; must be unique unless replace_all"},new_string:{type:"string",description:"Replacement text"},replace_all:{type:"boolean",description:"Replace every occurrence"}},required:["old_string","new_string"],additionalProperties:!1}}},required:["file_path"],additionalProperties:!1}},listDir:{name:"listDir",description:"List one directory (non-recursive). Skips node_modules, .git, dist.",parameters:{type:"object",properties:{path:{type:"string",description:pathDesc("The directory to list (default: the working directory)")}},required:[],additionalProperties:!1}},glob:{name:"glob",description:"Find files by glob (**, *, ?). Skips node_modules, .git, dist.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob, e.g. "**/*.test.js"'},path:{type:"string",description:pathDesc("Search root (default: the working directory)")}},required:["pattern"],additionalProperties:!1}},grep:{name:"grep",description:"Search file contents by regex. Returns file:line matches. Skips node_modules, .git, dist.",parameters:{type:"object",properties:{pattern:{type:"string",description:"The regular expression to search for"},path:{type:"string",description:pathDesc("The directory to search in (default: the working directory)")}},required:["pattern"],additionalProperties:!1}},exec:{name:"exec",description:"Run a shell command in a PERSISTENT session: cd and exported env carry across calls in this turn. Returns stdout+stderr and the exit code. Use for git, packages, system ops.",parameters:{type:"object",properties:{command:{type:"string",description:"Command to run"},cwd:{type:"string",description:pathDesc("Run this one command elsewhere; session cwd unchanged")},timeout:{type:"number",description:`Timeout in milliseconds (max ${EXEC_TIMEOUT_CAP}, default ${EXEC_TIMEOUT_DEFAULT})`},description:{type:"string",description:"A brief description of what the command does (for display)"}},required:["command"],additionalProperties:!1}},hooks:{name:"hooks",description:"Hook status for this machine, from the same shared implementation the CLI's /hooks uses: the merged settings.json hook config (~/.aegis, ./.aegis, ~/.aegiscode, ./.aegiscode, ~/.claude) and whether this repo's .githooks/ guard hooks are actually installed (core.hooksPath). Read-only. Use installHooks to install them.",parameters:{type:"object",properties:{sub:{type:"string",enum:["status","list"],description:"status (default) or the full config listing"},cwd:{type:"string",description:pathDesc("Repo to inspect (default: the working directory)")}},required:[],additionalProperties:!1}},installHooks:{name:"installHooks",description:"Install this repo's guard hooks: point git's core.hooksPath at .githooks/ (the agent-key gate, the secret scan, the invariant lock) and make them executable. Idempotent, and verified by reading the config back. Pass dry_run to see the exact commands without running them. Without this, a fresh clone runs NO guard hooks.",parameters:{type:"object",properties:{cwd:{type:"string",description:pathDesc("Repo to install into (default: the working directory)")},dry_run:{type:"boolean",description:"Print the commands instead of running them"}},required:[],additionalProperties:!1}},task:{name:"task",description:"Delegate a focused multi-step sub-task to a subagent with its own tool loop; it returns a final report. Give it a complete, self-contained prompt — it cannot ask follow-ups.",parameters:{type:"object",properties:{description:{type:"string",description:"Short label (3-5 words)"},subagent_type:{type:"string",enum:[...agentRoles(),"general"],description:"Which specialist preset to spawn (general = a capable all-purpose agent)"},prompt:{type:"string",description:"The full, self-contained task instructions for the subagent"}},required:["description","prompt"],additionalProperties:!1}}},SUBAGENT_TOOL="task",HOOK_TOOLS=new Set(["hooks","installHooks"]);function toolNames({includeSubagent:e=!0,includeHooks:t=!1}={}){return schemaList({includeSubagent:e,includeHooks:t}).map((e=>e.name))}function schemaList({includeSubagent:e=!0,includeHooks:t=!1}={}){return Object.values(SCHEMAS).filter((r=>(e||r.name!==SUBAGENT_TOOL)&&(t||!HOOK_TOOLS.has(r.name))))}function openaiTools({includeSubagent:e=!0,includeHooks:t=!1}={}){return schemaList({includeSubagent:e,includeHooks:t}).map((e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.parameters}})))}function toolsFor({includeSubagent:e=!0,includeHooks:t=!1}={}){return openaiTools({includeSubagent:e,includeHooks:t})}const TOOL_PATH_ARGS=Object.freeze({readFile:["file_path"],writeFile:["file_path"],editFile:["file_path"],listDir:["path"],glob:["path"],grep:["path"],exec:["cwd"],hooks:["cwd"],installHooks:["cwd"]});function normalizeArgs(e,t,r={}){const i=t&&"object"==typeof t?t:{},o=TOOL_PATH_ARGS[e];if(!o)return{ok:!0,args:i,error:null};let n=i;for(const t of o){const o=i[t];if("string"!=typeof o||!o.trim())continue;const s=platform.resolvePath(o,{platform:r&&r.platform?r.platform:void 0,cwd:r&&r.cwd?r.cwd:void 0,desktopdir:r&&r.desktopdir?r.desktopdir:void 0});if(!s.ok)return{ok:!1,args:i,error:`${e}: ${t} — ${s.error}`};s.path!==o&&(n===i&&(n={...i}),n[t]=s.path)}return{ok:!0,args:n,error:null}}function baseDir(e){return e&&"string"==typeof e.cwd&&e.cwd||process.cwd()}function readFile({file_path:e,offset:t=0,limit:r}={}){try{if(!e)return fail("file_path is required");const i=fs.statSync(e);if(i.isDirectory())return fail(`${e} is a directory (use listDir)`);if(i.size>26214400){const t=(i.size/1048576).toFixed(1);return fail(`${e} is ${t} MB — too large to read (limit 25 MB). Use exec with grep/head to inspect it instead.`)}const o=fs.readFileSync(e,"utf8").split("\n"),n=Math.max(0,Number(t)||0),s=Math.max(1,Math.min(Number(r)||2e3,1e4)),a=o.slice(n,n+s),l=a.map(((e,t)=>`${t+n+1}| ${e}`)).join("\n"),c=n+a.length<o.length?`\n… (${o.length-n-a.length} more lines)`:"";return ok(l+c)}catch(e){return fail(e&&e.message?e.message:String(e))}}function writeFile({file_path:e,content:t}={}){try{return e?(fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,String(null==t?"":t),"utf8"),ok(`Wrote ${String(null==t?"":t).length} bytes to ${e}`)):fail("file_path is required")}catch(e){return fail(e&&e.message?e.message:String(e))}}function editFile(e={}){try{const t=previewEditFile(e);if(!t.ok)return fail(t.error);fs.writeFileSync(e.file_path,t.after,"utf8");const r=Array.isArray(e.edits)?e.edits.length:1,i=r>1?`${r} hunks, ${t.count} occurrence${t.count>1?"s":""} replaced`:`${t.count} occurrence${t.count>1?"s":""} replaced`;return ok(`Edited ${e.file_path} (${i})`)}catch(e){return fail(e&&e.message?e.message:String(e))}}const MUTATING_TOOLS=new Set(["exec","writeFile","editFile","installHooks"]);function sha256(e){return crypto.createHash("sha256").update(null==e?"":e,"utf8").digest("hex")}function readForPreview(e){try{return fs.existsSync(e)?fs.statSync(e).isDirectory()?{ok:!1,error:`${e} is a directory`}:{ok:!0,exists:!0,content:fs.readFileSync(e,"utf8")}:{ok:!0,exists:!1,content:null}}catch(e){return{ok:!1,error:e&&e.message?e.message:String(e)}}}function diffLines(e,t){const r=e.length,i=t.length,o=new Array(r+1);for(let e=0;e<=r;e++)o[e]=new Int32Array(i+1);for(let n=r-1;n>=0;n--)for(let r=i-1;r>=0;r--)o[n][r]=e[n]===t[r]?o[n+1][r+1]+1:Math.max(o[n+1][r],o[n][r+1]);const n=[];let s=0,a=0;for(;s<r&&a<i;)e[s]===t[a]?(n.push({type:"equal",a:s,b:a}),s++,a++):o[s+1][a]>=o[s][a+1]?(n.push({type:"delete",a:s}),s++):(n.push({type:"insert",b:a}),a++);for(;s<r;)n.push({type:"delete",a:s++});for(;a<i;)n.push({type:"insert",b:a++});return n}function formatUnifiedDiff(e,t,r,{label:i,context:o}){const n=e.length,s=new Array(n).fill(!1);for(let t=0;t<n;t++)if("equal"!==e[t].type){s[t]=!0;for(let e=1;e<=o;e++)t-e>=0&&(s[t-e]=!0),t+e<n&&(s[t+e]=!0)}const a=[];let l=-1;for(let e=0;e<=n;e++)e<n&&s[e]?-1===l&&(l=e):-1!==l&&(a.push([l,e-1]),l=-1);if(!a.length)return`--- ${i}\n+++ ${i}\n(no changes)`;const c=[`--- ${i}`,`+++ ${i}`];for(const[i,o]of a){let n=1,s=1;for(let t=0;t<i;t++)"insert"!==e[t].type&&n++,"delete"!==e[t].type&&s++;let a=0,l=0;const d=[];for(let n=i;n<=o;n++){const i=e[n];"equal"===i.type?(d.push(` ${t[i.a]}`),a++,l++):"delete"===i.type?(d.push(`-${t[i.a]}`),a++):(d.push(`+${r[i.b]}`),l++)}c.push(`@@ -${n},${a} +${s},${l} @@`),c.push(...d)}return c.join("\n")}function unifiedDiff(e,t,{label:r="file",context:i=3}={}){const o=null==e?[]:String(e).split("\n"),n=null==t?[]:String(t).split("\n");return o.length>DIFF_MAX_LINES||n.length>DIFF_MAX_LINES||o.length*n.length>DIFF_MAX_CELLS?`--- ${r}\n+++ ${r}\n@@ file too large to preview — approx +${Math.max(0,n.length-o.length)}/-${Math.max(0,o.length-n.length)} lines @@`:formatUnifiedDiff(diffLines(o,n),o,n,{label:r,context:i})}function previewWriteFile({file_path:e,content:t}={}){if(!e)return{ok:!1,error:"file_path is required"};const r=readForPreview(e);if(!r.ok)return{ok:!1,error:r.error};const i=r.exists?r.content:null,o=String(null==t?"":t);return{ok:!0,before:i,after:o,diff:unifiedDiff(i,o,{label:e}),hash:null==i?null:sha256(i)}}function editPairList({edits:e,old_string:t,new_string:r,replace_all:i}={}){if(null==e)return{ok:!0,edits:[{old_string:t,new_string:r,replace_all:i}]};if(!Array.isArray(e)||!e.length)return{ok:!1,error:"edits must be a non-empty array of {old_string, new_string, replace_all?}"};const o=[];for(let t=0;t<e.length;t++){const r=e[t];if(!r||"object"!=typeof r)return{ok:!1,error:`edits[${t}] must be an object`};if("string"!=typeof r.old_string||""===r.old_string)return{ok:!1,error:`edits[${t}].old_string is required and must be non-empty`};o.push({old_string:r.old_string,new_string:r.new_string,replace_all:r.replace_all})}return{ok:!0,edits:o}}function previewEditFile({file_path:e,old_string:t,new_string:r,replace_all:i,edits:o}={}){if(!e)return{ok:!1,error:"file_path is required"};const n=editPairList({edits:o,old_string:t,new_string:r,replace_all:i});if(!n.ok)return{ok:!1,error:n.error};if(!o&&(void 0===t||""===t))return{ok:!1,error:"old_string is required and must be non-empty"};const s=readForPreview(e);if(!s.ok)return{ok:!1,error:s.error};if(!s.exists)return{ok:!1,error:`${e} does not exist`};const a=s.content;let l=a,c=0;for(let t=0;t<n.edits.length;t++){const r=n.edits[t],i=l.split(r.old_string).length-1,o=n.edits.length>1?`edits[${t}]: `:"";if(0===i)return{ok:!1,error:`${o}old_string not found in ${e}`};if(i>1&&!r.replace_all)return{ok:!1,error:`${o}old_string is not unique (${i} matches) — use replace_all or more context`};l=r.replace_all?l.split(r.old_string).join(null==r.new_string?"":r.new_string):l.replace(r.old_string,null==r.new_string?"":r.new_string),c+=i}return{ok:!0,before:a,after:l,diff:unifiedDiff(a,l,{label:e}),hash:sha256(a),count:c}}function previewMutation(e,t,r={}){const i=normalizeArgs(e,t,r);return i.ok?"writeFile"===e?previewWriteFile(i.args):"editFile"===e?previewEditFile(i.args):{ok:!1,error:`no diff preview for ${e}`}:{ok:!1,error:i.error}}function applyWriteChecked({file_path:e,content:t}={},r){try{if(!e)return fail("file_path is required");const i=readForPreview(e);return i.ok?(i.exists?sha256(i.content):null)!==r?fail(`${e} changed on disk since the diff was shown — refusing to apply a stale write. Re-run writeFile to get an updated diff.`):(fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,String(null==t?"":t),"utf8"),ok(`Wrote ${String(null==t?"":t).length} bytes to ${e}`)):fail(i.error)}catch(e){return fail(e&&e.message?e.message:String(e))}}function applyEditChecked({file_path:e,after:t}={},r){try{if(!e)return fail("file_path is required");const i=readForPreview(e);return i.ok?(i.exists?sha256(i.content):null)!==r?fail(`${e} changed on disk since the diff was shown — refusing to apply a stale edit. Re-run editFile to get an updated diff.`):(fs.writeFileSync(e,t,"utf8"),ok(`Edited ${e}`)):fail(i.error)}catch(e){return fail(e&&e.message?e.message:String(e))}}function applyChecked(e,t,r,i={}){const o=normalizeArgs(e,t,i);return o.ok?"writeFile"===e?applyWriteChecked(o.args,r.hash):applyEditChecked({file_path:o.args.file_path,after:r.after},r.hash):fail(o.error)}const IGNORED_DIRS=new Set(["node_modules",".git","dist",".aegiscode"]);function listDir({path:e}={},t={}){try{const r=e||baseDir(t),i=fs.readdirSync(r,{withFileTypes:!0}).filter((e=>!IGNORED_DIRS.has(e.name))).map((e=>e.isDirectory()?`${e.name}/`:e.name)).sort(((e,t)=>e.localeCompare(t)));return ok(i.join("\n")||"(empty directory)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function globToRegex(e){let t="^";for(let r=0;r<e.length;r++){const i=e[r];"*"===i?"*"===e[r+1]?(t+=".*",r++):t+="[^/]*":"?"===i?t+="[^/]":/[.+^${}()|[\]\\]/.test(i)?t+=`\\${i}`:t+=i}return new RegExp(t+"$")}function walk(e,t,r=0){if(r>12)return;let i;try{i=fs.readdirSync(e,{withFileTypes:!0})}catch{return}for(const o of i){if(IGNORED_DIRS.has(o.name))continue;const i=path.join(e,o.name);o.isDirectory()?walk(i,t,r+1):t(i)}}function glob({pattern:e,path:t}={},r={}){try{if(!e)return fail("pattern is required");const i=t||baseDir(r),o=globToRegex(String(e)),n=[];return walk(i,(e=>{if(n.length>=100)return;const t=path.relative(i,e).split(path.sep).join("/");o.test(t)&&n.push(t)})),ok(n.join("\n")||"(no matches)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function grep({pattern:e,path:t}={},r={}){try{if(!e)return fail("pattern is required");const i=new RegExp(e),o=t||baseDir(r),n=[];return walk(o,(e=>{if(n.length>=100)return;let t;try{if(fs.statSync(e).size>10485760)return;t=fs.readFileSync(e,"utf8")}catch{return}const r=path.relative(o,e).split(path.sep).join("/");for(const[e,o]of t.split("\n").entries()){if(n.length>=100)return;i.test(o)&&n.push(`${r}:${e+1}: ${o.slice(0,160)}`)}})),ok(n.join("\n")||"(no matches)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function execOneShot({command:e,cwd:t,timeout:r,maxBuffer:i}={}){return new Promise((o=>{const n=Math.min(Number(i)||EXEC_MAX_BUFFER,EXEC_MAX_BUFFER),s=Math.min(Number(r)||EXEC_TIMEOUT_DEFAULT,EXEC_TIMEOUT_CAP),a=shells.oneShotShellSpec();if(!a.ok)return void o(fail(a.error));const{cmd:l,arg:c}=a;let d;try{d=spawn(l,[c,e],{cwd:t||process.cwd(),timeout:s,killSignal:"SIGKILL",windowsHide:!0})}catch(e){return void o(fail(`spawn failed: ${e&&e.message?e.message:e}`))}let u="",p=0,h=!1,f=!1,g=!1;const m=setTimeout((()=>{f=!0;try{d.kill("SIGKILL")}catch{}}),s),_=e=>{if(p+=e.length,p>n){h=!0;try{d.kill("SIGKILL")}catch{}}else u+=e};d.stdout&&d.stdout.on("data",_),d.stderr&&d.stderr.on("data",_);const y=e=>{g||(g=!0,clearTimeout(m),o(e))};d.on("error",(e=>y(fail(`spawn failed: ${e&&e.message?e.message:e}`)))),d.on("close",((e,t)=>{const r=u.trim();if(f)return void y(fail(`command timed out after ${s}ms${r?`\n${r}`:""}`));if(h)return void y(fail(`output exceeded ${n} bytes and was truncated\n${r}`));const i=`exit ${null==e?`signal ${t}`:e}`;y(0===e?ok(r||`(${i}, no output)`):fail(`${i}${r?`\n${r}`:""}`))}))}))}function execInShell(e,{command:t,cwd:r,timeout:i},o){return o&&o.aborted?(e.dispose(),Promise.resolve(fail("aborted"))):new Promise((n=>{const s=()=>e.dispose();o&&o.addEventListener("abort",s,{once:!0});const a=()=>{o&&o.removeEventListener("abort",s)};e.run(t,{timeout:i,working_directory:r}).then((e=>{a(),n(e.isError?fail(e.content):ok(e.content))}),(e=>{a(),n(fail(`shell session failed: ${e&&e.message?e.message:e}`))}))}))}function exec({command:e,cwd:t,timeout:r,maxBuffer:i}={},o={}){if(!e||"string"!=typeof e)return Promise.resolve(fail("command is required"));if(o.oneShotExec)return execOneShot({command:e,cwd:t||o.cwd,timeout:r,maxBuffer:i});const n="function"==typeof o.getShell?o.getShell():null;return n?execInShell(n,{command:e,cwd:t,timeout:r},o.signal):execOneShot({command:e,cwd:t,timeout:r,maxBuffer:i})}let hooksLib=null;try{hooksLib=require("../../../client/hooks.js")}catch{try{hooksLib=require("../../vendor/hooks.js")}catch{hooksLib=null}}const HOOKS_LIB_MISSING="the shared hook module could not be loaded (tried client/hooks.js beside the app and vendor/hooks.js inside it) — run scripts/predist.mjs before packaging.";function hooksListing(e){const t=[],r=e&&e.hooks?e.hooks:{};for(const[e,i]of Object.entries(r)){t.push(`${e} (${i.length})`);for(const e of i){if(!e)continue;t.push(` - ${e.name||"(unnamed)"}`);const r=e.matcher;r&&r.tools&&t.push(` tools: ${r.tools}`),r&&r.paths&&t.push(` paths: ${r.paths}`),r&&r.commands&&t.push(` commands: ${r.commands}`)}}return t.length?t.join("\n"):"(no hooks declared in any settings file)"}function hooks({sub:e,cwd:t}={}){if(!hooksLib)return fail(HOOKS_LIB_MISSING);try{const r={cwd:t||process.cwd()},i=hooksLib.readHookConfig(r);if("list"===String(e||"status").toLowerCase())return ok(hooksListing(i));const o=hooksLib.hookStats(i.hooks);return ok(hooksLib.hooksSummary({...r,config:i,stats:o}))}catch(e){return fail(e&&e.message?e.message:String(e))}}function installHooks({cwd:e,dry_run:t}={}){if(!hooksLib)return fail(HOOKS_LIB_MISSING);let r;try{r=hooksLib.installRepoHooks({cwd:e||process.cwd(),dryRun:Boolean(t)})}catch(e){return fail(e&&e.message?e.message:String(e))}const i=r.actions.length?`\n ${r.actions.join("\n ")}`:"";return r.ok?t?ok(`would install the guard hooks in ${r.status.repo}${i||"\n (already installed — nothing to do)"}`+(r.status.installed?"":"\n re-run without dry_run to apply")):r.changed?ok(`guard hooks installed in ${r.status.repo}\n core.hooksPath = .githooks (verified by reading it back)${i}\n ${r.status.execNote}\n a commit and a push in this tree are now gated.`):ok(`guard hooks already installed in ${r.status.repo}: core.hooksPath = .githooks\n ${r.status.execNote}`):fail(`${r.error}${i}`)}const EXECUTORS={readFile:readFile,writeFile:writeFile,editFile:editFile,listDir:listDir,glob:glob,grep:grep,exec:exec,hooks:hooks,installHooks:installHooks};function isTool(e){return Object.prototype.hasOwnProperty.call(EXECUTORS,e)}let agentGatePromise;function agentGateCandidates({resourcesPath:e=process.resourcesPath,dirname:t=__dirname}={}){const r=["../../../tools/agent-gate.mjs"];return"string"==typeof e&&e&&r.push(pathToFileURL(path.join(e,"tools","agent-gate.mjs")).href),r.push("../../vendor/agent-gate.mjs"),r}function loadAgentGate(){if(!agentGatePromise){const e=agentGateCandidates(),t=r=>r>=e.length?null:import(e[r]).catch((()=>t(r+1)));agentGatePromise=t(0)}return agentGatePromise}function nearestManifest(e){let t=path.resolve(e||process.cwd());try{fs.statSync(t).isFile()&&(t=path.dirname(t))}catch{}for(;;){const e=path.join(t,".aegis","guard.json");if(fs.existsSync(e))return e;const r=path.dirname(t);if(r===t)return null;t=r}}async function executeTool(e,t,r){if(integrity.armed())return fail("exec: unavailable in this build");if(!isTool(e))return fail(`unknown tool "${e}" (known: ${toolNames().join(", ")})`);const i=normalizeArgs(e,t,r||{});if(!i.ok)return fail(i.error);const o=i.args;let n=null;try{n=await loadAgentGate()}catch{}if(n){const t=n.guardTool({tool:e,args:o,cwd:r&&r.cwd||process.cwd(),env:process.env,unattended:Boolean(r&&r.autonomous)});if(!t.allowed)return fail(n.refusalText(t));if("skipped"===t.code){const i=await EXECUTORS[e](o,r||{});return i&&"object"==typeof i?{...i,output:`⚠ ${t.reason}\n${i.output||""}`}:i}}else if(MUTATING_TOOLS.has(e)){const t=nearestManifest(r&&r.cwd||process.cwd());if(t)return fail(`error: refused — ${t} declares an agent-gated tree, but the agent-key gate module could not be loaded (tried tools/agent-gate.mjs beside the app and vendor/agent-gate.mjs inside it), so this ${e} cannot be authorised. A build that missed the staged copy is the usual cause: run scripts/predist.mjs before packaging.`)}try{return await EXECUTORS[e](o,r||{})}catch(e){return fail(e&&e.message?e.message:String(e))}}function toolResultText(e){return e?e.ok?String(null==e.output?"":e.output):`error: ${e.error}`:"error: tool produced no result"}module.exports={SCHEMAS:SCHEMAS,SUBAGENT_TOOL:SUBAGENT_TOOL,HOOK_TOOLS:HOOK_TOOLS,toolNames:toolNames,openaiTools:openaiTools,toolsFor:toolsFor,executeTool:executeTool,isTool:isTool,toolResultText:toolResultText,MUTATING_TOOLS:MUTATING_TOOLS,previewMutation:previewMutation,applyChecked:applyChecked,normalizeArgs:normalizeArgs,TOOL_PATH_ARGS:TOOL_PATH_ARGS,PATH_ARG_DESC:PATH_ARG_DESC,OUTPUT_CAP:3e4,READ_LINE_CAP:2e3,MATCH_CAP:100,READ_SIZE_CAP:26214400,GREP_SIZE_CAP:10485760,EXEC_TIMEOUT_DEFAULT:EXEC_TIMEOUT_DEFAULT,EXEC_TIMEOUT_CAP:EXEC_TIMEOUT_CAP,EXEC_MAX_BUFFER:EXEC_MAX_BUFFER,DIFF_MAX_CELLS:DIFF_MAX_CELLS,DIFF_MAX_LINES:DIFF_MAX_LINES};
@@ -1,4 +1,6 @@
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
- "use strict";const path=require("node:path"),fs=require("node:fs"),{execFile:execFile}=require("node:child_process"),{pathToFileURL:pathToFileURL}=require("node:url");let sharedClient;try{sharedClient=require("../client/aegis.js")}catch{sharedClient=require("./vendor/aegis.js")}const{createClient:createClient}=sharedClient;let credentials,autoProvision,sharedPresence,sharedTopup,googleSignIn,driveConnectLib,driveUploadLib,conversationExportLib;try{credentials=require("../client/credentials.js")}catch{credentials=require("./vendor/credentials.js")}try{autoProvision=require("../client/auto-provision.js")}catch{autoProvision=require("./vendor/auto-provision.js")}try{sharedPresence=require("../client/presence.js")}catch{sharedPresence=require("./vendor/presence.js")}try{sharedTopup=require("../client/topup.js")}catch{sharedTopup=require("./vendor/topup.js")}try{googleSignIn=require("../client/google-signin.js")}catch{googleSignIn=require("./vendor/google-signin.js")}try{driveConnectLib=require("../client/drive-connect.js")}catch{driveConnectLib=require("./vendor/drive-connect.js")}try{driveUploadLib=require("../client/drive-upload.js")}catch{driveUploadLib=require("./vendor/drive-upload.js")}try{conversationExportLib=require("../client/conversation-export.js")}catch{try{conversationExportLib=require("./vendor/conversation-export.js")}catch{conversationExportLib=null}}const{createGoogleConnect:createGoogleConnect}=require("./lib/google-connect.js");let sharedFingerprint;try{sharedFingerprint=require("../client/device-fingerprint.js")}catch{sharedFingerprint=require("./vendor/device-fingerprint.js")}const{createFingerprintService:createFingerprintService}=require("./lib/fingerprint.js"),{createAutoDrain:createAutoDrain,createAutoMint:createAutoMint}=require("./lib/auto.js");let envFile=null;try{envFile=require("../client/env-file.js")}catch{try{envFile=require("./vendor/env-file.js")}catch{}}let electron=null;try{electron=require("electron")}catch{}const os=require("node:os"),{createLocalEngine:createLocalEngine}=require("./lib/local/engine.js"),{createAccountKey:createAccountKey,startupKeyOverride:startupKeyOverride}=require("./lib/account-key.js"),{createSettingsStore:createSettingsStore,isReservedNamespace:isReservedNamespace}=require("./lib/settings.js"),sessionStore=require("./lib/sync/sessions.js"),memoryQueue=require("./lib/sync/memory-queue.js"),persistGate=require("./lib/sync/persist-gate.js"),avatarStore=require("./lib/avatar/store.js"),windowState=require("./lib/window-state.js"),deepLink=require("./lib/deep-link.js"),quickLauncherLib=require("./lib/quick-launcher.js");let foreignMemory;try{foreignMemory=require("../client/foreign-memory.js")}catch{foreignMemory=require("./vendor/foreign-memory.js")}const localTools=require("./lib/local/tools.js"),queueModule=require("./lib/local/queue.js"),autonomousModule=require("./lib/local/autonomous.js"),{autoContinuePlan:autoContinuePlan,autoContinueLimit:autoContinueLimit,autoRoundsDefault:autoRoundsDefault}=require("./lib/local/autonomous.js"),entitlementModule=require("./lib/local/entitlement.js"),telemetryModule=require("./lib/local/telemetry.js"),covenantModule=require("./lib/local/covenant.js"),{createTelemetry:createTelemetry,telemetryEnabled:telemetryEnabled}=telemetryModule,IPC_PREFIX="aegis:",MODEL_PREFIX="model:",SYNC_PREFIX="sync:",TOOLS_PREFIX="tools:",QUICK_PREFIX="quick:",QUEUE_PREFIX="queue:",AUTO_PREFIX="auto:",DESKTOP_CLASSES=Object.freeze(["aegis","byok","local"]),CHAT_DELTA_CHANNEL=`${IPC_PREFIX}chatDelta`,MENU_NEW_CHAT_CHANNEL=`${IPC_PREFIX}menuNewChat`,MENU_SEARCH_CHANNEL=`${IPC_PREFIX}menuSearch`,MENU_EXPORT_MARKDOWN_CHANNEL=`${IPC_PREFIX}menuExportMarkdown`,MENU_EXPORT_JSON_CHANNEL=`${IPC_PREFIX}menuExportJson`,MENU_FINGERPRINT_CHANNEL=`${IPC_PREFIX}menuFingerprint`,MENU_GOOGLE_DRIVE_CHANNEL=`${IPC_PREFIX}menuGoogleDrive`,DEEP_LINK_CHANNEL=`${IPC_PREFIX}deepLink`,QUICK_LAUNCHER_PUSH_CHANNEL=`${IPC_PREFIX}quickLauncherPush`,QUEUE_PROGRESS_CHANNEL=`${QUEUE_PREFIX}progress`,QUEUE_MAX_TASK_CHARS=8e3,QUEUE_MAX_ROUNDS=200,QUEUE_MAX_WORKERS=8,QUEUE_EFFORTS=new Set(["low","medium","high","max"]);function taggedChunk(e,t){return{...e&&"object"==typeof e?e:{delta:e},id:t}}const APP_VERSION=require("./package.json").version;function maskKey(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}function upgradeInfo(e){const t=e&&e.status,n=e&&e.data||{},r="string"==typeof n.error?n.error:"";if(402!==t&&"free_session_limit_reached"!==r)return null;const o=null!=n.tokensUsed?n.tokensUsed:null!=n.sessionsUsed?n.sessionsUsed:null,s=null!=n.tokenLimit?n.tokenLimit:null!=n.freeSessionLimit?n.freeSessionLimit:null;return{url:n.upgradeUrl||"https://aegiscloud.org/go/upgrade?s=desktop&c=status_card",used:o,limit:s,code:r||"free_session_limit_reached"}}function errorText(e){return e&&e.message?e.message:String(e)}function isAbortShapedError(e){return!(!e||"object"!=typeof e||!0!==e.aegisCancelled&&"AbortError"!==e.name&&"ABORT_ERR"!==e.code)}function abortedTurnPayload(e){return{aborted:!0,status:0,code:"ABORT_ERR",message:errorText(e),choices:[{message:{content:""}}]}}function describeSyncError(e){const t=e&&(e.status||e.response&&e.response.status)||0,n=errorText(e);return upgradeInfo(e)?{kind:"quota",status:t||402,message:n,hint:"the plan's synced-token ceiling is reached — free space in the account dashboard or upgrade to keep syncing"}:401===t?{kind:"auth",status:t,message:n,hint:"the memory token was refused — re-enter your AEGIS API key to exchange a new one"}:{kind:"error",status:t||null,message:n,hint:null}}function syncErrorReason(e){return e?e.hint?`${e.message} — ${e.hint}`:e.message:"sync failed"}async function billingResult(e){try{const t=await e();return{ok:!0,url:t&&t.url||null,status:0,reason:null,setupRequired:!1,upgrade:null}}catch(e){const t=e&&e.data||{};return{ok:!1,url:null,status:e&&e.status||0,reason:errorText(e),setupRequired:Boolean(t.setup_required),upgrade:upgradeInfo(e)}}}const{bankAmount:bankAmount,parseTopupAmount:parseTopupAmount,startTopup:startTopup,createCreditWatch:createCreditWatch,TOPUP_POLL_MS:TOPUP_POLL_MS,TOPUP_POLL_TRIES:TOPUP_POLL_TRIES}=sharedTopup;let topupWatch=null;function watchTopupCredit(e,t){const n=t||{},r=n.intervalMs||TOPUP_POLL_MS,o=n.log;topupWatch&&clearInterval(topupWatch);const s=createCreditWatch(e,n.maxTries?{maxTries:n.maxTries}:void 0),a=()=>{topupWatch&&clearInterval(topupWatch),topupWatch=null,s.stop()},i=async()=>{const e=await s.tick();"credited"===e.state?(a(),(e=>{if("function"!=typeof n.notify)try{const t=electron&&electron.Notification;t&&t.isSupported()&&new t({title:"AEGIS Desktop",body:`Bank credited — €${e.toFixed(2)} available`}).show()}catch{}else n.notify(e)})(e.amount)):"expired"===e.state&&(a(),o&&o("top-up: no credit observed within the watch window; stopping"))};return topupWatch=setInterval(i,r),topupWatch&&"function"==typeof topupWatch.unref&&topupWatch.unref(),{stop:a,tick:i,get baseline(){return s.baseline}}}async function saveMemoryWithQueue(e,t,n,r){const o=avatarStore.normalizeMemoryEntry(n);try{const t=await e.memorySave(o);return r&&o&&"object"==typeof o&&r.awardSave(o,{session:o.session}),t}catch(e){const s=upgradeInfo(e);if(s)return{ok:!1,queued:0,saved:0,upgrade:s,reason:errorText(e)};if(!t||!n)throw e;return memoryQueue.enqueue(t,o),r&&o&&"object"==typeof o&&r.awardQueued(o,{session:o.session}),{ok:!0,queued:!0,reason:errorText(e)}}}async function normalizeMemoryRead(e){try{const t=await e,n=quotaFromPayload(t);return n?Object.assign({},t,{upgrade:n}):t}catch(e){const t=upgradeInfo(e);if(!t)throw e;return{entries:[],upgrade:t}}}function quotaFromPayload(e){if(!e||"object"!=typeof e)return null;const t=null!=e.tokensUsed?e.tokensUsed:null,n=null!=e.tokenLimit?e.tokenLimit:null;return null==t||null==n||n<=0||t<n?null:{url:"https://aegiscloud.org/go/upgrade?s=desktop&c=memory_quota",used:t,limit:n,code:"sync_quota_reached"}}async function importForeignMemory(e,t,n,r){const o=n||{},s=foreignMemory.scan({sources:o.sources,limit:o.limit||1e3}),a=foreignMemory.describe(s),i=s.sources.map((e=>({id:e.id,label:e.label,verified:e.verified,present:e.present,count:e.count,skipped:e.skipped,files:e.files}))),c={summary:a,totals:s.totals,sources:i};if(!o.confirm||!s.entries.length)return{...c,ok:!0,dryRun:!o.confirm,saved:0,queued:0};let u=0,l=0;const d=[];let p=null;for(const n of foreignMemory.chunk(s.entries,200))try{const t=await e.memorySaveBatch(n);if(u+=t&&t.saved||n.length,r&&n.length){const e=n[0]||{};r.awardImports(n,{source:e.session||e.source||"foreign-import"})}}catch(e){if(p=upgradeInfo(e),!p&&t)for(const e of n)memoryQueue.enqueue(t,e),l+=1,r&&r.awardQueued(e,{session:e&&e.session});d.push(errorText(e));break}return{...c,ok:0===d.length,dryRun:!1,saved:u,queued:l,upgrade:p,reason:d[0]||null}}function resolveIconsDir(e,t,n){return e?path.join(t,"icons"):path.join(n,"build")}function iconForPlatform(e,t){return"darwin"===t?path.join(e,"icon.icns"):"win32"===t?path.join(e,"icon.ico"):path.join(e,"icon.png")}function isSafeExternalUrl(e){if("string"!=typeof e||!e)return!1;try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}function providerRouteConfigured(e){try{const t=e&&e.settings&&e.settings.list;return"function"==typeof t&&(t.call(e.settings)||[]).some((e=>{if(!e||!e.provider||isReservedNamespace(e.provider))return!1;const t="string"==typeof e.baseURL?e.baseURL.trim():"";return Boolean(e.configured||t)}))}catch{return!1}}function createIpcDispatch(e,t,n,r,o,s,a){let i=null;const c=new Proxy({},{get(e,n){i||(i=createFingerprintService({dir:t,getVaultBackend:a}));const r=i[n];return"function"==typeof r?r.bind(i):r},has:(e,n)=>(i||(i=createFingerprintService({dir:t,getVaultBackend:a})),n in i)}),u=()=>{try{return Boolean("function"==typeof o&&o())}catch{return!1}},l=r||(()=>Promise.reject(new Error("no opener configured")));return{status:()=>({appVersion:APP_VERSION,clientVersion:e.clientVersion,apiBase:e.apiBase,keyConfigured:Boolean(e.apiKey),keyMask:maskKey(e.apiKey),providerConfigured:u()}),setApiKey:t=>{try{const r=t&&t.key;return e.setApiKey(r||""),n&&n(e.apiKey),{ok:!0,keyConfigured:Boolean(e.apiKey),keyMask:maskKey(e.apiKey)}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},verifyApiKey:async()=>{try{return{ok:!0,...await e.verifyApiKey()}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},tokenBankBalance:()=>e.tokenBankBalance(),billingCheckout:()=>billingResult((()=>e.billingCheckout())),tokenBankTopup:async t=>{const n=parseTopupAmount(t&&t.amountEur);if(!n.ok)return{ok:!1,url:null,status:400,reason:n.message,setupRequired:!1,upgrade:null};const r=await startTopup(e,n.amount);return!0===r.ok&&r.url&&watchTopupCredit(e),{ok:!0===r.ok,url:r.url,status:r.status,reason:r.ok?null:r.hint?`${r.message} — ${r.hint}`:r.message,setupRequired:r.setupRequired,upgrade:null}},listModels:()=>e.listModels(),chatCompletion:t=>e.chatCompletion({prompt:t&&t.prompt,system:t&&t.system,model:t&&t.model,mode:t&&t.mode,maxTokens:t&&t.maxTokens,stream:t&&t.stream,onStream:t&&t.onStream}),fingerprintStatus:()=>c.status(),fingerprintKeygen:e=>c.keygen(e||{}),fingerprintMint:e=>c.mint(e||{}),fingerprintVerify:e=>c.verify(e||{}),fingerprintBackup:e=>c.backup(e||{}),fingerprintPublish:e=>c.publish(e||{}),fingerprintAnchor:e=>c.anchor(e||{}),fingerprintVault:()=>c.vaultList(),fingerprintVaultAudit:()=>c.vaultAudit(),byokStatus:()=>e.byokStatus(),byokSet:t=>e.byokSet(t&&t.provider,t&&t.apiKey),memorySearch:t=>normalizeMemoryRead(e.memorySearch(t&&t.query,t&&t.limit)),memorySave:n=>saveMemoryWithQueue(e,t,n&&n.entry,s),memoryList:t=>normalizeMemoryRead(e.memoryList(t&&t.limit)),verifyToken:t=>e.verifyToken(t&&t.token),memoryActivate:t=>e.memoryActivate(t&&t.token),memoryPull:t=>e.memoryPull(t&&t.since),memorySaveBatch:t=>e.memorySaveBatch(t&&t.entries),memoryImport:n=>importForeignMemory(e,t,n,s),importConversation:t=>e.importConversation(t||{}),openExternal:e=>{const t=e&&e.url;return isSafeExternalUrl(t)?Promise.resolve(l(t)).then((()=>({ok:!0})),(e=>({ok:!1,reason:errorText(e)}))):Promise.resolve({ok:!1,reason:"unsupported URL scheme"})}}}function withReplyNotify(e,t,n){return n?e.then((e=>(n(t,e),e))):e}function registerIpc(e,t,n,r,o,s,a,i){const c=createIpcDispatch(t,n,r,o,a,void 0,i);for(const[t,n]of Object.entries(c))"chatCompletion"!==t?e.handle(`${IPC_PREFIX}${t}`,((e,t)=>n(t))):e.handle(`${IPC_PREFIX}${t}`,((e,t)=>{const r={...t||{}};if(!r.stream)return withReplyNotify(n(r),e,s);const o=e&&e.sender;return withReplyNotify(n({...r,stream:!0,onStream:e=>{o&&"function"==typeof o.send&&!o.isDestroyed()&&o.send(CHAT_DELTA_CHANNEL,taggedChunk(e,r.sessionId))}}),e,s)}));return c}function createConfirmModeDispatch(e){if(!e)throw new Error("createConfirmModeDispatch requires a settings store");return{getConfirmMode:()=>({enabled:e.getConfirmMode()}),setConfirmMode:t=>{const n=t&&t.enabled;return"boolean"!=typeof n?{enabled:e.getConfirmMode()}:{enabled:e.setConfirmMode(n)}}}}function withAutoRoundsSwitch(e,t){const n=e.setConfirmMode;return{...e,setConfirmMode:e=>{const r=n(e);return e&&"boolean"==typeof e.enabled&&t&&"function"==typeof t.setAutoRounds&&t.setAutoRounds(!1===e.enabled),r}}}function registerConfirmModeIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`${IPC_PREFIX}${n}`,((e,t)=>r(t)));return t}function createVaultBackendDispatch(e){if(!e)throw new Error("createVaultBackendDispatch requires a settings store");return{getVaultBackend:()=>e.vaultBackendConfig(),setVaultBackend:t=>e.setVaultBackendConfig(t&&t.backend)}}function createTelemetryDispatch(e){const t=e||null;return{telemetryEvent:e=>{try{if(!t||"function"!=typeof t.record)return{ok:!1,reason:"telemetry off"};const n=e&&"object"==typeof e?e:{};return t.record(n.event,{campaign:n.campaign,surface:n.surface})?{ok:!0}:{ok:!1,reason:"not an allowlisted funnel event"}}catch(e){return{ok:!1,reason:errorText(e)}}},telemetryReport:()=>{try{return t&&"function"==typeof t.report?t.report():{enabled:!1,transport:"off"}}catch(e){return{enabled:!1,error:errorText(e)}}}}}function createCovenantDispatch(e){return{covenantStatus:()=>({ok:!0,covenant:e.snapshot(),gapReport:e.gapReport()}),covenantGapReport:()=>({ok:!0,gapReport:e.gapReport()})}}function registerCovenantIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`${IPC_PREFIX}${n}`,((e,t)=>r(t)));return t}function registerTelemetryIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`${IPC_PREFIX}${n}`,((e,t)=>r(t)));return t}function safeExportBasename(e){return(e&&(e.title||e.id)||"session").replace(/[^\w.-]+/g,"_").slice(0,80)||"session"}function createExportDispatch(e,t,n,r){return{exportSession:async o=>{const s=o&&o.sessionId,a=o&&"json"===o.format?"json":"markdown",i=s?e.getSession(t,s):null;if(!i)return{ok:!1,reason:"session not found"};const c="json"===a?e.toJson(i):e.toMarkdown(i),u="json"===a?"json":"md",l="json"===a?[{name:"JSON",extensions:["json"]}]:[{name:"Markdown",extensions:["md"]}],d=await n({defaultPath:`${safeExportBasename(i)}.${u}`,filters:l});if(!d||d.canceled||!d.filePath)return{ok:!1,canceled:!0};try{await r(d.filePath,c)}catch(e){return{ok:!1,reason:errorText(e)}}return{ok:!0,filePath:d.filePath}}}}function registerExportIpc(e,t,n,r,o){const s=createExportDispatch(t,n,r,o);for(const[t,n]of Object.entries(s))e.handle(`${IPC_PREFIX}${t}`,((e,t)=>n(t)));return s}function createQuickLauncherDispatch(e,t={}){const n=Boolean(t.isPackaged),r=t.applyConfig||(()=>({active:!1,reason:null})),o=t.pushToMain||(()=>({ok:!1,reason:"no main window"}));let s={active:!1,reason:null};return{status:function(){return{...e.quickLauncherConfig(),packaged:n,...s}},setConfig:function(t){const o=e.setQuickLauncherConfig({enabled:t&&t.enabled,shortcut:t&&t.shortcut});return s=r(o)||{active:!1,reason:null},{...o,packaged:n,...s}},pushToMain:(e,t)=>o(e,t)}}function registerQuickLauncherIpc(e,t){for(const[n,r]of Object.entries(t))"pushToMain"!==n?e.handle(`${QUICK_PREFIX}${n}`,((e,t)=>r(t))):e.handle(`${QUICK_PREFIX}${n}`,((e,t)=>r(t,e)));return t}function resolveUserDataDir(e){if(e&&"function"==typeof e.getPath)try{return e.getPath("userData")}catch{}return path.join(os.homedir(),".aegiscode")}function createEngine(e,{app:t,safeStorage:n,dir:r,sessionsDir:o}={}){const s=r||resolveUserDataDir(t),a=createSettingsStore({dir:s,safeStorage:n});return a.migrateLegacyAegisKey(),{engine:createLocalEngine({aegis:e,settings:a}),sessionsDir:o||sessionStore.resolveStoreDir(s),settingsDir:s,settings:a}}const PREVIEW_READ_MAX_BYTES=524288;function readTextFileForPreview(e){try{const t=e&&"string"==typeof e.file?e.file:"",n=e&&"string"==typeof e.cwd?e.cwd:"";if(!t||!n||!path.isAbsolute(n))return null;const r=fs.realpathSync(n),o=fs.realpathSync(path.resolve(r,t)),s=path.relative(r,o);if(""===s||s.startsWith("..")||path.isAbsolute(s))return null;const a=fs.statSync(o);if(!a.isFile())return null;if(a.size<=PREVIEW_READ_MAX_BYTES)return{text:fs.readFileSync(o,"utf8"),truncated:!1};const i=fs.openSync(o,"r");try{const e=Buffer.alloc(PREVIEW_READ_MAX_BYTES),t=fs.readSync(i,e,0,PREVIEW_READ_MAX_BYTES,0);let n=e.toString("utf8",0,t);const r=n.lastIndexOf("\n");return r>0&&(n=n.slice(0,r+1)),{text:n,truncated:!0}}finally{fs.closeSync(i)}}catch{return null}}const attachmentsModule=require("./lib/local/attachments.js");function nativeImageResizer(e,t){try{const{nativeImage:n}=require("electron");if(!n)return null;const r=n.createFromBuffer(e);if(!r||r.isEmpty())return null;const o=r.getSize(),s=Math.max(o.width,o.height),a=s>1568?r.resize({width:Math.round(1568*o.width/s)}):r,i="image/png"===t?a.toPNG():a.toJPEG(82);return i&&i.length?{buffer:i,mime:"image/png"===t?"image/png":"image/jpeg"}:null}catch{return null}}function ingestAttachment(e,{resize:t=nativeImageResizer}={}){const n=e&&"string"==typeof e.path?e.path.trim():"";if(!n)return{ok:!1,reason:"no path"};if(!path.isAbsolute(n))return{ok:!1,reason:"not an absolute path"};let r,o,s;try{r=fs.realpathSync(n),o=fs.statSync(r)}catch{return{ok:!1,reason:"not found"}}if(!o.isFile())return{ok:!1,reason:"not a regular file"};if(0===o.size)return{ok:!1,reason:"empty file"};if(o.size>attachmentsModule.MAX_FILE_BYTES)return{ok:!1,reason:`too large (${attachmentsModule.humanBytes(o.size)})`};try{s=fs.readFileSync(r)}catch{return{ok:!1,reason:"unreadable"}}const a=attachmentsModule.sniff(s),i={path:r,name:path.basename(r),size:o.size,mime:a.mime,kind:a.kind};if("image"===a.kind){let{mime:e}=a,n=s,r=!1;if(n.length>attachmentsModule.MAX_IMAGE_BYTES&&"function"==typeof t){const o=t(s,e);o&&o.buffer&&o.buffer.length<n.length&&(n=o.buffer,e=o.mime,r=!0)}const o=attachmentsModule.toDataUrl(n,e);return o?{ok:!0,attachment:{...i,kind:"image",mime:e,size:n.length,dataUrl:o,scaled:r,vision:attachmentsModule.isVisionMime(e)}}:{ok:!1,reason:"could not encode image"}}if("text"===a.kind){if(o.size>attachmentsModule.MAX_TEXT_BYTES){let e=s.subarray(0,attachmentsModule.MAX_TEXT_BYTES).toString("utf8");const t=e.lastIndexOf("\n");return t>0&&(e=e.slice(0,t+1)),{ok:!0,attachment:{...i,kind:"text",text:e,truncated:!0}}}return{ok:!0,attachment:{...i,kind:"text",text:s.toString("utf8"),truncated:!1}}}return"pdf"===a.kind?{ok:!0,attachment:{...i,kind:"pdf"}}:{ok:!0,attachment:{...i,kind:"binary"}}}function createModelDispatch(e,{env:t=process.env,settings:n}={}){const r=new Map;let o,s=autoRoundsDefault(t),a=!1;const i=()=>{const t=n||e&&e.settings||null,r=e=>"boolean"==typeof e?e:void 0;let i;try{if(t&&"function"==typeof t.confirmModeState){const e=t.confirmModeState();i=r(e&&e.enabled)}void 0===i&&t&&"function"==typeof t.getConfirmMode&&(i=r(t.getConfirmMode()))}catch{}return a||void 0===i||(void 0===o?o=i:i!==o&&(a=!0,s=!0)),!(!s||!t||void 0===i)&&!1===i},c={listClasses:async()=>(await e.listClasses()).filter((e=>DESKTOP_CLASSES.includes(e.class))),listModels:t=>e.listModels(t&&t.class),chat:n=>{const o=n&&n.onStream;if("function"!=typeof o)return e.chat(n,o);const s=n&&n.sessionId||"";return e.chat(n,(n=>{if(n&&n.rounds&&n.rounds.id&&i()){const a=autoContinuePlan({on:!0,used:r.get(s)||0,limit:autoContinueLimit(t)});if(r.set(s,a.used),a.auto){const t="function"==typeof e.respondRoundsAsk?e.respondRoundsAsk(n.rounds.id,!0):{ok:!1};if(t&&t.ok){const e=Number(n.rounds.spent)||0;return void o({note:`auto mode: the ${e}-round limit was reached — continuing automatically (${a.used}/${a.cap}, then it asks).`})}}}o(n)}))},"settings.get":()=>e.settings.list().filter((e=>!(e&&isReservedNamespace(e.provider)))),"settings.set":t=>e.settings.set(t&&t.provider,{baseURL:t&&t.baseURL,key:t&&t.key}),"settings.remove":t=>e.settings.remove(t&&t.provider),"userModels.get":()=>e.userModels(),"userModels.add":t=>e.addUserModel(t&&t.provider,t&&t.model),"userModels.remove":t=>e.removeUserModel(t&&t.provider,t&&t.model),"userModels.discover":t=>e.discoverModels(t&&t.provider),"userModels.addAll":t=>e.addUserModels(t&&t.provider,t&&t.ids),"userModels.canDiscover":t=>Boolean(e.canDiscoverModels(t&&t.provider)),"userModels.discoverable":()=>e.discoverableProviders(),"memoryPersist.get":()=>e.settings.memoryPersistState(),"memoryPersist.set":t=>e.settings.setMemoryPersist(Boolean(t&&t.enabled)),cancel:t=>e.cancel(t&&t.sessionId),respondApproval:t=>e.respondApproval(t&&t.approvalId,t&&t.decision),respondRoundsAsk:t=>"function"==typeof e.respondRoundsAsk?e.respondRoundsAsk(t&&t.roundsAskId,t&&t.decision):{ok:!1},clearApprovals:t=>e.clearSessionApprovals(t&&t.sessionId)};return Object.defineProperties(c,{autoRoundsOn:{value:i,enumerable:!1},setAutoRounds:{value:e=>{s=Boolean(e),a=!0},enumerable:!1}}),c}function createSyncDispatch(e,t,n,r){let o=null;function s(){return Boolean(n&&n.apiKey)}async function a(){const r=e.listPending(t);if(!s())return{ok:!1,queued:r.length,reason:"no AEGIS key configured"};const a=await async function(){const e=memoryQueue.listQueued(t);if(!e.length)return{flushed:0,remaining:0,upgrade:null};const r=[];let o=0,s=null;for(let t=0;t<e.length;t+=1)try{await n.memorySave(e[t]),o+=1}catch(n){const o=upgradeInfo(n);if(o){s=o,r.push(...e.slice(t));break}r.push(e[t])}return memoryQueue.save(t,r),{flushed:o,remaining:r.length,upgrade:s}}();if(!r.length)return{ok:!0,queued:0,pushed:0,memoryFlushed:a.flushed,upgrade:a.upgrade};let i=0,c=null,u=null;for(const o of r)try{const r=await n.conversationSyncPush({session_id:o.id,title:o.title,messages:o.messages}),s=r&&(r.session_id||r.id);e.markSynced(t,o.id,{remoteId:s}),i+=1}catch(e){if(c=e,u=describeSyncError(e),"quota"===u.kind||"auth"===u.kind)break}const l=e.listPending(t).length;i&&(o=Date.now());const d=(c?upgradeInfo(c):null)||a.upgrade;return 0===i&&c?{ok:!1,queued:l,reason:syncErrorReason(u),failed:u?[u]:[],kind:u?u.kind:"error",status:u?u.status:0,hint:u?u.hint:null,memoryFlushed:a.flushed,upgrade:d}:{ok:!0,queued:l,pushed:i,failed:u?[u]:[],memoryFlushed:a.flushed,upgrade:d}}const i=persistGate.createAutoPush({push:a,dir:r||t});return{auto:()=>i.auto(),memoryPersistState:()=>i.gate(),listSessions:()=>({sessions:e.listSessions(t)}),open:n=>e.getSession(t,n&&n.sessionId),save:n=>e.upsertSession(t,n||{}),append:n=>e.appendMessage(t,n&&n.sessionId,n&&n.message),delete:n=>e.deleteSession(t,n&&n.sessionId),push:a,pull:async function(){if(!s())return{ok:!1,merged:0,reason:"no AEGIS key configured"};try{const r=await n.conversationSyncPull(),s=e.mergeRemoteSessions(t,r&&r.sessions||[]);return o=Date.now(),{ok:!0,merged:s,failed:[],upgrade:null}}catch(e){const t=describeSyncError(e);return{ok:!1,merged:0,reason:syncErrorReason(t),failed:[t],kind:t.kind,status:t.status,hint:t.hint,upgrade:upgradeInfo(e)}}},status:()=>({count:e.listSessions(t).length,pending:e.listPending(t).length,cloud:s(),lastSyncAt:o})}}const HEARTBEAT_RETRY_BASE_MS=5e3,HEARTBEAT_RETRY_MAX_MS=3e4;function createHeartbeatRetry(e,t={}){const n="function"==typeof t.now?t.now:()=>Date.now(),r=Number(t.baseMs)>0?Number(t.baseMs):HEARTBEAT_RETRY_BASE_MS,o=Number(t.maxMs)>0?Number(t.maxMs):HEARTBEAT_RETRY_MAX_MS;let s=0,a=0,i=null,c=!1;function u(e){s+=1;const t=Math.min(o,r*2**Math.max(0,s-1));return i=e||"push failed",a=n()+t,{attempted:!0,ok:!1,error:i,failures:s,retryInMs:t}}return{run:async function(){const t=n();if(s>0&&t<a)return{attempted:!1,ok:!1,error:i,failures:s,retryInMs:a-t};if(c)return{attempted:!1,ok:!1,error:i,failures:s,retryInMs:0};c=!0;try{const t=await e();return t&&!1===t.ok?u(t.reason||t.kind||"push failed"):(s=0,a=0,i=null,{attempted:!0,ok:!0,error:null,failures:0,retryInMs:0,result:t})}catch(e){return u(errorText(e))}finally{c=!1}},state:function(){const e=n();return{failures:s,lastError:i,retryInMs:s>0&&a>e?a-e:0}},recordFailure:e=>u(errorText(e))}}function registerModelIpc(e,t,n,r,o,s,a){const i=createModelDispatch(t),c=createSyncDispatch(sessionStore,n,r,a),u=createHeartbeatRetry((()=>c.push()),s);function l(){const e=u.run();e&&"function"==typeof e.catch&&e.catch((e=>u.recordFailure(e)))}for(const[t,n]of Object.entries(i))"chat"!==t?"listModels"!==t?e.handle(`${MODEL_PREFIX}${t}`,((e,t)=>n(t))):e.handle(`${MODEL_PREFIX}${t}`,((e,t)=>(l(),n(t)))):e.handle(`${MODEL_PREFIX}${t}`,((e,t)=>{const r={...t||{}},s=!0===r.bestEffort;delete r.bestEffort;const a="low"===r.effort||"medium"===r.effort||"max"===r.effort?r.effort:"high";r.effort=a;const i=e&&e.sender,c=r.class||"model",u=n({...r,onStream:e=>{i&&"function"==typeof i.send&&!i.isDestroyed()&&i.send(CHAT_DELTA_CHANNEL,taggedChunk(e,r.sessionId))}});return s?u.then((t=>(o&&o(e,t),t)),(e=>{const t=e&&"number"==typeof e.status?e.status:0,n=e&&e.code||"";return console.warn(`[model] background ${c} turn produced no answer: ${errorText(e)}${t?` (status ${t})`:""}${n?` [${n}]`:""}`),{bestEffortFailed:!0,status:t,code:n||void 0,message:errorText(e),choices:[{message:{content:""}}]}})):withReplyNotify(u,e,o).catch((e=>{if(!isAbortShapedError(e))throw e;return console.warn(`[model] ${c} turn stopped before it finished: ${errorText(e)} [ABORT_ERR]`),abortedTurnPayload(e)}))}));e.on(`${MODEL_PREFIX}readTextFile`,((e,t)=>{e.returnValue=readTextFileForPreview(t)})),e.handle(`${IPC_PREFIX}attachments:ingest`,(async(e,t)=>ingestAttachment(t)));for(const[t,n]of Object.entries(c))"status"!==t?e.handle(`${SYNC_PREFIX}${t}`,((e,t)=>n(t))):e.handle(`${SYNC_PREFIX}${t}`,((e,t)=>{l();const r=n(t);return r&&"object"==typeof r?{...r,retry:u.state()}:r}));return{modelDispatch:i,syncDispatch:c,heartbeat:u}}function createQueueEngine(e,t){return createLocalEngine({aegis:e,settings:t,getConfirmMode:()=>!1})}function queueEngineWithDeniedApprovals(e){return e&&"function"==typeof e.chat?{...e,chat:(t,n)=>e.chat(t,(t=>{(t=>{const n=t&&t.approval;if(n&&n.id&&"function"==typeof e.respondApproval)try{e.respondApproval(n.id,"deny")}catch{}})(t),(t=>{const n=t&&t.rounds;if(n&&n.id&&"function"==typeof e.respondRoundsAsk)try{e.respondRoundsAsk(n.id,!1)}catch{}})(t),"function"==typeof n&&n(t)}))}:e}function isExistingDir(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function clampInt(e,t,n){const r=Number(e);return!Number.isInteger(r)||r<t||r>n?null:r}function createQueueDispatch({engine:e,env:t=process.env,queue:n=queueModule,autonomous:r=autonomousModule,entitlement:o=entitlementModule.createEntitlement({}),log:s=(()=>{})}={}){if(!e||"function"!=typeof e.chat)throw new Error("createQueueDispatch: a local engine with chat() is required");let a=null,i=!1,c=!1;const u=r.createQueueWorker({engine:queueEngineWithDeniedApprovals(e),env:t,log:e=>{e&&"start"===e.type&&(a=e.taskId),e&&"finish"===e.type&&(a=null),s(e)},canFanOut:()=>o.current().entitled});function l(){const e=n.loadQueue(t);return{ok:!0,items:e,pending:n.pendingCount(e),running:e.find((e=>e&&"running"===e.status))||null,draining:c,stopping:i,defaultCwd:process.cwd(),defaultModel:r.resolveModel({env:t}),queueFile:n.queuePath(t),runs:n.readRuns(t,{limit:20}),entitlement:o.current()}}const d=e=>(e||[]).map((e=>({id:e.id,ok:Boolean(e.ok),error:e.error||null})));return{enqueue:async e=>{await o.refresh();const s=o.gateFanout({workers:clampInt(e&&e.workers,1,QUEUE_MAX_WORKERS),fanout:Boolean(e&&!0===e.fanout)});if(!s.ok)return{...s,...l()};const{opts:a,error:i}=function(e){const t=e||{},n=String(null==t.task?"":t.task).trim();if(!n)return{error:"a queued task needs text"};if(n.length>QUEUE_MAX_TASK_CHARS)return{error:`task text is too long (${n.length} > ${QUEUE_MAX_TASK_CHARS} chars)`};const o=String(null==t.cwd?"":t.cwd).trim()||process.cwd();if(!path.isAbsolute(o))return{error:"the working directory must be an absolute path"};if(!isExistingDir(o))return{error:`not a directory: ${o}`};const s=r.normalizeClass(t.class),a=String(null==t.model?"":t.model).trim().slice(0,120)||null,i=r.modelRefusal(a,s);if(i)return{error:i};const c=String(null==t.effort?"":t.effort).trim().toLowerCase();return{opts:{task:n,cwd:o,class:s,model:a,effort:QUEUE_EFFORTS.has(c)?c:null,workers:clampInt(t.workers,1,QUEUE_MAX_WORKERS),maxRounds:clampInt(t.maxRounds,1,QUEUE_MAX_ROUNDS),singlePass:!(!0===t.fanout||!0===t.autonomous),commit:Boolean(t.commit),source:"desktop"}}}(e);return i?{ok:!1,reason:i,...l()}:{ok:!0,item:n.addTask(t,a),...l()}},list:()=>l(),entitlement:async e=>(await o.refresh({force:Boolean(e&&!0===e.force)}),{ok:!0,...l()}),clear:e=>({...n.clearQueue(t,{all:Boolean(e&&e.all)}),ok:!0,...l()}),retry:e=>{const r=e&&e.id,o=n.retryTask(t,r);return o?{ok:!0,item:o,...l()}:{ok:!1,reason:`no task #${r}`,...l()}},remove:e=>{const r=e&&e.id,o=n.loadQueue(t),s=n.findTask(o,r);return s?"running"===s.status?{ok:!1,reason:`task #${s.id} is running — stop the drain first`,...l()}:(n.saveQueue(t,o.filter((e=>Number(e&&e.id)!==Number(s.id)))),{ok:!0,removed:s.id,...l()}):{ok:!1,reason:`no task #${r}`,...l()}},drain:()=>async function(){if(c)return{ok:!1,reason:"a drain is already running in this window",...l()};let e;c=!0,i=!1;try{const t=await u.proceed({max:1});e=t.locked?{ok:!1,locked:!0,holder:t.holder,ran:[]}:{ok:!0,ran:d(t.ran)}}catch(t){e={ok:!1,reason:errorText(t),ran:[]}}return c=!1,a=null,{...e,...l()}}(),proceed:()=>async function(){if(c)return{ok:!1,reason:"a drain is already running in this window",...l()};c=!0,i=!1;const e=[];let t;try{for(;;){const n=await u.proceed({max:1});if(n.locked){t={ok:!1,locked:!0,holder:n.holder,ran:d(e)};break}if(!n.ran.length){t={ok:!0,stopped:i,ran:d(e)};break}if(e.push(...n.ran),i){t={ok:!0,stopped:!0,ran:d(e)};break}}}catch(n){t={ok:!1,reason:errorText(n),ran:d(e)}}return c=!1,a=null,{...t,...l()}}(),stop:e=>{i=!0;const t=e&&null!=e.id?e.id:a,n=null==t?null:u.cancel(t);return{ok:!0,wasDraining:c,cancelled:n,...l()}}}}function createAutoDispatch({autoDrain:e,autoMint:t}={}){if(!e||"function"!=typeof e.state)throw new Error("createAutoDispatch: the auto-drain automation is required");if(!t||"function"!=typeof t.state)throw new Error("createAutoDispatch: the auto-mint automation is required");return{autoStatus:()=>({ok:!0,drain:e.state(),mint:t.state()}),autoSetDrain:t=>{const n=t||{},r={};null!=n.enabled&&(r.enabled=Boolean(n.enabled)),null!=n.intervalMs&&(r.intervalMs=Number(n.intervalMs));try{return{ok:!0,drain:e.set(r)}}catch(e){return{ok:!1,error:errorText(e)}}},autoSetMint:e=>{const n=e||{},r={};null!=n.enabled&&(r.enabled=Boolean(n.enabled)),null!=n.publish&&(r.publish=Boolean(n.publish));try{return{ok:!0,mint:t.set(r)}}catch(e){return{ok:!1,error:errorText(e)}}},autoSealNow:async e=>{const n=e||{};null!=n.publish&&t.set({publish:Boolean(n.publish)});try{const e=await t.flush();return t.reset(),{ok:!0,...e}}catch(e){return t.reset(),{ok:!1,error:errorText(e)}}}}}function registerQueueIpc(e,{engine:t,env:n,queue:r,autonomous:o,entitlement:s,aegis:a}={}){let i=null;const c=createQueueDispatch({engine:t,env:n,queue:r,autonomous:o,entitlement:s||entitlementModule.createEntitlement({probe:a&&"function"==typeof a.verifyApiKey?async()=>{const e=await a.verifyApiKey(),t=e&&"object"==typeof e?{...e}:{};if("function"==typeof a.tokenBankBalance)try{const e=await a.tokenBankBalance();e&&"object"==typeof e&&(null!=e.balance_micros?t.balance_micros=e.balance_micros:null!=e.balance_eur&&(t.balance_eur=e.balance_eur))}catch{}return t}:void 0}),log:e=>{i&&"function"==typeof i.send&&("function"==typeof i.isDestroyed&&i.isDestroyed()||i.send(QUEUE_PROGRESS_CHANNEL,e))}});for(const[t,n]of Object.entries(c))e.handle(`${QUEUE_PREFIX}${t}`,((e,t)=>(i=e&&e.sender||null,n(t))));return c}function registerAutoIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`${AUTO_PREFIX}${n}`,((e,t)=>r(t)));return t}const UPDATE_STATUS_CHANNEL=`${IPC_PREFIX}updateStatus`,ACCOUNT_STATUS_CHANNEL=`${IPC_PREFIX}accountStatusChanged`,UPDATE_CHECK_INTERVAL_MS=144e5,UPDATE_RETRY_BACKOFF_MS=[6e4,3e5,9e5,36e5];function describeRegistryFailure(e,t,n){switch(e){case"not-found":return`${n} is not published on the npm registry (404)`;case"forbidden":return`the npm registry refused the request (${t||"auth"})`;case"malformed":return"the npm registry sent a response this app could not read";case"too-large":return"the npm registry response was too large to read";case"timeout":return"the npm registry did not respond in time";case"network":return"the npm registry could not be reached";default:return"the update check did not complete"}}function createNpmUpdateManager({onStatus:e,packaged:t=!1,now:n=(()=>Date.now()),fetchImpl:r,setTimeoutImpl:o=setTimeout,clearTimeoutImpl:s=clearTimeout,runUpgrade:a,relaunch:i}={}){const c="aegis-desktop";let u="unknown";try{u=require("./package.json").version}catch{}let l={status:"idle",version:null,error:null,channel:"npm",reason:null,transient:!1,attempts:0,retryInMs:0,command:null,plan:null,method:null,canDownload:!1};const d=t=>(l={...l,...t},e&&e(l),l);let p=null;try{p=require("../client/update.js")}catch{try{p=require("./vendor/update.js")}catch{p=null}}let f=0,m=0,h=null,g=null,y=null,E=null;function k(){h&&s(h),h=null}async function _({announce:e=!1}={}){if(!p)return d({status:"disabled",error:"update checker unavailable"});if(g)return g;g=(async()=>{const s=l.status,a=l.version;let i;d({status:"checking",error:null,reason:null,transient:!1});try{i=await async function(){if(r)return r({pkg:c});if(p&&"function"==typeof p.checkPublished){const e=await p.checkPublished({current:u,pkg:c,now:n(),intervalMs:0});return e?{ok:e.ok,latest:e.latest,reason:e.reason,status:e.status}:{ok:!1,latest:null,reason:"unknown",status:null}}return{ok:!1,latest:null,reason:"unavailable",status:null}}()}catch(e){i={ok:!1,latest:null,reason:"unknown",status:null,error:errorText(e)}}if(i.ok){if(f=0,m=0,k(),!p.isNewer(i.latest,u))return d({status:"up-to-date",version:i.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0});const e=function(){if(E)return E;const e=p&&p.detectInstallMethod;if("function"!=typeof e)return E="npm",E;try{E=e({env:process.env,argv:process.argv,pkg:c,entry:__dirname,fileExists:e=>fs.existsSync(path.resolve(__dirname,"..",e))})}catch{E="npm"}return E}(),n="function"==typeof p.updatePlan?p.updatePlan({current:u,latest:i.latest,behind:!0,channel:"npm",pkg:c,method:e}):null;return d({status:"available",version:i.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0,plan:n,method:e,command:t?`${i.latest} is published — reinstall AEGIS Desktop from the installer to pick it up`:n&&n.instruction||`npm i -g ${c}@latest`,commandIsSentence:t||Boolean(n&&!n.apply),canDownload:Boolean(n&&n.apply)&&!t})}f+=1;const g=i.error||describeRegistryFailure(i.reason,i.status,c);return y=i.reason,v=i.status,("function"==typeof p.isTransientReason?p.isTransientReason(y,v):"unknown"===y)?(function(){k();const e=UPDATE_RETRY_BACKOFF_MS[Math.min(Math.max(f-1,0),UPDATE_RETRY_BACKOFF_MS.length-1)];m=n()+e,h=o((()=>{h=null,_().catch((()=>{}))}),e),h&&h.unref&&h.unref(),d({retryInMs:e})}(),d(e?{status:"error",error:g,reason:i.reason,transient:!0,attempts:f}:{status:"available"===s?"available":"unavailable",version:a,error:g,reason:i.reason,transient:!0,attempts:f})):(k(),m=0,d({status:"error",error:g,reason:i.reason,transient:!1,attempts:f,retryInMs:0}));var y,v})();try{return await g}finally{g=null}}return{status:()=>l,check:_,download:async()=>{const e=!t&&l.plan&&l.plan.apply;if(!e)return d({status:"available"===l.status?"available":l.status,command:l.plan&&l.plan.instruction||l.command,canDownload:!1});d({status:"downloading",error:null,progress:0});const n=await function(e){const t=a||((e,t)=>new Promise((n=>{execFile(e,t,{timeout:18e4,windowsHide:!0},((e,t,r)=>{if(e)return n({ok:!1,output:String(r||t||e.message||e)});n({ok:!0,output:String(t||"")})}))}))),n=!a&&p&&"function"==typeof p.installSpawn?p.installSpawn(e,{env:process.env}):null,r=n?n.command:e.command,o=n?n.args:e.args;return Promise.resolve(t(r,o)).then((e=>({ok:Boolean(e&&e.ok),output:String(e&&e.output||"")})),(e=>({ok:!1,output:errorText(e)})))}(e);return n.ok?d({status:"downloaded",version:l.version,error:null,progress:100,command:`npm i -g ${c}@latest`,canDownload:!1}):d({status:"error",transient:!1,error:n.output.trim().split("\n").slice(-3).join(" ").trim()||"the installer failed",command:`${e.command} ${e.args.join(" ")}`})},quitAndInstall:()=>{"downloaded"===l.status&&(i||(()=>{try{const{app:e}=require("electron");e.relaunch(),e.exit(0)}catch{}}))()},start:()=>{_().catch((()=>{})),y=setInterval((()=>_().catch((()=>{}))),UPDATE_CHECK_INTERVAL_MS),y.unref&&y.unref()},stop:()=>{k(),y&&clearInterval(y),y=null},retryState:()=>({attempts:f,retryAt:m,inFlight:!!g,hasTimer:!!h})}}function createUpdateManager({isPackaged:e,onStatus:t}){let n={status:"idle",version:null,error:null,canDownload:!1};return createNpmUpdateManager({onStatus:function(e){n={...n,...e},t&&t(n)},packaged:Boolean(e)})}function createUpdateDispatch(e){return{checkForUpdates:()=>e.check({announce:!0}),downloadUpdate:()=>e.download(),quitAndInstallUpdate:()=>(e.quitAndInstall(),{ok:!0}),updateStatus:()=>Promise.resolve(e.status())}}function registerUpdateIpc(e,t){const n=createUpdateDispatch(t);for(const[t,r]of Object.entries(n))e.handle(`${IPC_PREFIX}${t}`,((e,t)=>r(t)));return n}function sendToFocusedWindow(e,t){const n=e.getFocusedWindow()||e.getAllWindows()[0];n&&!n.isDestroyed()&&n.webContents.send(t)}function sendDeepLinkToWindow(e,t){if(!e||e.isDestroyed()||!t)return;const n=()=>{e.isDestroyed()||e.webContents.send(DEEP_LINK_CHANNEL,t)};e.webContents.isLoadingMainFrame()?e.webContents.once("did-finish-load",n):n()}function buildAppMenu({app:e,Menu:t,BrowserWindow:n,updateManager:r,loggedIn:o}){const s="darwin"===process.platform;e.setAboutPanelOptions({applicationName:e.getName(),applicationVersion:e.getVersion(),version:e.getVersion()});const a={label:"Check for Updates…",click:()=>r.check({announce:!0})},i={label:"New Chat",accelerator:"CmdOrCtrl+N",click:()=>sendToFocusedWindow(n,MENU_NEW_CHAT_CHANNEL)},c={label:"Search…",accelerator:"CmdOrCtrl+K",click:()=>sendToFocusedWindow(n,MENU_SEARCH_CHANNEL)},u={label:"Save as…",accelerator:"CmdOrCtrl+S",click:()=>sendToFocusedWindow(n,MENU_EXPORT_MARKDOWN_CHANNEL)},l={label:"Export Session…",click:()=>sendToFocusedWindow(n,MENU_EXPORT_JSON_CHANNEL)},d={label:"Authorship Panel…",click:()=>sendToFocusedWindow(n,MENU_FINGERPRINT_CHANNEL)},p={label:"Google Drive Backup…",enabled:Boolean(o),click:()=>sendToFocusedWindow(n,MENU_GOOGLE_DRIVE_CHANNEL)},f=[...s?[{label:e.getName(),submenu:[{role:"about"},a,{type:"separator"},{role:"services"},{type:"separator"},{role:"hide"},{role:"hideOthers"},{role:"unhide"},{type:"separator"},{role:"quit"}]}]:[],{label:"File",submenu:[i,{type:"separator"},u,l,{type:"separator"},...s?[]:[a,{type:"separator"}],s?{role:"close"}:{role:"quit"}]},{label:"Edit",submenu:[{role:"undo"},{role:"redo"},{type:"separator"},{role:"cut"},{role:"copy"},{role:"paste"},{role:"selectAll"}]},{label:"View",submenu:[c,{type:"separator"},d,p,{type:"separator"},{role:"reload",accelerator:"CmdOrCtrl+R"},{role:"forceReload"},{type:"separator"},{role:"toggleDevTools",accelerator:"CmdOrCtrl+Shift+I"}]},...s?[]:[{label:"Help",submenu:[{role:"about"}]}]];return t.buildFromTemplate(f)}function bootstrap(){const{app:e,BrowserWindow:t,ipcMain:n,safeStorage:r,shell:o,Menu:s,Notification:a,screen:i,dialog:c,globalShortcut:u}=electron;if(e.disableHardwareAcceleration(),e.commandLine.appendSwitch("disable-gpu"),e.commandLine.appendSwitch("disable-software-rasterizer"),e.commandLine.appendSwitch("disable-gpu-compositing"),e.commandLine.appendSwitch("disable-features","UsePortalAccentColor"),process.argv.some((e=>/^--(log-level|enable-logging)/.test(e)))||process.env.ELECTRON_ENABLE_LOGGING||e.commandLine.appendSwitch("log-level","3"),!e.requestSingleInstanceLock())return void e.quit();if(e.setName("AEGIS Desktop"),envFile&&"function"==typeof envFile.loadEnvFile)try{const e=envFile.loadEnvFile();e.loose&&console.warn(`aegis: ${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it.`)}catch(e){console.warn(`aegis: could not read ${envFile.envFileFor()}: ${e&&e.message}`)}e.setAsDefaultProtocolClient(deepLink.PROTOCOL);let l=deepLink.parseDeepLinkArgv(process.argv);e.on("open-url",((e,n)=>{e.preventDefault();const r=deepLink.parseDeepLinkUrl(n);if(!r)return;const o=t.getFocusedWindow()||t.getAllWindows()[0];o?sendDeepLinkToWindow(o,r):l=r}));const d=createClient(credentials.clientOptions()),p=resolveUserDataDir(e),{engine:f,sessionsDir:m,settingsDir:h,settings:g}=createEngine(d,{app:e,safeStorage:r,dir:p}),y=createAccountKey({aegis:d,credentials:credentials,persistKey:e=>g.setAegisKey(e),provision:(e,t)=>autoProvision.autoProvisionApiKey(e,t,{app:"desktop"}),describeFailure:autoProvision.provisionFailureText,onChange:e=>q(e)});let E=null;const k=createGoogleConnect({aegis:d,credentials:credentials,persistKey:e=>g.setAegisKey(e),openUrl:e=>!!isSafeExternalUrl(e)&&(o.openExternal(e),!0),googleSignIn:googleSignIn,driveConnect:driveConnectLib,driveUpload:driveUploadLib,conversationExport:conversationExportLib?{...conversationExportLib,toTranscript:e=>sessionStore.toMarkdown(e)}:null,getSession:e=>sessionStore.getSession(m,e),getAuthor:()=>{try{E||(E=createFingerprintService({dir:p,getVaultBackend:()=>g.vaultBackendConfig().backend}));const e=E.status();return e&&e.ok?e:null}catch{return null}},onAccountChange:()=>q(y.status())}),_=Boolean(d.apiKey),v=autoProvision.autoProvisionApiKey(d,credentials,{app:"desktop"}).then((e=>{if(y.recordStartup(e),!e.key&&!d.apiKey){const t=e.error&&(e.error.status||e.error.message||String(e.error))||"no key returned";console.warn(`auto-provision: no account key from register-device (${t})`)}return e}));try{const{wrapProviderKeyMirror:e}=require("./lib/provider-key-mirror.js"),t=e=>console.warn(`aegis: ${e}`);e(g,envFile,{onWarn:t}),f&&f.settings&&f.settings!==g&&e(f.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not wire the shared env-file key mirror: ${e&&e.message}`)}let A=null;const b=(e,n)=>{if(function(e){const n=e&&e.sender,r=n&&t.fromWebContents(n);if(!r||r.isDestroyed())return;if(r.isFocused()&&r.isVisible())return;if(!a||!a.isSupported())return;const o=new a({title:"AEGIS Desktop",body:"Reply ready"});o.on("click",(()=>{r.isDestroyed()||(r.isMinimized()&&r.restore(),r.isVisible()||r.show(),r.focus())})),o.show()}(e),A&&"function"==typeof A.note){const e=n&&(n.model||n.modelId)||void 0;A.note({sessionId:n&&n.sessionId||null,model:e})}};registerIpc(n,d,p,(e=>{const t=g.setAegisKey(e);return e?credentials.saveApiKey(e):credentials.clearApiKey(),t}),(e=>o.openExternal(e)),b,(()=>providerRouteConfigured(f)),(()=>g.vaultBackendConfig().backend));const S=registerModelIpc(n,f,m,d,b,void 0,h);registerConfirmModeIpc(n,withAutoRoundsSwitch(createConfirmModeDispatch(g),S.modelDispatch)),registerConfirmModeIpc(n,createVaultBackendDispatch(g)),registerTelemetryIpc(n,createTelemetryDispatch(createTelemetry({dir:h,enabled:telemetryEnabled(process.env,g),appVersion:(()=>{try{return"function"==typeof e.getVersion?e.getVersion():""}catch{return""}})()}))),registerCovenantIpc(n,createCovenantDispatch(covenantModule));const C=registerQueueIpc(n,{engine:createQueueEngine(d,g),aegis:d}),I=createAutoDrain({proceed:()=>C.proceed(),settings:g,queue:queueModule,env:process.env,log:e=>{e&&"skip"!==e.type&&console.log("[auto-drain]",e.type,e.reason||e.error||"")}});let R=null;A=createAutoMint({mint:e=>(R||(R=createFingerprintService({dir:p,getVaultBackend:()=>g.vaultBackendConfig().backend})),R.mint(e||{})),settings:g}),registerAutoIpc(n,createAutoDispatch({autoDrain:I,autoMint:A})),I.start(),A.start();let w=null,P=null;function M(){return P&&!P.isDestroyed()||(P=new t({width:560,height:320,show:!1,frame:!1,alwaysOnTop:!0,skipTaskbar:!0,resizable:!1,movable:!0,fullscreenable:!1,minimizable:!1,maximizable:!1,backgroundColor:"#0d1117",icon:iconForPlatform(resolveIconsDir(e.isPackaged,process.resourcesPath,__dirname),process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0}}),P.setMenuBarVisibility(!1),P.loadFile(path.join(__dirname,"renderer","quick.html")),P.webContents.on("before-input-event",((e,t)=>{"keyDown"!==t.type||"Escape"!==t.key||P.isDestroyed()||P.hide()})),P.on("blur",(()=>{!P.isDestroyed()&&P.isVisible()&&P.hide()})),P.on("closed",(()=>{P=null}))),P}function T(){const e=M(),t=i.getCursorScreenPoint(),n=i.getAllDisplays(),r=e.getBounds(),o=quickLauncherLib.computeQuickLauncherBounds({cursor:t,displays:n,size:{width:r.width,height:r.height}});return e.setBounds(o),e.show(),e.focus(),e}function N(){const e=M();e.isVisible()?e.hide():T()}const D=createQuickLauncherDispatch(g,{isPackaged:e.isPackaged,applyConfig:function(t){if(u.unregisterAll(),!quickLauncherLib.shouldEnableGlobalShortcut({isPackaged:e.isPackaged,enabled:t.enabled}))return{active:!1,reason:null};try{if(!u.register(t.shortcut,N)){const e=`"${t.shortcut}" could not be registered — it may already be in use by another application.`;return console.warn(`[quick-launcher] ${e}`),{active:!1,reason:e}}return{active:!0,reason:null}}catch(e){const n=errorText(e);return console.warn(`[quick-launcher] failed to register shortcut "${t.shortcut}": ${n}`),{active:!1,reason:n}}},pushToMain:function(e,n){const r=n&&n.sender&&t.fromWebContents(n.sender);r&&!r.isDestroyed()&&r.hide();const o=w&&!w.isDestroyed()?w:t.getAllWindows().find((e=>e!==r))||null;return o?(o.webContents.send(QUICK_LAUNCHER_PUSH_CHANNEL,e||{}),o.isMinimized()&&o.restore(),o.isVisible()||o.show(),o.focus(),{ok:!0}):{ok:!1,reason:"no main window is open"}}});registerQuickLauncherIpc(n,D);let L=null;e.on("will-quit",(()=>{L&&"function"==typeof L.stop&&L.stop(),u.unregisterAll(),x&&"function"==typeof x.stop&&x.stop()}));let U=!1;e.on("before-quit",(t=>{!U&&f&&"function"==typeof f.unloadLocalModels&&(t.preventDefault(),Promise.resolve().then((()=>f.unloadLocalModels())).catch((()=>{})).finally((()=>{U=!0,e.quit()})))}));const F=new Set;function q(e){for(const t of F)t.isDestroyed()||t.webContents.send(ACCOUNT_STATUS_CHANNEL,e);O()}function O(){s.setApplicationMenu(buildAppMenu({app:e,Menu:s,BrowserWindow:t,updateManager:x,loggedIn:Boolean(d.apiKey)}))}const x=createUpdateManager({isPackaged:e.isPackaged,onStatus:function(e){for(const t of F)t.isDestroyed()||t.webContents.send(UPDATE_STATUS_CHANNEL,e)}});registerUpdateIpc(n,x),n.handle(`${IPC_PREFIX}accountStatus`,(()=>y.status())),n.handle(`${IPC_PREFIX}registerAccount`,(()=>y.registerAccount())),n.handle(`${IPC_PREFIX}driveSignIn`,(()=>k.signInWithGoogle())),n.handle(`${IPC_PREFIX}driveConnect`,(()=>k.connectDrive())),n.handle(`${IPC_PREFIX}driveStatus`,(()=>k.status())),n.handle(`${IPC_PREFIX}driveSyncMemory`,(()=>k.syncMemoryNow())),n.handle(`${IPC_PREFIX}driveBackupConversation`,((e,t)=>k.backupConversation({sessionId:t&&t.sessionId}))),registerExportIpc(n,sessionStore,m,(e=>c.showSaveDialog(t.getFocusedWindow(),e)),((e,t)=>fs.promises.writeFile(e,t,"utf8"))),O();const B=pathToFileURL(path.join(__dirname,"renderer","index.html")).href;function $(){const n=windowState.load(p),r=windowState.clampToDisplay(n,i.getAllDisplays(),{width:1080,height:720}),s=resolveIconsDir(e.isPackaged,process.resourcesPath,__dirname),a=new t({...r,minWidth:720,minHeight:480,show:!1,backgroundColor:"#0d1117",title:"AEGIS Desktop",icon:iconForPlatform(s,process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0,spellcheck:!0}});n&&n.isMaximized&&a.maximize(),a.webContents.setWindowOpenHandler((({url:e})=>(isSafeExternalUrl(e)&&o.openExternal(e),{action:"deny"}))),a.webContents.on("will-navigate",((e,t)=>{t!==B&&(e.preventDefault(),isSafeExternalUrl(t)&&o.openExternal(t))}));let c=null;function u(){if(a.isDestroyed())return;const e=a.isMaximized(),t=e?a.getNormalBounds():a.getBounds();windowState.save(p,{...t,isMaximized:e})}function l(){c&&clearTimeout(c),c=setTimeout(u,500)}return a.on("resize",l),a.on("move",l),a.on("close",(()=>{c&&clearTimeout(c),u()})),a.loadFile(path.join(__dirname,"renderer","index.html")),F.add(a),w=a,a.on("closed",(()=>{F.delete(a),w===a&&(w=null)})),a}e.whenReady().then((async()=>{if(!credentials.normalizeApiKey(process.env[credentials.KEY_ENV])){const e=await v,t=startupKeyOverride({mintedKey:_?"":e.key,hostKey:credentials.normalizeApiKey(g.aegisRawKey())});if(t)credentials.saveApiKey(t),d.setApiKey(t);else{const e=credentials.preferNewest(g.aegisRawKey(),g.aegisKeySavedAt());e.key&&(d.setApiKey(e.key),"shared"===e.source&&g.setAegisKey(e.key))}}try{L&&"function"==typeof L.stop&&L.stop(),L=sharedPresence.createPresence({apiKey:d.apiKey,app:"desktop",version:e.getVersion(),platform:process.platform,install:sharedFingerprint.machineFingerprint(),queueDepth:()=>{try{return queueModule.readQueue(queueModule.queuePath()).filter((e=>e&&"pending"===e.status)).length}catch{return 0}},autonomous:!1,log:(e,t)=>{"debug"!==e&&console.warn(t)}}),L.start()}catch(e){console.warn("presence: beacon not started",e&&e.message)}try{const{backfillProviderKeys:e}=require("./lib/provider-key-mirror.js"),t=e=>console.warn(`aegis: ${e}`),n=e(g,envFile,{onWarn:t});n.mirrored.length&&console.warn(`aegis: shared ${n.mirrored.join(", ")} key(s) with the other hosts (${envFile.envFileFor()})`),f&&f.settings&&f.settings!==g&&e(f.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not backfill the shared env-file key mirror: ${e&&e.message}`)}D.setConfig(g.quickLauncherConfig());const t=$();x.start(),l?(t.show(),sendDeepLinkToWindow(t,l)):T()})),e.on("window-all-closed",(()=>{"darwin"!==process.platform&&e.quit()})),e.on("activate",(()=>{const e=t.getAllWindows();if(0===e.length)return $(),void T();e.some((e=>e.isVisible()))||T()})),e.on("second-instance",((e,n)=>{const r=t.getAllWindows()[0],o=deepLink.parseDeepLinkArgv(n);if(r)r.isMinimized()&&r.restore(),r.isVisible()||r.show(),r.focus(),o&&sendDeepLinkToWindow(r,o);else{const e=$();o&&sendDeepLinkToWindow(e,o)}}))}electron&&electron.app&&bootstrap(),module.exports={createIpcDispatch:createIpcDispatch,registerIpc:registerIpc,providerRouteConfigured:providerRouteConfigured,IPC_PREFIX:IPC_PREFIX,MODEL_PREFIX:MODEL_PREFIX,SYNC_PREFIX:SYNC_PREFIX,watchTopupCredit:watchTopupCredit,bankAmount:bankAmount,TOPUP_POLL_MS:TOPUP_POLL_MS,TOPUP_POLL_TRIES:TOPUP_POLL_TRIES,CHAT_DELTA_CHANNEL:CHAT_DELTA_CHANNEL,MENU_NEW_CHAT_CHANNEL:MENU_NEW_CHAT_CHANNEL,MENU_SEARCH_CHANNEL:MENU_SEARCH_CHANNEL,MENU_EXPORT_MARKDOWN_CHANNEL:MENU_EXPORT_MARKDOWN_CHANNEL,MENU_EXPORT_JSON_CHANNEL:MENU_EXPORT_JSON_CHANNEL,MENU_FINGERPRINT_CHANNEL:MENU_FINGERPRINT_CHANNEL,MENU_GOOGLE_DRIVE_CHANNEL:MENU_GOOGLE_DRIVE_CHANNEL,DEEP_LINK_CHANNEL:DEEP_LINK_CHANNEL,UPDATE_STATUS_CHANNEL:UPDATE_STATUS_CHANNEL,UPDATE_CHECK_INTERVAL_MS:UPDATE_CHECK_INTERVAL_MS,taggedChunk:taggedChunk,maskKey:maskKey,createModelDispatch:createModelDispatch,DESKTOP_CLASSES:DESKTOP_CLASSES,readTextFileForPreview:readTextFileForPreview,PREVIEW_READ_MAX_BYTES:PREVIEW_READ_MAX_BYTES,ingestAttachment:ingestAttachment,nativeImageResizer:nativeImageResizer,createSyncDispatch:createSyncDispatch,registerModelIpc:registerModelIpc,createHeartbeatRetry:createHeartbeatRetry,describeSyncError:describeSyncError,HEARTBEAT_RETRY_BASE_MS:HEARTBEAT_RETRY_BASE_MS,HEARTBEAT_RETRY_MAX_MS:HEARTBEAT_RETRY_MAX_MS,createEngine:createEngine,resolveUserDataDir:resolveUserDataDir,importForeignMemory:importForeignMemory,isSafeExternalUrl:isSafeExternalUrl,createUpdateManager:createUpdateManager,createNpmUpdateManager:createNpmUpdateManager,createUpdateDispatch:createUpdateDispatch,describeRegistryFailure:describeRegistryFailure,UPDATE_RETRY_BACKOFF_MS:UPDATE_RETRY_BACKOFF_MS,registerUpdateIpc:registerUpdateIpc,buildAppMenu:buildAppMenu,createExportDispatch:createExportDispatch,registerExportIpc:registerExportIpc,safeExportBasename:safeExportBasename,sendDeepLinkToWindow:sendDeepLinkToWindow,QUICK_PREFIX:QUICK_PREFIX,QUICK_LAUNCHER_PUSH_CHANNEL:QUICK_LAUNCHER_PUSH_CHANNEL,createQuickLauncherDispatch:createQuickLauncherDispatch,registerQuickLauncherIpc:registerQuickLauncherIpc,createConfirmModeDispatch:createConfirmModeDispatch,createVaultBackendDispatch:createVaultBackendDispatch,withAutoRoundsSwitch:withAutoRoundsSwitch,createTelemetryDispatch:createTelemetryDispatch,registerTelemetryIpc:registerTelemetryIpc,createCovenantDispatch:createCovenantDispatch,registerCovenantIpc:registerCovenantIpc,registerConfirmModeIpc:registerConfirmModeIpc,QUEUE_PREFIX:QUEUE_PREFIX,QUEUE_PROGRESS_CHANNEL:QUEUE_PROGRESS_CHANNEL,QUEUE_MAX_TASK_CHARS:QUEUE_MAX_TASK_CHARS,QUEUE_MAX_ROUNDS:QUEUE_MAX_ROUNDS,createQueueEngine:createQueueEngine,queueEngineWithDeniedApprovals:queueEngineWithDeniedApprovals,createQueueDispatch:createQueueDispatch,registerQueueIpc:registerQueueIpc,AUTO_PREFIX:AUTO_PREFIX,createAutoDispatch:createAutoDispatch,registerAutoIpc:registerAutoIpc};
4
+ "use strict";const path=require("node:path"),fs=require("node:fs"),{execFile:execFile}=require("node:child_process"),{pathToFileURL:pathToFileURL}=require("node:url");let sharedClient;try{sharedClient=require("../client/aegis.js")}catch{sharedClient=require("./vendor/aegis.js")}const{createClient:createClient}=sharedClient;let credentials,autoProvision,sharedPresence,sharedTopup,googleSignIn,driveConnectLib,driveUploadLib,conversationExportLib;try{credentials=require("../client/credentials.js")}catch{credentials=require("./vendor/credentials.js")}try{autoProvision=require("../client/auto-provision.js")}catch{autoProvision=require("./vendor/auto-provision.js")}try{sharedPresence=require("../client/presence.js")}catch{sharedPresence=require("./vendor/presence.js")}try{sharedTopup=require("../client/topup.js")}catch{sharedTopup=require("./vendor/topup.js")}try{googleSignIn=require("../client/google-signin.js")}catch{googleSignIn=require("./vendor/google-signin.js")}try{driveConnectLib=require("../client/drive-connect.js")}catch{driveConnectLib=require("./vendor/drive-connect.js")}try{driveUploadLib=require("../client/drive-upload.js")}catch{driveUploadLib=require("./vendor/drive-upload.js")}try{conversationExportLib=require("../client/conversation-export.js")}catch{try{conversationExportLib=require("./vendor/conversation-export.js")}catch{conversationExportLib=null}}const{createGoogleConnect:createGoogleConnect}=require("./lib/google-connect.js");let sharedFingerprint;try{sharedFingerprint=require("../client/device-fingerprint.js")}catch{sharedFingerprint=require("./vendor/device-fingerprint.js")}const{createFingerprintService:createFingerprintService}=require("./lib/fingerprint.js"),{createAutoDrain:createAutoDrain,createAutoMint:createAutoMint}=require("./lib/auto.js");let envFile=null;try{envFile=require("../client/env-file.js")}catch{try{envFile=require("./vendor/env-file.js")}catch{}}let electron=null;try{electron=require("electron")}catch{}const os=require("node:os"),{createLocalEngine:createLocalEngine}=require("./lib/local/engine.js"),{createAccountKey:createAccountKey,startupKeyOverride:startupKeyOverride}=require("./lib/account-key.js"),{createSettingsStore:createSettingsStore,isReservedNamespace:isReservedNamespace}=require("./lib/settings.js"),sessionStore=require("./lib/sync/sessions.js"),memoryQueue=require("./lib/sync/memory-queue.js"),persistGate=require("./lib/sync/persist-gate.js"),avatarStore=require("./lib/avatar/store.js"),windowState=require("./lib/window-state.js"),deepLink=require("./lib/deep-link.js"),quickLauncherLib=require("./lib/quick-launcher.js");let foreignMemory;try{foreignMemory=require("../client/foreign-memory.js")}catch{foreignMemory=require("./vendor/foreign-memory.js")}const localTools=require("./lib/local/tools.js"),queueModule=require("./lib/local/queue.js"),autonomousModule=require("./lib/local/autonomous.js"),{autoContinuePlan:autoContinuePlan,autoContinueLimit:autoContinueLimit,autoRoundsDefault:autoRoundsDefault}=require("./lib/local/autonomous.js"),entitlementModule=require("./lib/local/entitlement.js"),telemetryModule=require("./lib/local/telemetry.js"),covenantModule=require("./lib/local/covenant.js"),{createTelemetry:createTelemetry,telemetryEnabled:telemetryEnabled}=telemetryModule,IPC_PREFIX="aegis:",MODEL_PREFIX="model:",SYNC_PREFIX="sync:",TOOLS_PREFIX="tools:",QUICK_PREFIX="quick:",QUEUE_PREFIX="queue:",AUTO_PREFIX="auto:",DESKTOP_CLASSES=Object.freeze(["aegis","byok","local"]),CHAT_DELTA_CHANNEL=`${IPC_PREFIX}chatDelta`,MENU_NEW_CHAT_CHANNEL=`${IPC_PREFIX}menuNewChat`,MENU_SEARCH_CHANNEL=`${IPC_PREFIX}menuSearch`,MENU_EXPORT_MARKDOWN_CHANNEL=`${IPC_PREFIX}menuExportMarkdown`,MENU_EXPORT_JSON_CHANNEL=`${IPC_PREFIX}menuExportJson`,MENU_FINGERPRINT_CHANNEL=`${IPC_PREFIX}menuFingerprint`,MENU_GOOGLE_DRIVE_CHANNEL=`${IPC_PREFIX}menuGoogleDrive`,DEEP_LINK_CHANNEL=`${IPC_PREFIX}deepLink`,QUICK_LAUNCHER_PUSH_CHANNEL=`${IPC_PREFIX}quickLauncherPush`,QUEUE_PROGRESS_CHANNEL=`${QUEUE_PREFIX}progress`,QUEUE_MAX_TASK_CHARS=8e3,QUEUE_MAX_ROUNDS=200,QUEUE_MAX_WORKERS=8,QUEUE_EFFORTS=new Set(["low","medium","high","max"]);function taggedChunk(e,t){return{...e&&"object"==typeof e?e:{delta:e},id:t}}const APP_VERSION=require("./package.json").version;function maskKey(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}function upgradeInfo(e){const t=e&&e.status,n=e&&e.data||{},r="string"==typeof n.error?n.error:"";if(402!==t&&"free_session_limit_reached"!==r)return null;const o=null!=n.tokensUsed?n.tokensUsed:null!=n.sessionsUsed?n.sessionsUsed:null,s=null!=n.tokenLimit?n.tokenLimit:null!=n.freeSessionLimit?n.freeSessionLimit:null;return{url:n.upgradeUrl||"https://aegiscloud.org/go/upgrade?s=desktop&c=status_card",used:o,limit:s,code:r||"free_session_limit_reached"}}function errorText(e){return e&&e.message?e.message:String(e)}function isAbortShapedError(e){return!(!e||"object"!=typeof e||!0!==e.aegisCancelled&&"AbortError"!==e.name&&"ABORT_ERR"!==e.code)}function abortedTurnPayload(e){return{aborted:!0,status:0,code:"ABORT_ERR",message:errorText(e),choices:[{message:{content:""}}]}}function describeSyncError(e){const t=e&&(e.status||e.response&&e.response.status)||0,n=errorText(e);return upgradeInfo(e)?{kind:"quota",status:t||402,message:n,hint:"the plan's synced-token ceiling is reached — free space in the account dashboard or upgrade to keep syncing"}:401===t?{kind:"auth",status:t,message:n,hint:"the memory token was refused — re-enter your AEGIS API key to exchange a new one"}:{kind:"error",status:t||null,message:n,hint:null}}function syncErrorReason(e){return e?e.hint?`${e.message} — ${e.hint}`:e.message:"sync failed"}async function billingResult(e){try{const t=await e();return{ok:!0,url:t&&t.url||null,status:0,reason:null,setupRequired:!1,upgrade:null}}catch(e){const t=e&&e.data||{};return{ok:!1,url:null,status:e&&e.status||0,reason:errorText(e),setupRequired:Boolean(t.setup_required),upgrade:upgradeInfo(e)}}}const{bankAmount:bankAmount,parseTopupAmount:parseTopupAmount,startTopup:startTopup,createCreditWatch:createCreditWatch,TOPUP_POLL_MS:TOPUP_POLL_MS,TOPUP_POLL_TRIES:TOPUP_POLL_TRIES}=sharedTopup;let topupWatch=null;function watchTopupCredit(e,t){const n=t||{},r=n.intervalMs||TOPUP_POLL_MS,o=n.log;topupWatch&&clearInterval(topupWatch);const s=createCreditWatch(e,n.maxTries?{maxTries:n.maxTries}:void 0),i=()=>{topupWatch&&clearInterval(topupWatch),topupWatch=null,s.stop()},a=async()=>{const e=await s.tick();"credited"===e.state?(i(),(e=>{if("function"!=typeof n.notify)try{const t=electron&&electron.Notification;t&&t.isSupported()&&new t({title:"AEGIS Desktop",body:`Bank credited — €${e.toFixed(2)} available`}).show()}catch{}else n.notify(e)})(e.amount)):"expired"===e.state&&(i(),o&&o("top-up: no credit observed within the watch window; stopping"))};return topupWatch=setInterval(a,r),topupWatch&&"function"==typeof topupWatch.unref&&topupWatch.unref(),{stop:i,tick:a,get baseline(){return s.baseline}}}async function saveMemoryWithQueue(e,t,n,r){const o=avatarStore.normalizeMemoryEntry(n);try{const t=await e.memorySave(o);return r&&o&&"object"==typeof o&&r.awardSave(o,{session:o.session}),t}catch(e){const s=upgradeInfo(e);if(s)return{ok:!1,queued:0,saved:0,upgrade:s,reason:errorText(e)};if(!t||!n)throw e;return memoryQueue.enqueue(t,o),r&&o&&"object"==typeof o&&r.awardQueued(o,{session:o.session}),{ok:!0,queued:!0,reason:errorText(e)}}}async function normalizeMemoryRead(e){try{const t=await e,n=quotaFromPayload(t);return n?Object.assign({},t,{upgrade:n}):t}catch(e){const t=upgradeInfo(e);if(!t)throw e;return{entries:[],upgrade:t}}}function quotaFromPayload(e){if(!e||"object"!=typeof e)return null;const t=null!=e.tokensUsed?e.tokensUsed:null,n=null!=e.tokenLimit?e.tokenLimit:null;return null==t||null==n||n<=0||t<n?null:{url:"https://aegiscloud.org/go/upgrade?s=desktop&c=memory_quota",used:t,limit:n,code:"sync_quota_reached"}}async function importForeignMemory(e,t,n,r){const o=n||{},s=foreignMemory.scan({sources:o.sources,limit:o.limit||1e3}),i=foreignMemory.describe(s),a=s.sources.map((e=>({id:e.id,label:e.label,verified:e.verified,present:e.present,count:e.count,skipped:e.skipped,files:e.files}))),c={summary:i,totals:s.totals,sources:a};if(!o.confirm||!s.entries.length)return{...c,ok:!0,dryRun:!o.confirm,saved:0,queued:0};let u=0,l=0;const d=[];let p=null;for(const n of foreignMemory.chunk(s.entries,200))try{const t=await e.memorySaveBatch(n);if(u+=t&&t.saved||n.length,r&&n.length){const e=n[0]||{};r.awardImports(n,{source:e.session||e.source||"foreign-import"})}}catch(e){if(p=upgradeInfo(e),!p&&t)for(const e of n)memoryQueue.enqueue(t,e),l+=1,r&&r.awardQueued(e,{session:e&&e.session});d.push(errorText(e));break}return{...c,ok:0===d.length,dryRun:!1,saved:u,queued:l,upgrade:p,reason:d[0]||null}}function resolveIconsDir(e,t,n){return e?path.join(t,"icons"):path.join(n,"build")}function iconForPlatform(e,t){return"darwin"===t?path.join(e,"icon.icns"):"win32"===t?path.join(e,"icon.ico"):path.join(e,"icon.png")}function isSafeExternalUrl(e){if("string"!=typeof e||!e)return!1;try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}function providerRouteConfigured(e){try{const t=e&&e.settings&&e.settings.list;return"function"==typeof t&&(t.call(e.settings)||[]).some((e=>{if(!e||!e.provider||isReservedNamespace(e.provider))return!1;const t="string"==typeof e.baseURL?e.baseURL.trim():"";return Boolean(e.configured||t)}))}catch{return!1}}function createIpcDispatch(e,t,n,r,o,s,i){let a=null;const c=new Proxy({},{get(e,n){a||(a=createFingerprintService({dir:t,getVaultBackend:i}));const r=a[n];return"function"==typeof r?r.bind(a):r},has:(e,n)=>(a||(a=createFingerprintService({dir:t,getVaultBackend:i})),n in a)}),u=()=>{try{return Boolean("function"==typeof o&&o())}catch{return!1}},l=r||(()=>Promise.reject(new Error("no opener configured")));return{status:()=>({appVersion:APP_VERSION,clientVersion:e.clientVersion,apiBase:e.apiBase,keyConfigured:Boolean(e.apiKey),keyMask:maskKey(e.apiKey),providerConfigured:u()}),setApiKey:t=>{try{const r=t&&t.key;return e.setApiKey(r||""),n&&n(e.apiKey),{ok:!0,keyConfigured:Boolean(e.apiKey),keyMask:maskKey(e.apiKey)}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},verifyApiKey:async()=>{try{return{ok:!0,...await e.verifyApiKey()}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},tokenBankBalance:()=>e.tokenBankBalance(),billingCheckout:()=>billingResult((()=>e.billingCheckout())),tokenBankTopup:async t=>{const n=parseTopupAmount(t&&t.amountEur);if(!n.ok)return{ok:!1,url:null,status:400,reason:n.message,setupRequired:!1,upgrade:null};const r=await startTopup(e,n.amount);return!0===r.ok&&r.url&&watchTopupCredit(e),{ok:!0===r.ok,url:r.url,status:r.status,reason:r.ok?null:r.hint?`${r.message} — ${r.hint}`:r.message,setupRequired:r.setupRequired,upgrade:null}},listModels:()=>e.listModels(),chatCompletion:t=>e.chatCompletion({prompt:t&&t.prompt,system:t&&t.system,model:t&&t.model,mode:t&&t.mode,maxTokens:t&&t.maxTokens,stream:t&&t.stream,onStream:t&&t.onStream}),fingerprintStatus:()=>c.status(),fingerprintKeygen:e=>c.keygen(e||{}),fingerprintMint:e=>c.mint(e||{}),fingerprintVerify:e=>c.verify(e||{}),fingerprintBackup:e=>c.backup(e||{})
5
+ // gdrive:AEGIS-AGPL/records and writes the `.anchor.json` link beside the
6
+ ,fingerprintPublish:e=>c.publish(e||{}),fingerprintAnchor:e=>c.anchor(e||{}),fingerprintVault:()=>c.vaultList(),fingerprintVaultAudit:()=>c.vaultAudit(),byokStatus:()=>e.byokStatus(),byokSet:t=>e.byokSet(t&&t.provider,t&&t.apiKey),memorySearch:t=>normalizeMemoryRead(e.memorySearch(t&&t.query,t&&t.limit)),memorySave:n=>saveMemoryWithQueue(e,t,n&&n.entry,s),memoryList:t=>normalizeMemoryRead(e.memoryList(t&&t.limit)),verifyToken:t=>e.verifyToken(t&&t.token),memoryActivate:t=>e.memoryActivate(t&&t.token),memoryPull:t=>e.memoryPull(t&&t.since),memorySaveBatch:t=>e.memorySaveBatch(t&&t.entries),memoryImport:n=>importForeignMemory(e,t,n,s),importConversation:t=>e.importConversation(t||{}),openExternal:e=>{const t=e&&e.url;return isSafeExternalUrl(t)?Promise.resolve(l(t)).then((()=>({ok:!0})),(e=>({ok:!1,reason:errorText(e)}))):Promise.resolve({ok:!1,reason:"unsupported URL scheme"})}}}function withReplyNotify(e,t,n){return n?e.then((e=>(n(t,e),e))):e}function registerIpc(e,t,n,r,o,s,i,a){const c=createIpcDispatch(t,n,r,o,i,void 0,a);for(const[t,n]of Object.entries(c))"chatCompletion"!==t?e.handle(`${IPC_PREFIX}${t}`,((e,t)=>n(t))):e.handle(`${IPC_PREFIX}${t}`,((e,t)=>{const r={...t||{}};if(!r.stream)return withReplyNotify(n(r),e,s);const o=e&&e.sender;return withReplyNotify(n({...r,stream:!0,onStream:e=>{o&&"function"==typeof o.send&&!o.isDestroyed()&&o.send(CHAT_DELTA_CHANNEL,taggedChunk(e,r.sessionId))}}),e,s)}));return c}function createConfirmModeDispatch(e){if(!e)throw new Error("createConfirmModeDispatch requires a settings store");return{getConfirmMode:()=>({enabled:e.getConfirmMode()}),setConfirmMode:t=>{const n=t&&t.enabled;return"boolean"!=typeof n?{enabled:e.getConfirmMode()}:{enabled:e.setConfirmMode(n)}}}}function withAutoRoundsSwitch(e,t){const n=e.setConfirmMode;return{...e,setConfirmMode:e=>{const r=n(e);return e&&"boolean"==typeof e.enabled&&t&&"function"==typeof t.setAutoRounds&&t.setAutoRounds(!1===e.enabled),r}}}function registerConfirmModeIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`${IPC_PREFIX}${n}`,((e,t)=>r(t)));return t}function createVaultBackendDispatch(e){if(!e)throw new Error("createVaultBackendDispatch requires a settings store");return{getVaultBackend:()=>e.vaultBackendConfig(),setVaultBackend:t=>e.setVaultBackendConfig(t&&t.backend)}}function createTelemetryDispatch(e){const t=e||null;return{telemetryEvent:e=>{try{if(!t||"function"!=typeof t.record)return{ok:!1,reason:"telemetry off"};const n=e&&"object"==typeof e?e:{};return t.record(n.event,{campaign:n.campaign,surface:n.surface})?{ok:!0}:{ok:!1,reason:"not an allowlisted funnel event"}}catch(e){return{ok:!1,reason:errorText(e)}}},telemetryReport:()=>{try{return t&&"function"==typeof t.report?t.report():{enabled:!1,transport:"off"}}catch(e){return{enabled:!1,error:errorText(e)}}}}}function createCovenantDispatch(e){return{covenantStatus:()=>({ok:!0,covenant:e.snapshot(),gapReport:e.gapReport()}),covenantGapReport:()=>({ok:!0,gapReport:e.gapReport()})}}function registerCovenantIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`${IPC_PREFIX}${n}`,((e,t)=>r(t)));return t}function registerTelemetryIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`${IPC_PREFIX}${n}`,((e,t)=>r(t)));return t}function safeExportBasename(e){return(e&&(e.title||e.id)||"session").replace(/[^\w.-]+/g,"_").slice(0,80)||"session"}function createExportDispatch(e,t,n,r){return{exportSession:async o=>{const s=o&&o.sessionId,i=o&&"json"===o.format?"json":"markdown",a=s?e.getSession(t,s):null;if(!a)return{ok:!1,reason:"session not found"};const c="json"===i?e.toJson(a):e.toMarkdown(a),u="json"===i?"json":"md",l="json"===i?[{name:"JSON",extensions:["json"]}]:[{name:"Markdown",extensions:["md"]}],d=await n({defaultPath:`${safeExportBasename(a)}.${u}`,filters:l});if(!d||d.canceled||!d.filePath)return{ok:!1,canceled:!0};try{await r(d.filePath,c)}catch(e){return{ok:!1,reason:errorText(e)}}return{ok:!0,filePath:d.filePath}}}}function registerExportIpc(e,t,n,r,o){const s=createExportDispatch(t,n,r,o);for(const[t,n]of Object.entries(s))e.handle(`${IPC_PREFIX}${t}`,((e,t)=>n(t)));return s}function createQuickLauncherDispatch(e,t={}){const n=Boolean(t.isPackaged),r=t.applyConfig||(()=>({active:!1,reason:null})),o=t.pushToMain||(()=>({ok:!1,reason:"no main window"}));let s={active:!1,reason:null};return{status:function(){return{...e.quickLauncherConfig(),packaged:n,...s}},setConfig:function(t){const o=e.setQuickLauncherConfig({enabled:t&&t.enabled,shortcut:t&&t.shortcut});return s=r(o)||{active:!1,reason:null},{...o,packaged:n,...s}},pushToMain:(e,t)=>o(e,t)}}function registerQuickLauncherIpc(e,t){for(const[n,r]of Object.entries(t))"pushToMain"!==n?e.handle(`${QUICK_PREFIX}${n}`,((e,t)=>r(t))):e.handle(`${QUICK_PREFIX}${n}`,((e,t)=>r(t,e)));return t}function resolveUserDataDir(e){if(e&&"function"==typeof e.getPath)try{return e.getPath("userData")}catch{}return path.join(os.homedir(),".aegiscode")}function createEngine(e,{app:t,safeStorage:n,dir:r,sessionsDir:o}={}){const s=r||resolveUserDataDir(t),i=createSettingsStore({dir:s,safeStorage:n});return i.migrateLegacyAegisKey(),{engine:createLocalEngine({aegis:e,settings:i}),sessionsDir:o||sessionStore.resolveStoreDir(s),settingsDir:s,settings:i}}const PREVIEW_READ_MAX_BYTES=524288;function readTextFileForPreview(e){try{const t=e&&"string"==typeof e.file?e.file:"",n=e&&"string"==typeof e.cwd?e.cwd:"";if(!t||!n||!path.isAbsolute(n))return null;const r=fs.realpathSync(n),o=fs.realpathSync(path.resolve(r,t)),s=path.relative(r,o);if(""===s||s.startsWith("..")||path.isAbsolute(s))return null;const i=fs.statSync(o);if(!i.isFile())return null;if(i.size<=PREVIEW_READ_MAX_BYTES)return{text:fs.readFileSync(o,"utf8"),truncated:!1};const a=fs.openSync(o,"r");try{const e=Buffer.alloc(PREVIEW_READ_MAX_BYTES),t=fs.readSync(a,e,0,PREVIEW_READ_MAX_BYTES,0);let n=e.toString("utf8",0,t);const r=n.lastIndexOf("\n");return r>0&&(n=n.slice(0,r+1)),{text:n,truncated:!0}}finally{fs.closeSync(a)}}catch{return null}}const attachmentsModule=require("./lib/local/attachments.js");function nativeImageResizer(e,t){try{const{nativeImage:n}=require("electron");if(!n)return null;const r=n.createFromBuffer(e);if(!r||r.isEmpty())return null;const o=r.getSize(),s=Math.max(o.width,o.height),i=s>1568?r.resize({width:Math.round(1568*o.width/s)}):r,a="image/png"===t?i.toPNG():i.toJPEG(82);return a&&a.length?{buffer:a,mime:"image/png"===t?"image/png":"image/jpeg"}:null}catch{return null}}function ingestAttachment(e,{resize:t=nativeImageResizer}={}){const n=e&&"string"==typeof e.path?e.path.trim():"";if(!n)return{ok:!1,reason:"no path"};if(!path.isAbsolute(n))return{ok:!1,reason:"not an absolute path"};let r,o,s;try{r=fs.realpathSync(n),o=fs.statSync(r)}catch{return{ok:!1,reason:"not found"}}if(!o.isFile())return{ok:!1,reason:"not a regular file"};if(0===o.size)return{ok:!1,reason:"empty file"};if(o.size>attachmentsModule.MAX_FILE_BYTES)return{ok:!1,reason:`too large (${attachmentsModule.humanBytes(o.size)})`};try{s=fs.readFileSync(r)}catch{return{ok:!1,reason:"unreadable"}}const i=attachmentsModule.sniff(s),a={path:r,name:path.basename(r),size:o.size,mime:i.mime,kind:i.kind};if("image"===i.kind){let{mime:e}=i,n=s,r=!1;if(n.length>attachmentsModule.MAX_IMAGE_BYTES&&"function"==typeof t){const o=t(s,e);o&&o.buffer&&o.buffer.length<n.length&&(n=o.buffer,e=o.mime,r=!0)}const o=attachmentsModule.toDataUrl(n,e);return o?{ok:!0,attachment:{...a,kind:"image",mime:e,size:n.length,dataUrl:o,scaled:r,vision:attachmentsModule.isVisionMime(e)}}:{ok:!1,reason:"could not encode image"}}if("text"===i.kind){if(o.size>attachmentsModule.MAX_TEXT_BYTES){let e=s.subarray(0,attachmentsModule.MAX_TEXT_BYTES).toString("utf8");const t=e.lastIndexOf("\n");return t>0&&(e=e.slice(0,t+1)),{ok:!0,attachment:{...a,kind:"text",text:e,truncated:!0}}}return{ok:!0,attachment:{...a,kind:"text",text:s.toString("utf8"),truncated:!1}}}return"pdf"===i.kind?{ok:!0,attachment:{...a,kind:"pdf"}}:{ok:!0,attachment:{...a,kind:"binary"}}}function createModelDispatch(e,{env:t=process.env,settings:n}={}){const r=new Map;let o,s=autoRoundsDefault(t),i=!1;const a=()=>{const t=n||e&&e.settings||null,r=e=>"boolean"==typeof e?e:void 0;let a;try{if(t&&"function"==typeof t.confirmModeState){const e=t.confirmModeState();a=r(e&&e.enabled)}void 0===a&&t&&"function"==typeof t.getConfirmMode&&(a=r(t.getConfirmMode()))}catch{}return i||void 0===a||(void 0===o?o=a:a!==o&&(i=!0,s=!0)),!(!s||!t||void 0===a)&&!1===a},c={listClasses:async()=>(await e.listClasses()).filter((e=>DESKTOP_CLASSES.includes(e.class))),listModels:t=>e.listModels(t&&t.class),chat:n=>{const o=n&&n.onStream;if("function"!=typeof o)return e.chat(n,o);const s=n&&n.sessionId||"";return e.chat(n,(n=>{if(n&&n.rounds&&n.rounds.id&&a()){const i=autoContinuePlan({on:!0,used:r.get(s)||0,limit:autoContinueLimit(t)});if(r.set(s,i.used),i.auto){const t="function"==typeof e.respondRoundsAsk?e.respondRoundsAsk(n.rounds.id,!0):{ok:!1};if(t&&t.ok){const e=Number(n.rounds.spent)||0;return void o({note:`auto mode: the ${e}-round limit was reached — continuing automatically (${i.used}/${i.cap}, then it asks).`})}}}o(n)}))},"settings.get":()=>e.settings.list().filter((e=>!(e&&isReservedNamespace(e.provider)))),"settings.set":t=>e.settings.set(t&&t.provider,{baseURL:t&&t.baseURL,key:t&&t.key}),"settings.remove":t=>e.settings.remove(t&&t.provider),"userModels.get":()=>e.userModels(),"userModels.add":t=>e.addUserModel(t&&t.provider,t&&t.model),"userModels.remove":t=>e.removeUserModel(t&&t.provider,t&&t.model),"userModels.discover":t=>e.discoverModels(t&&t.provider),"userModels.addAll":t=>e.addUserModels(t&&t.provider,t&&t.ids),"userModels.canDiscover":t=>Boolean(e.canDiscoverModels(t&&t.provider)),"userModels.discoverable":()=>e.discoverableProviders(),"memoryPersist.get":()=>e.settings.memoryPersistState(),"memoryPersist.set":t=>e.settings.setMemoryPersist(Boolean(t&&t.enabled)),cancel:t=>e.cancel(t&&t.sessionId),respondApproval:t=>e.respondApproval(t&&t.approvalId,t&&t.decision),respondRoundsAsk:t=>"function"==typeof e.respondRoundsAsk?e.respondRoundsAsk(t&&t.roundsAskId,t&&t.decision):{ok:!1},clearApprovals:t=>e.clearSessionApprovals(t&&t.sessionId)};return Object.defineProperties(c,{autoRoundsOn:{value:a,enumerable:!1},setAutoRounds:{value:e=>{s=Boolean(e),i=!0},enumerable:!1}}),c}function createSyncDispatch(e,t,n,r){let o=null;function s(){return Boolean(n&&n.apiKey)}async function i(){const r=e.listPending(t);if(!s())return{ok:!1,queued:r.length,reason:"no AEGIS key configured"};const i=await async function(){const e=memoryQueue.listQueued(t);if(!e.length)return{flushed:0,remaining:0,upgrade:null};const r=[];let o=0,s=null;for(let t=0;t<e.length;t+=1)try{await n.memorySave(e[t]),o+=1}catch(n){const o=upgradeInfo(n);if(o){s=o,r.push(...e.slice(t));break}r.push(e[t])}return memoryQueue.save(t,r),{flushed:o,remaining:r.length,upgrade:s}}();if(!r.length)return{ok:!0,queued:0,pushed:0,memoryFlushed:i.flushed,upgrade:i.upgrade};let a=0,c=null,u=null;for(const o of r)try{const r=await n.conversationSyncPush({session_id:o.id,title:o.title,messages:o.messages}),s=r&&(r.session_id||r.id);e.markSynced(t,o.id,{remoteId:s}),a+=1}catch(e){if(c=e,u=describeSyncError(e),"quota"===u.kind||"auth"===u.kind)break}const l=e.listPending(t).length;a&&(o=Date.now());const d=(c?upgradeInfo(c):null)||i.upgrade;return 0===a&&c?{ok:!1,queued:l,reason:syncErrorReason(u),failed:u?[u]:[],kind:u?u.kind:"error",status:u?u.status:0,hint:u?u.hint:null,memoryFlushed:i.flushed,upgrade:d}:{ok:!0,queued:l,pushed:a,failed:u?[u]:[],memoryFlushed:i.flushed,upgrade:d}}const a=persistGate.createAutoPush({push:i,dir:r||t});return{auto:()=>a.auto(),memoryPersistState:()=>a.gate(),listSessions:()=>({sessions:e.listSessions(t)}),open:n=>e.getSession(t,n&&n.sessionId),save:n=>e.upsertSession(t,n||{}),append:n=>e.appendMessage(t,n&&n.sessionId,n&&n.message),delete:n=>e.deleteSession(t,n&&n.sessionId),push:i,pull:async function(){if(!s())return{ok:!1,merged:0,reason:"no AEGIS key configured"};try{const r=await n.conversationSyncPull(),s=e.mergeRemoteSessions(t,r&&r.sessions||[]);return o=Date.now(),{ok:!0,merged:s,failed:[],upgrade:null}}catch(e){const t=describeSyncError(e);return{ok:!1,merged:0,reason:syncErrorReason(t),failed:[t],kind:t.kind,status:t.status,hint:t.hint,upgrade:upgradeInfo(e)}}},status:()=>({count:e.listSessions(t).length,pending:e.listPending(t).length,cloud:s(),lastSyncAt:o})}}const HEARTBEAT_RETRY_BASE_MS=5e3,HEARTBEAT_RETRY_MAX_MS=3e4;function createHeartbeatRetry(e,t={}){const n="function"==typeof t.now?t.now:()=>Date.now(),r=Number(t.baseMs)>0?Number(t.baseMs):HEARTBEAT_RETRY_BASE_MS,o=Number(t.maxMs)>0?Number(t.maxMs):HEARTBEAT_RETRY_MAX_MS;let s=0,i=0,a=null,c=!1;function u(e){s+=1;const t=Math.min(o,r*2**Math.max(0,s-1));return a=e||"push failed",i=n()+t,{attempted:!0,ok:!1,error:a,failures:s,retryInMs:t}}return{run:async function(){const t=n();if(s>0&&t<i)return{attempted:!1,ok:!1,error:a,failures:s,retryInMs:i-t};if(c)return{attempted:!1,ok:!1,error:a,failures:s,retryInMs:0};c=!0;try{const t=await e();return t&&!1===t.ok?u(t.reason||t.kind||"push failed"):(s=0,i=0,a=null,{attempted:!0,ok:!0,error:null,failures:0,retryInMs:0,result:t})}catch(e){return u(errorText(e))}finally{c=!1}},state:function(){const e=n();return{failures:s,lastError:a,retryInMs:s>0&&i>e?i-e:0}},recordFailure:e=>u(errorText(e))}}function registerModelIpc(e,t,n,r,o,s,i){const a=createModelDispatch(t),c=createSyncDispatch(sessionStore,n,r,i),u=createHeartbeatRetry((()=>c.push()),s);function l(){const e=u.run();e&&"function"==typeof e.catch&&e.catch((e=>u.recordFailure(e)))}for(const[t,n]of Object.entries(a))"chat"!==t?"listModels"!==t?e.handle(`${MODEL_PREFIX}${t}`,((e,t)=>n(t))):e.handle(`${MODEL_PREFIX}${t}`,((e,t)=>(l(),n(t)))):e.handle(`${MODEL_PREFIX}${t}`,((e,t)=>{const r={...t||{}},s=!0===r.bestEffort;delete r.bestEffort;const i="low"===r.effort||"medium"===r.effort||"max"===r.effort?r.effort:"high";r.effort=i;const a=e&&e.sender,c=r.class||"model",u=n({...r,onStream:e=>{a&&"function"==typeof a.send&&!a.isDestroyed()&&a.send(CHAT_DELTA_CHANNEL,taggedChunk(e,r.sessionId))}});return s?u.then((t=>(o&&o(e,t),t)),(e=>{const t=e&&"number"==typeof e.status?e.status:0,n=e&&e.code||"";return console.warn(`[model] background ${c} turn produced no answer: ${errorText(e)}${t?` (status ${t})`:""}${n?` [${n}]`:""}`),{bestEffortFailed:!0,status:t,code:n||void 0,message:errorText(e),choices:[{message:{content:""}}]}})):withReplyNotify(u,e,o).catch((e=>{if(!isAbortShapedError(e))throw e;return console.warn(`[model] ${c} turn stopped before it finished: ${errorText(e)} [ABORT_ERR]`),abortedTurnPayload(e)}))}));e.on(`${MODEL_PREFIX}readTextFile`,((e,t)=>{e.returnValue=readTextFileForPreview(t)})),e.handle(`${IPC_PREFIX}attachments:ingest`,(async(e,t)=>ingestAttachment(t)));for(const[t,n]of Object.entries(c))"status"!==t?e.handle(`${SYNC_PREFIX}${t}`,((e,t)=>n(t))):e.handle(`${SYNC_PREFIX}${t}`,((e,t)=>{l();const r=n(t);return r&&"object"==typeof r?{...r,retry:u.state()}:r}));return{modelDispatch:a,syncDispatch:c,heartbeat:u}}function createQueueEngine(e,t){return createLocalEngine({aegis:e,settings:t,getConfirmMode:()=>!1})}function queueEngineWithDeniedApprovals(e){return e&&"function"==typeof e.chat?{...e,chat:(t,n)=>e.chat(t,(t=>{(t=>{const n=t&&t.approval;if(n&&n.id&&"function"==typeof e.respondApproval)try{e.respondApproval(n.id,"deny")}catch{}})(t),(t=>{const n=t&&t.rounds;if(n&&n.id&&"function"==typeof e.respondRoundsAsk)try{e.respondRoundsAsk(n.id,!1)}catch{}})(t),"function"==typeof n&&n(t)}))}:e}function isExistingDir(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function clampInt(e,t,n){const r=Number(e);return!Number.isInteger(r)||r<t||r>n?null:r}function createQueueDispatch({engine:e,env:t=process.env,queue:n=queueModule,autonomous:r=autonomousModule,entitlement:o=entitlementModule.createEntitlement({}),log:s=(()=>{})}={}){if(!e||"function"!=typeof e.chat)throw new Error("createQueueDispatch: a local engine with chat() is required");let i=null,a=!1,c=!1;const u=r.createQueueWorker({engine:queueEngineWithDeniedApprovals(e),env:t,log:e=>{e&&"start"===e.type&&(i=e.taskId),e&&"finish"===e.type&&(i=null),s(e)},canFanOut:()=>o.current().entitled});function l(){const e=n.loadQueue(t);return{ok:!0,items:e,pending:n.pendingCount(e),running:e.find((e=>e&&"running"===e.status))||null,draining:c,stopping:a,defaultCwd:process.cwd(),defaultModel:r.resolveModel({env:t}),queueFile:n.queuePath(t),runs:n.readRuns(t,{limit:20}),entitlement:o.current()}}const d=e=>(e||[]).map((e=>({id:e.id,ok:Boolean(e.ok),error:e.error||null})));return{enqueue:async e=>{await o.refresh();const s=o.gateFanout({workers:clampInt(e&&e.workers,1,QUEUE_MAX_WORKERS),fanout:Boolean(e&&!0===e.fanout)});if(!s.ok)return{...s,...l()};const{opts:i,error:a}=function(e){const t=e||{},n=String(null==t.task?"":t.task).trim();if(!n)return{error:"a queued task needs text"};if(n.length>QUEUE_MAX_TASK_CHARS)return{error:`task text is too long (${n.length} > ${QUEUE_MAX_TASK_CHARS} chars)`};const o=String(null==t.cwd?"":t.cwd).trim()||process.cwd();if(!path.isAbsolute(o))return{error:"the working directory must be an absolute path"};if(!isExistingDir(o))return{error:`not a directory: ${o}`};const s=r.normalizeClass(t.class),i=String(null==t.model?"":t.model).trim().slice(0,120)||null,a=r.modelRefusal(i,s);if(a)return{error:a};const c=String(null==t.effort?"":t.effort).trim().toLowerCase();return{opts:{task:n,cwd:o,class:s,model:i,effort:QUEUE_EFFORTS.has(c)?c:null,workers:clampInt(t.workers,1,QUEUE_MAX_WORKERS),maxRounds:clampInt(t.maxRounds,1,QUEUE_MAX_ROUNDS),singlePass:!(!0===t.fanout||!0===t.autonomous),commit:Boolean(t.commit),source:"desktop"}}}(e);return a?{ok:!1,reason:a,...l()}:{ok:!0,item:n.addTask(t,i),...l()}},list:()=>l(),entitlement:async e=>(await o.refresh({force:Boolean(e&&!0===e.force)}),{ok:!0,...l()}),clear:e=>({...n.clearQueue(t,{all:Boolean(e&&e.all)}),ok:!0,...l()}),retry:e=>{const r=e&&e.id,o=n.retryTask(t,r);return o?{ok:!0,item:o,...l()}:{ok:!1,reason:`no task #${r}`,...l()}},remove:e=>{const r=e&&e.id,o=n.loadQueue(t),s=n.findTask(o,r);return s?"running"===s.status?{ok:!1,reason:`task #${s.id} is running — stop the drain first`,...l()}:(n.saveQueue(t,o.filter((e=>Number(e&&e.id)!==Number(s.id)))),{ok:!0,removed:s.id,...l()}):{ok:!1,reason:`no task #${r}`,...l()}},drain:()=>async function(){if(c)return{ok:!1,reason:"a drain is already running in this window",...l()};let e;c=!0,a=!1;try{const t=await u.proceed({max:1});e=t.locked?{ok:!1,locked:!0,holder:t.holder,ran:[]}:{ok:!0,ran:d(t.ran)}}catch(t){e={ok:!1,reason:errorText(t),ran:[]}}return c=!1,i=null,{...e,...l()}}(),proceed:()=>async function(){if(c)return{ok:!1,reason:"a drain is already running in this window",...l()};c=!0,a=!1;const e=[];let t;try{for(;;){const n=await u.proceed({max:1});if(n.locked){t={ok:!1,locked:!0,holder:n.holder,ran:d(e)};break}if(!n.ran.length){t={ok:!0,stopped:a,ran:d(e)};break}if(e.push(...n.ran),a){t={ok:!0,stopped:!0,ran:d(e)};break}}}catch(n){t={ok:!1,reason:errorText(n),ran:d(e)}}return c=!1,i=null,{...t,...l()}}(),stop:e=>{a=!0;const t=e&&null!=e.id?e.id:i,n=null==t?null:u.cancel(t);return{ok:!0,wasDraining:c,cancelled:n,...l()}}}}function createAutoDispatch({autoDrain:e,autoMint:t}={}){if(!e||"function"!=typeof e.state)throw new Error("createAutoDispatch: the auto-drain automation is required");if(!t||"function"!=typeof t.state)throw new Error("createAutoDispatch: the auto-mint automation is required");return{autoStatus:()=>({ok:!0,drain:e.state(),mint:t.state()}),autoSetDrain:t=>{const n=t||{},r={};null!=n.enabled&&(r.enabled=Boolean(n.enabled)),null!=n.intervalMs&&(r.intervalMs=Number(n.intervalMs));try{return{ok:!0,drain:e.set(r)}}catch(e){return{ok:!1,error:errorText(e)}}},autoSetMint:e=>{const n=e||{},r={};null!=n.enabled&&(r.enabled=Boolean(n.enabled)),null!=n.publish&&(r.publish=Boolean(n.publish));try{return{ok:!0,mint:t.set(r)}}catch(e){return{ok:!1,error:errorText(e)}}},autoSealNow:async e=>{const n=e||{};null!=n.publish&&t.set({publish:Boolean(n.publish)});try{const e=await t.flush();return t.reset(),{ok:!0,...e}}catch(e){return t.reset(),{ok:!1,error:errorText(e)}}}}}function registerQueueIpc(e,{engine:t,env:n,queue:r,autonomous:o,entitlement:s,aegis:i}={}){let a=null;const c=createQueueDispatch({engine:t,env:n,queue:r,autonomous:o,entitlement:s||entitlementModule.createEntitlement({probe:i&&"function"==typeof i.verifyApiKey?async()=>{const e=await i.verifyApiKey(),t=e&&"object"==typeof e?{...e}:{};if("function"==typeof i.tokenBankBalance)try{const e=await i.tokenBankBalance();e&&"object"==typeof e&&(null!=e.balance_micros?t.balance_micros=e.balance_micros:null!=e.balance_eur&&(t.balance_eur=e.balance_eur))}catch{}return t}:void 0}),log:e=>{a&&"function"==typeof a.send&&("function"==typeof a.isDestroyed&&a.isDestroyed()||a.send(QUEUE_PROGRESS_CHANNEL,e))}});for(const[t,n]of Object.entries(c))e.handle(`${QUEUE_PREFIX}${t}`,((e,t)=>(a=e&&e.sender||null,n(t))));return c}function registerAutoIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`${AUTO_PREFIX}${n}`,((e,t)=>r(t)));return t}const UPDATE_STATUS_CHANNEL=`${IPC_PREFIX}updateStatus`,ACCOUNT_STATUS_CHANNEL=`${IPC_PREFIX}accountStatusChanged`,UPDATE_CHECK_INTERVAL_MS=144e5,UPDATE_RETRY_BACKOFF_MS=[6e4,3e5,9e5,36e5];function describeRegistryFailure(e,t,n){switch(e){case"not-found":return`${n} is not published on the npm registry (404)`;case"forbidden":return`the npm registry refused the request (${t||"auth"})`;case"malformed":return"the npm registry sent a response this app could not read";case"too-large":return"the npm registry response was too large to read";case"timeout":return"the npm registry did not respond in time";case"network":return"the npm registry could not be reached";default:return"the update check did not complete"}}function createNpmUpdateManager({onStatus:e,packaged:t=!1,now:n=(()=>Date.now()),fetchImpl:r,setTimeoutImpl:o=setTimeout,clearTimeoutImpl:s=clearTimeout,runUpgrade:i,relaunch:a}={}){const c="aegis-desktop";let u="unknown";try{u=require("./package.json").version}catch{}let l={status:"idle",version:null,error:null,channel:"npm",reason:null,transient:!1,attempts:0,retryInMs:0,command:null,plan:null,method:null,canDownload:!1};const d=t=>(l={...l,...t},e&&e(l),l);let p=null;try{p=require("../client/update.js")}catch{try{p=require("./vendor/update.js")}catch{p=null}}let f=0,m=0,h=null,g=null,y=null,E=null;function k(){h&&s(h),h=null}async function _({announce:e=!1}={}){if(!p)return d({status:"disabled",error:"update checker unavailable"});if(g)return g;g=(async()=>{const s=l.status,i=l.version;let a;d({status:"checking",error:null,reason:null,transient:!1});try{a=await async function(){if(r)return r({pkg:c});if(p&&"function"==typeof p.checkPublished){const e=await p.checkPublished({current:u,pkg:c,now:n(),intervalMs:0});return e?{ok:e.ok,latest:e.latest,reason:e.reason,status:e.status}:{ok:!1,latest:null,reason:"unknown",status:null}}return{ok:!1,latest:null,reason:"unavailable",status:null}}()}catch(e){a={ok:!1,latest:null,reason:"unknown",status:null,error:errorText(e)}}if(a.ok){if(f=0,m=0,k(),!p.isNewer(a.latest,u))return d({status:"up-to-date",version:a.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0});const e=function(){if(E)return E;const e=p&&p.detectInstallMethod;if("function"!=typeof e)return E="npm",E;try{E=e({env:process.env,argv:process.argv,pkg:c,entry:__dirname,fileExists:e=>fs.existsSync(path.resolve(__dirname,"..",e))})}catch{E="npm"}return E}(),n="function"==typeof p.updatePlan?p.updatePlan({current:u,latest:a.latest,behind:!0,channel:"npm",pkg:c,method:e}):null;return d({status:"available",version:a.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0,plan:n,method:e,command:t?`${a.latest} is published — reinstall AEGIS Desktop from the installer to pick it up`:n&&n.instruction||`npm i -g ${c}@latest`,commandIsSentence:t||Boolean(n&&!n.apply),canDownload:Boolean(n&&n.apply)&&!t})}f+=1;const g=a.error||describeRegistryFailure(a.reason,a.status,c);return y=a.reason,v=a.status,("function"==typeof p.isTransientReason?p.isTransientReason(y,v):"unknown"===y)?(function(){k();const e=UPDATE_RETRY_BACKOFF_MS[Math.min(Math.max(f-1,0),UPDATE_RETRY_BACKOFF_MS.length-1)];m=n()+e,h=o((()=>{h=null,_().catch((()=>{}))}),e),h&&h.unref&&h.unref(),d({retryInMs:e})}(),d(e?{status:"error",error:g,reason:a.reason,transient:!0,attempts:f}:{status:"available"===s?"available":"unavailable",version:i,error:g,reason:a.reason,transient:!0,attempts:f})):(k(),m=0,d({status:"error",error:g,reason:a.reason,transient:!1,attempts:f,retryInMs:0}));var y,v})();try{return await g}finally{g=null}}return{status:()=>l,check:_,download:async()=>{const e=!t&&l.plan&&l.plan.apply;if(!e)return d({status:"available"===l.status?"available":l.status,command:l.plan&&l.plan.instruction||l.command,canDownload:!1});d({status:"downloading",error:null,progress:0});const n=await function(e){const t=i||((e,t)=>new Promise((n=>{execFile(e,t,{timeout:18e4,windowsHide:!0},((e,t,r)=>{if(e)return n({ok:!1,output:String(r||t||e.message||e)});n({ok:!0,output:String(t||"")})}))}))),n=!i&&p&&"function"==typeof p.installSpawn?p.installSpawn(e,{env:process.env}):null,r=n?n.command:e.command,o=n?n.args:e.args;return Promise.resolve(t(r,o)).then((e=>({ok:Boolean(e&&e.ok),output:String(e&&e.output||"")})),(e=>({ok:!1,output:errorText(e)})))}(e);return n.ok?d({status:"downloaded",version:l.version,error:null,progress:100,command:`npm i -g ${c}@latest`,canDownload:!1}):d({status:"error",transient:!1,error:n.output.trim().split("\n").slice(-3).join(" ").trim()||"the installer failed",command:`${e.command} ${e.args.join(" ")}`})},quitAndInstall:()=>{"downloaded"===l.status&&(a||(()=>{try{const{app:e}=require("electron");e.relaunch(),e.exit(0)}catch{}}))()},start:()=>{_().catch((()=>{})),y=setInterval((()=>_().catch((()=>{}))),UPDATE_CHECK_INTERVAL_MS),y.unref&&y.unref()},stop:()=>{k(),y&&clearInterval(y),y=null},retryState:()=>({attempts:f,retryAt:m,inFlight:!!g,hasTimer:!!h})}}function createUpdateManager({isPackaged:e,onStatus:t}){let n={status:"idle",version:null,error:null,canDownload:!1};return createNpmUpdateManager({onStatus:function(e){n={...n,...e},t&&t(n)},packaged:Boolean(e)})}function createUpdateDispatch(e){return{checkForUpdates:()=>e.check({announce:!0}),downloadUpdate:()=>e.download(),quitAndInstallUpdate:()=>(e.quitAndInstall(),{ok:!0}),updateStatus:()=>Promise.resolve(e.status())}}function registerUpdateIpc(e,t){const n=createUpdateDispatch(t);for(const[t,r]of Object.entries(n))e.handle(`${IPC_PREFIX}${t}`,((e,t)=>r(t)));return n}let resolveTargetWindow=null;function sendToAppWindow(e,t){const n="function"==typeof resolveTargetWindow?resolveTargetWindow():null,r=n&&!n.isDestroyed()?n:e.getFocusedWindow()||e.getAllWindows()[0];r&&!r.isDestroyed()&&r.webContents.send(t)}function sendDeepLinkToWindow(e,t){if(!e||e.isDestroyed()||!t)return;const n=()=>{e.isDestroyed()||e.webContents.send(DEEP_LINK_CHANNEL,t)};e.webContents.isLoadingMainFrame()?e.webContents.once("did-finish-load",n):n()}function buildAppMenu({app:e,Menu:t,BrowserWindow:n,updateManager:r,loggedIn:o}){const s="darwin"===process.platform;e.setAboutPanelOptions({applicationName:e.getName(),applicationVersion:e.getVersion(),version:e.getVersion()});const i={label:"Check for Updates…",click:()=>r.check({announce:!0})},a={label:"New Chat",accelerator:"CmdOrCtrl+N",click:()=>sendToAppWindow(n,MENU_NEW_CHAT_CHANNEL)},c={label:"Search…",accelerator:"CmdOrCtrl+K",click:()=>sendToAppWindow(n,MENU_SEARCH_CHANNEL)},u={label:"Save as…",accelerator:"CmdOrCtrl+S",click:()=>sendToAppWindow(n,MENU_EXPORT_MARKDOWN_CHANNEL)},l={label:"Export Session…",click:()=>sendToAppWindow(n,MENU_EXPORT_JSON_CHANNEL)},d={label:"Authorship Panel…",click:()=>sendToAppWindow(n,MENU_FINGERPRINT_CHANNEL)},p={label:"Google Drive Backup…",enabled:Boolean(o),click:()=>sendToAppWindow(n,MENU_GOOGLE_DRIVE_CHANNEL)},f=[...s?[{label:e.getName(),submenu:[{role:"about"},i,{type:"separator"},{role:"services"},{type:"separator"},{role:"hide"},{role:"hideOthers"},{role:"unhide"},{type:"separator"},{role:"quit"}]}]:[],{label:"File",submenu:[a,{type:"separator"},u,l,{type:"separator"},...s?[]:[i,{type:"separator"}],s?{role:"close"}:{role:"quit"}]},{label:"Edit",submenu:[{role:"undo"},{role:"redo"},{type:"separator"},{role:"cut"},{role:"copy"},{role:"paste"},{role:"selectAll"}]},{label:"View",submenu:[c,{type:"separator"},d,p,{type:"separator"},{role:"reload",accelerator:"CmdOrCtrl+R"},{role:"forceReload"},{type:"separator"},{role:"toggleDevTools",accelerator:"CmdOrCtrl+Shift+I"}]},...s?[]:[{label:"Help",submenu:[{role:"about"}]}]];return t.buildFromTemplate(f)}function bootstrap(){let e=!1;try{e=require("./lib/local/integrity.js").armed()}catch{e=!0,process.env.AEGIS_REDUCED_MODE="1",process.stderr.write("aegis-desktop: reduced mode (d1) — this build is not the one that was published.\n")}if(e){try{const{app:e}=electron;e&&"function"==typeof e.quit&&e.quit()}catch{}return}const{app:t,BrowserWindow:n,ipcMain:r,safeStorage:o,shell:s,Menu:i,Notification:a,screen:c,dialog:u,globalShortcut:l}=electron;if(t.disableHardwareAcceleration(),t.commandLine.appendSwitch("disable-gpu"),t.commandLine.appendSwitch("disable-software-rasterizer"),t.commandLine.appendSwitch("disable-gpu-compositing"),t.commandLine.appendSwitch("disable-features","UsePortalAccentColor"),process.argv.some((e=>/^--(log-level|enable-logging)/.test(e)))||process.env.ELECTRON_ENABLE_LOGGING||t.commandLine.appendSwitch("log-level","3"),!t.requestSingleInstanceLock())return void t.quit();if(t.setName("AEGIS Desktop"),envFile&&"function"==typeof envFile.loadEnvFile)try{const e=envFile.loadEnvFile();e.loose&&console.warn(`aegis: ${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it.`)}catch(e){console.warn(`aegis: could not read ${envFile.envFileFor()}: ${e&&e.message}`)}t.setAsDefaultProtocolClient(deepLink.PROTOCOL);let d=deepLink.parseDeepLinkArgv(process.argv);t.on("open-url",((e,t)=>{e.preventDefault();const n=deepLink.parseDeepLinkUrl(t);if(!n)return;const r="function"==typeof resolveTargetWindow?resolveTargetWindow():null;r&&!r.isDestroyed()?sendDeepLinkToWindow(r,n):d=n}));const p=createClient(credentials.clientOptions()),f=resolveUserDataDir(t),{engine:m,sessionsDir:h,settingsDir:g,settings:y}=createEngine(p,{app:t,safeStorage:o,dir:f}),E=createAccountKey({aegis:p,credentials:credentials,persistKey:e=>y.setAegisKey(e),provision:(e,t)=>autoProvision.autoProvisionApiKey(e,t,{app:"desktop"}),describeFailure:autoProvision.provisionFailureText,onChange:e=>q(e)});let k=null;const _=createGoogleConnect({aegis:p,credentials:credentials,persistKey:e=>y.setAegisKey(e),openUrl:e=>!!isSafeExternalUrl(e)&&(s.openExternal(e),!0),googleSignIn:googleSignIn,driveConnect:driveConnectLib,driveUpload:driveUploadLib,conversationExport:conversationExportLib?{...conversationExportLib,toTranscript:e=>sessionStore.toMarkdown(e)}:null,getSession:e=>sessionStore.getSession(h,e),getAuthor:()=>{try{k||(k=createFingerprintService({dir:f,getVaultBackend:()=>y.vaultBackendConfig().backend}));const e=k.status();return e&&e.ok?e:null}catch{return null}},onAccountChange:()=>q(E.status())}),v=Boolean(p.apiKey),A=autoProvision.autoProvisionApiKey(p,credentials,{app:"desktop"}).then((e=>{if(E.recordStartup(e),!e.key&&!p.apiKey){const t=e.error&&(e.error.status||e.error.message||String(e.error))||"no key returned";console.warn(`auto-provision: no account key from register-device (${t})`)}return e}));try{const{wrapProviderKeyMirror:e}=require("./lib/provider-key-mirror.js"),t=e=>console.warn(`aegis: ${e}`);e(y,envFile,{onWarn:t}),m&&m.settings&&m.settings!==y&&e(m.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not wire the shared env-file key mirror: ${e&&e.message}`)}let b=null;const S=(e,t)=>{if(function(e){const t=e&&e.sender,r=t&&n.fromWebContents(t);if(!r||r.isDestroyed())return;if(r.isFocused()&&r.isVisible())return;if(!a||!a.isSupported())return;const o=new a({title:"AEGIS Desktop",body:"Reply ready"});o.on("click",(()=>{r.isDestroyed()||(r.isMinimized()&&r.restore(),r.isVisible()||r.show(),r.focus())})),o.show()}(e),b&&"function"==typeof b.note){const e=t&&(t.model||t.modelId)||void 0;b.note({sessionId:t&&t.sessionId||null,model:e})}};registerIpc(r,p,f,(e=>{const t=y.setAegisKey(e);return e?credentials.saveApiKey(e):credentials.clearApiKey(),t}),(e=>s.openExternal(e)),S,(()=>providerRouteConfigured(m)),(()=>y.vaultBackendConfig().backend));const w=registerModelIpc(r,m,h,p,S,void 0,g);registerConfirmModeIpc(r,withAutoRoundsSwitch(createConfirmModeDispatch(y),w.modelDispatch)),registerConfirmModeIpc(r,createVaultBackendDispatch(y)),registerTelemetryIpc(r,createTelemetryDispatch(createTelemetry({dir:g,enabled:telemetryEnabled(process.env,y),appVersion:(()=>{try{return"function"==typeof t.getVersion?t.getVersion():""}catch{return""}})()}))),registerCovenantIpc(r,createCovenantDispatch(covenantModule));const C=registerQueueIpc(r,{engine:createQueueEngine(p,y),aegis:p}),I=createAutoDrain({proceed:()=>C.proceed(),settings:y,queue:queueModule,env:process.env,log:e=>{e&&"skip"!==e.type&&console.log("[auto-drain]",e.type,e.reason||e.error||"")}});let R=null;b=createAutoMint({mint:e=>(R||(R=createFingerprintService({dir:f,getVaultBackend:()=>y.vaultBackendConfig().backend})),R.mint(e||{})),settings:y}),registerAutoIpc(r,createAutoDispatch({autoDrain:I,autoMint:b})),I.start(),b.start();let M=null,P=null;function T(){return P&&!P.isDestroyed()||(P=new n({width:560,height:320,show:!1,frame:!1,alwaysOnTop:!0,skipTaskbar:!0,resizable:!1,movable:!0,fullscreenable:!1,minimizable:!1,maximizable:!1,backgroundColor:"#0d1117",icon:iconForPlatform(resolveIconsDir(t.isPackaged,process.resourcesPath,__dirname),process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0}}),P.setMenuBarVisibility(!1),P.loadFile(path.join(__dirname,"renderer","quick.html")),P.webContents.on("before-input-event",((e,t)=>{"keyDown"!==t.type||"Escape"!==t.key||P.isDestroyed()||P.hide()})),P.on("blur",(()=>{!P.isDestroyed()&&P.isVisible()&&P.hide()})),P.on("closed",(()=>{P=null}))),P}function D(){const e=T();e.isVisible()?e.hide():function(){const e=T(),t=c.getCursorScreenPoint(),n=c.getAllDisplays(),r=e.getBounds(),o=quickLauncherLib.computeQuickLauncherBounds({cursor:t,displays:n,size:{width:r.width,height:r.height}});e.setBounds(o),e.show(),e.focus()}()}resolveTargetWindow=()=>{if(M&&!M.isDestroyed())return M;const e=n.getFocusedWindow();return e&&!e.isDestroyed()&&e!==P?e:n.getAllWindows().find((e=>e!==P))||null};const N=createQuickLauncherDispatch(y,{isPackaged:t.isPackaged,applyConfig:function(e){if(l.unregisterAll(),!quickLauncherLib.shouldEnableGlobalShortcut({isPackaged:t.isPackaged,enabled:e.enabled}))return{active:!1,reason:null};try{if(!l.register(e.shortcut,D)){const t=`"${e.shortcut}" could not be registered — it may already be in use by another application.`;return console.warn(`[quick-launcher] ${t}`),{active:!1,reason:t}}return{active:!0,reason:null}}catch(t){const n=errorText(t);return console.warn(`[quick-launcher] failed to register shortcut "${e.shortcut}": ${n}`),{active:!1,reason:n}}},pushToMain:function(e,t){const r=t&&t.sender&&n.fromWebContents(t.sender);r&&!r.isDestroyed()&&r.hide();const o=M&&!M.isDestroyed()?M:n.getAllWindows().find((e=>e!==r))||null;return o?(o.webContents.send(QUICK_LAUNCHER_PUSH_CHANNEL,e||{}),o.isMinimized()&&o.restore(),o.isVisible()||o.show(),o.focus(),{ok:!0}):{ok:!1,reason:"no main window is open"}}});registerQuickLauncherIpc(r,N);let L=null;t.on("will-quit",(()=>{L&&"function"==typeof L.stop&&L.stop(),l.unregisterAll(),x&&"function"==typeof x.stop&&x.stop()}));let U=!1;t.on("before-quit",(e=>{!U&&m&&"function"==typeof m.unloadLocalModels&&(e.preventDefault(),Promise.resolve().then((()=>m.unloadLocalModels())).catch((()=>{})).finally((()=>{U=!0,t.quit()})))}));const F=new Set;function q(e){for(const t of F)t.isDestroyed()||t.webContents.send(ACCOUNT_STATUS_CHANNEL,e);O()}function O(){i.setApplicationMenu(buildAppMenu({app:t,Menu:i,BrowserWindow:n,updateManager:x,loggedIn:Boolean(p.apiKey)}))}const x=createUpdateManager({isPackaged:t.isPackaged,onStatus:function(e){for(const t of F)t.isDestroyed()||t.webContents.send(UPDATE_STATUS_CHANNEL,e)}});registerUpdateIpc(r,x),r.handle(`${IPC_PREFIX}accountStatus`,(()=>E.status())),r.handle(`${IPC_PREFIX}registerAccount`,(()=>E.registerAccount())),r.handle(`${IPC_PREFIX}driveSignIn`,(()=>_.signInWithGoogle())),r.handle(`${IPC_PREFIX}driveConnect`,(()=>_.connectDrive())),r.handle(`${IPC_PREFIX}driveStatus`,(()=>_.status())),r.handle(`${IPC_PREFIX}driveSyncMemory`,(()=>_.syncMemoryNow())),r.handle(`${IPC_PREFIX}driveBackupConversation`,((e,t)=>_.backupConversation({sessionId:t&&t.sessionId}))),registerExportIpc(r,sessionStore,h,(e=>u.showSaveDialog(n.getFocusedWindow(),e)),((e,t)=>fs.promises.writeFile(e,t,"utf8"))),O();const B=pathToFileURL(path.join(__dirname,"renderer","index.html")).href;function $(){const e=windowState.load(f),r=windowState.clampToDisplay(e,c.getAllDisplays(),{width:1080,height:720}),o=resolveIconsDir(t.isPackaged,process.resourcesPath,__dirname),i=new n({...r,minWidth:720,minHeight:480,show:!0,backgroundColor:"#0d1117",title:"AEGIS Desktop",icon:iconForPlatform(o,process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0,spellcheck:!0}});e&&e.isMaximized&&i.maximize(),i.webContents.setWindowOpenHandler((({url:e})=>(isSafeExternalUrl(e)&&s.openExternal(e),{action:"deny"}))),i.webContents.on("will-navigate",((e,t)=>{t!==B&&(e.preventDefault(),isSafeExternalUrl(t)&&s.openExternal(t))}));let a=null;function u(){if(i.isDestroyed())return;const e=i.isMaximized(),t=e?i.getNormalBounds():i.getBounds();windowState.save(f,{...t,isMaximized:e})}function l(){a&&clearTimeout(a),a=setTimeout(u,500)}return i.on("resize",l),i.on("move",l),i.on("close",(()=>{a&&clearTimeout(a),u()})),i.loadFile(path.join(__dirname,"renderer","index.html")),F.add(i),M=i,i.on("closed",(()=>{F.delete(i),M===i&&(M=null)})),i}t.whenReady().then((async()=>{if(!credentials.normalizeApiKey(process.env[credentials.KEY_ENV])){const e=await A,t=startupKeyOverride({mintedKey:v?"":e.key,hostKey:credentials.normalizeApiKey(y.aegisRawKey())});if(t)credentials.saveApiKey(t),p.setApiKey(t);else{const e=credentials.preferNewest(y.aegisRawKey(),y.aegisKeySavedAt());e.key&&(p.setApiKey(e.key),"shared"===e.source&&y.setAegisKey(e.key))}}try{L&&"function"==typeof L.stop&&L.stop(),L=sharedPresence.createPresence({apiKey:p.apiKey,app:"desktop",version:t.getVersion(),platform:process.platform,install:sharedFingerprint.machineFingerprint(),queueDepth:()=>{try{return queueModule.readQueue(queueModule.queuePath()).filter((e=>e&&"pending"===e.status)).length}catch{return 0}},autonomous:!1,log:(e,t)=>{"debug"!==e&&console.warn(t)}}),L.start()}catch(e){console.warn("presence: beacon not started",e&&e.message)}try{const{backfillProviderKeys:e}=require("./lib/provider-key-mirror.js"),t=e=>console.warn(`aegis: ${e}`),n=e(y,envFile,{onWarn:t});n.mirrored.length&&console.warn(`aegis: shared ${n.mirrored.join(", ")} key(s) with the other hosts (${envFile.envFileFor()})`),m&&m.settings&&m.settings!==y&&e(m.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not backfill the shared env-file key mirror: ${e&&e.message}`)}N.setConfig(y.quickLauncherConfig());const e=$();x.start(),d&&sendDeepLinkToWindow(e,d)})),t.on("window-all-closed",(()=>{"darwin"!==process.platform&&t.quit()})),t.on("activate",(()=>{const e=n.getAllWindows();if(0===e.length)return void $();const t=resolveTargetWindow()||e[0];t.isMinimized()&&t.restore(),t.isVisible()||t.show(),t.focus()})),t.on("second-instance",((e,t)=>{const n=resolveTargetWindow(),r=deepLink.parseDeepLinkArgv(t);if(n)n.isMinimized()&&n.restore(),n.isVisible()||n.show(),n.focus(),r&&sendDeepLinkToWindow(n,r);else{const e=$();r&&sendDeepLinkToWindow(e,r)}}))}electron&&electron.app&&bootstrap(),module.exports={createIpcDispatch:createIpcDispatch,registerIpc:registerIpc,providerRouteConfigured:providerRouteConfigured,IPC_PREFIX:IPC_PREFIX,MODEL_PREFIX:MODEL_PREFIX,SYNC_PREFIX:SYNC_PREFIX,watchTopupCredit:watchTopupCredit,bankAmount:bankAmount,TOPUP_POLL_MS:TOPUP_POLL_MS,TOPUP_POLL_TRIES:TOPUP_POLL_TRIES,CHAT_DELTA_CHANNEL:CHAT_DELTA_CHANNEL,MENU_NEW_CHAT_CHANNEL:MENU_NEW_CHAT_CHANNEL,MENU_SEARCH_CHANNEL:MENU_SEARCH_CHANNEL,MENU_EXPORT_MARKDOWN_CHANNEL:MENU_EXPORT_MARKDOWN_CHANNEL,MENU_EXPORT_JSON_CHANNEL:MENU_EXPORT_JSON_CHANNEL,MENU_FINGERPRINT_CHANNEL:MENU_FINGERPRINT_CHANNEL,MENU_GOOGLE_DRIVE_CHANNEL:MENU_GOOGLE_DRIVE_CHANNEL,DEEP_LINK_CHANNEL:DEEP_LINK_CHANNEL,UPDATE_STATUS_CHANNEL:UPDATE_STATUS_CHANNEL,UPDATE_CHECK_INTERVAL_MS:UPDATE_CHECK_INTERVAL_MS,taggedChunk:taggedChunk,maskKey:maskKey,createModelDispatch:createModelDispatch,DESKTOP_CLASSES:DESKTOP_CLASSES,readTextFileForPreview:readTextFileForPreview,PREVIEW_READ_MAX_BYTES:PREVIEW_READ_MAX_BYTES,ingestAttachment:ingestAttachment,nativeImageResizer:nativeImageResizer,createSyncDispatch:createSyncDispatch,registerModelIpc:registerModelIpc,createHeartbeatRetry:createHeartbeatRetry,describeSyncError:describeSyncError,HEARTBEAT_RETRY_BASE_MS:HEARTBEAT_RETRY_BASE_MS,HEARTBEAT_RETRY_MAX_MS:HEARTBEAT_RETRY_MAX_MS,createEngine:createEngine,resolveUserDataDir:resolveUserDataDir,importForeignMemory:importForeignMemory,isSafeExternalUrl:isSafeExternalUrl,createUpdateManager:createUpdateManager,createNpmUpdateManager:createNpmUpdateManager,createUpdateDispatch:createUpdateDispatch,describeRegistryFailure:describeRegistryFailure,UPDATE_RETRY_BACKOFF_MS:UPDATE_RETRY_BACKOFF_MS,registerUpdateIpc:registerUpdateIpc,buildAppMenu:buildAppMenu,createExportDispatch:createExportDispatch,registerExportIpc:registerExportIpc,safeExportBasename:safeExportBasename,sendDeepLinkToWindow:sendDeepLinkToWindow,QUICK_PREFIX:QUICK_PREFIX,QUICK_LAUNCHER_PUSH_CHANNEL:QUICK_LAUNCHER_PUSH_CHANNEL,createQuickLauncherDispatch:createQuickLauncherDispatch,registerQuickLauncherIpc:registerQuickLauncherIpc,createConfirmModeDispatch:createConfirmModeDispatch,createVaultBackendDispatch:createVaultBackendDispatch,withAutoRoundsSwitch:withAutoRoundsSwitch,createTelemetryDispatch:createTelemetryDispatch,registerTelemetryIpc:registerTelemetryIpc,createCovenantDispatch:createCovenantDispatch,registerCovenantIpc:registerCovenantIpc,registerConfirmModeIpc:registerConfirmModeIpc,QUEUE_PREFIX:QUEUE_PREFIX,QUEUE_PROGRESS_CHANNEL:QUEUE_PROGRESS_CHANNEL,QUEUE_MAX_TASK_CHARS:QUEUE_MAX_TASK_CHARS,QUEUE_MAX_ROUNDS:QUEUE_MAX_ROUNDS,createQueueEngine:createQueueEngine,queueEngineWithDeniedApprovals:queueEngineWithDeniedApprovals,createQueueDispatch:createQueueDispatch,registerQueueIpc:registerQueueIpc,AUTO_PREFIX:AUTO_PREFIX,createAutoDispatch:createAutoDispatch,registerAutoIpc:registerAutoIpc};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegis-desktop",
3
3
  "productName": "AEGIS Desktop",
4
- "version": "1.0.19",
4
+ "version": "1.0.21",
5
5
  "description": "Thin Electron host for AEGIS — a local chat UI over the shared client/aegis.js transport. Ships transport + UI only; engine logic stays server-side.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",