aegisone 1.0.69 → 1.0.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/vendor/cli/bin/aegiscode.js +11 -0
  4. package/vendor/cli/package.json +1 -1
  5. package/vendor/cli/src/app.js +1 -1
  6. package/vendor/cli/src/limits.js +1 -1
  7. package/vendor/cli/src/provenance.lock.json +2 -2
  8. package/vendor/cli/src/screen.js +1 -1
  9. package/vendor/cli/vendor/client/session-store.js +1 -1
  10. package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
  11. package/vendor/cli/vendor/desktop/main.js +12 -1
  12. package/vendor/desktop/lib/local/integrity.js +1 -1
  13. package/vendor/desktop/lib/local/pty-host.js +1 -1
  14. package/vendor/desktop/main.js +12 -1
  15. package/vendor/desktop/package.json +1 -1
  16. package/vendor/desktop/renderer/app.js +3 -3
  17. package/vendor/desktop/renderer/index.html +18 -0
  18. package/vendor/desktop/renderer/pty-panel.js +1 -1
  19. package/vendor/desktop/renderer/pty-renderer.js +1 -1
  20. package/vendor/desktop/renderer/pty-window.js +1 -1
  21. package/vendor/desktop/renderer/style.css +53 -1
  22. package/vendor/desktop/vendor/faces/cli/bin/aegiscode.js +2 -2
  23. package/vendor/desktop/vendor/faces/cli/package.json +1 -1
  24. package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
  25. package/vendor/desktop/vendor/faces/cli/src/limits.js +1 -1
  26. package/vendor/desktop/vendor/faces/cli/src/provenance.lock.json +2 -2
  27. package/vendor/desktop/vendor/faces/cli/src/screen.js +1 -1
  28. package/vendor/desktop/vendor/faces/cli/vendor/client/session-store.js +1 -1
  29. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
  30. package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +1 -1
  31. package/vendor/desktop/vendor/session-store.js +1 -1
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),STORE_FILE="sessions.json",STORE_VERSION=2,MAX_MESSAGES_PER_SESSION=2e3;function storeDir(e){return e||aegisHome()}function storeFile(e){return path.join(storeDir(e),STORE_FILE)}function nextSeq(e){const t=("number"==typeof e.__seq?e.__seq:0)+1;return e.__seq=t,t}function toEpochMs(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.trim()){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function load(e){try{const t=JSON.parse(fs.readFileSync(storeFile(e),"utf8"));if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}return{}}function atomicWrite(e,t){fs.mkdirSync(path.dirname(e),{recursive:!0});const n=`${e}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),fs.renameSync(n,e);try{fs.chmodSync(e,384)}catch{}}const LOCK_STALE_MS=3e4,LOCK_WAIT_MS=(()=>{const e=Number(process.env.AEGIS_STORE_LOCK_WAIT_MS);return Number.isFinite(e)&&e>0?e:15e3})(),SLEEP_CELL=new Int32Array(new SharedArrayBuffer(4));function lockFile(e){return`${storeFile(e)}.lock`}function acquireLock(e){const t=lockFile(e);try{fs.mkdirSync(path.dirname(t),{recursive:!0})}catch{return!1}const n=Date.now()+LOCK_WAIT_MS,s=Math.max(200,Math.ceil(LOCK_WAIT_MS/5)+200);for(let e=0;e<s;e++)try{const e=fs.openSync(t,"wx");return fs.writeSync(e,String(process.pid)),fs.closeSync(e),!0}catch{let e=null;try{e=Date.now()-fs.statSync(t).mtimeMs}catch{continue}if(lockAbandoned(t,e)){try{fs.unlinkSync(t)}catch{}continue}if(Date.now()>=n)return!1;Atomics.wait(SLEEP_CELL,0,0,5)}return!1}function pidAlive(e){try{return process.kill(e,0),!0}catch(e){return e&&"EPERM"===e.code}}function lockAbandoned(e,t){let n=0;try{n=Number(String(fs.readFileSync(e,"utf8")).trim())}catch{n=0}return Number.isInteger(n)&&n>0?!pidAlive(n):t>3e4}function releaseLock(e){try{fs.unlinkSync(lockFile(e))}catch{}}function mutate(e,t){if(!acquireLock(e))throw new Error(`session store is locked by another writer: ${lockFile(e)} (waited ${LOCK_WAIT_MS}ms — refusing to write unlocked and overwrite it)`);try{const n=load(e),s=t(n);return save(e,n),s}finally{releaseLock(e)}}function save(e,t){atomicWrite(storeFile(e),t)}function trimMessages(e){return Array.isArray(e)?e.length<=2e3?e:e.slice(e.length-2e3):[]}function upsertSession(e,t){const n=t&&t.id;if(!n)throw new Error("session.id is required");return mutate(e,e=>{const s=e[n]||{messages:[]};e[n]={...s,...t,id:n,version:2};const r=t&&!0===t.seed,i="string"==typeof s.title&&s.title;return!0===s.named&&i?(e[n].title=s.title,e[n].named=!0):r&&i&&s.title&&(e[n].title=s.title),delete e[n].seed,!1!==t.pending&&(e[n].pending=!0),e[n].updatedAt||(e[n].updatedAt=Date.now()),e[n].seq=nextSeq(e),e[n]})}function appendMessage(e,t,n){if(!t)throw new Error("sessionId is required");return mutate(e,e=>{const s=e[t]||{id:t,messages:[]},r=Array.isArray(s.messages)?s.messages:[];return s.messages=trimMessages(r.concat(n)),s.updatedAt=Date.now(),s.pending=!0,s.seq=nextSeq(e),e[t]=s,s})}function recordExchange(e,t){const n=t||{};if(!n.sessionId)return null;const s=n.sessionId;return mutate(e,e=>{const t=e[s]||{id:s,messages:[]},r=Array.isArray(t.messages)?t.messages:[],i=n.ts||(new Date).toISOString(),o={role:"user",content:null==n.prompt?"":String(n.prompt),ts:i},a={role:"assistant",content:null==n.reply?"":String(n.reply),ts:i};return n.tokens&&(a.tokens=n.tokens),"number"==typeof n.costUsd&&(a.costUsd=n.costUsd),n.status&&(a.status=n.status),n.model&&(a.model=n.model),n.provider&&(a.provider=n.provider),n.origin&&(o.origin=n.origin,a.origin=n.origin),t.messages=trimMessages(r.concat([o,a])),t.title=t.title||String(n.prompt||"").slice(0,60),n.cwd&&(t.cwd=n.cwd),t.origin=n.origin||t.origin||"unknown",t.updatedAt=Date.now(),t.pending=!0===n.pending,t.seq=nextSeq(e),e[s]=t,t})}function setTitle(e,t,n,s){const r=String(null==n?"":n).trim().slice(0,200);if(!t||!r)return null;const i=s&&!0===s.named;return mutate(e,e=>{const n=e[t];return n?(n.title=r,i&&(n.named=!0),n.updatedAt=Date.now(),n.seq=nextSeq(e),n):null})}function listSessions(e){const t=load(e);return Object.values(t).filter(e=>e&&e.id).sort((e,t)=>(t.updatedAt||0)-(e.updatedAt||0)||(t.seq||0)-(e.seq||0))}function getSession(e,t){return load(e)[t]||null}function deleteSession(e,t){return mutate(e,e=>(delete e[t],{ok:!0}))}function markSynced(e,t,n){return mutate(e,e=>{const s=e[t];return s?(s.pending=!1,s.lastSyncedAt=Date.now(),n&&n.remoteId&&(s.remoteId=n.remoteId),s.seq=nextSeq(e),s):null})}function markPending(e,t){return mutate(e,e=>{const n=e[t];return n?(n.pending=!0,n.seq=nextSeq(e),n):null})}function listPending(e){return listSessions(e).filter(e=>!1!==e.pending)}function mergeRemoteSessions(e,t){const n=Array.isArray(t)?t:[];return n.length?mutate(e,e=>{let t=0;for(const s of n){const n=s&&(s.session_id||s.id);if(!n)continue;const r=e[n],i=toEpochMs(s.updated_at??s.updatedAt);r&&(r.pending||(r.updatedAt||0)>=i)||(e[n]={id:n,title:s.title||r&&r.title||"",messages:Array.isArray(s.messages)?s.messages:[],updatedAt:i||Date.now(),pending:!1,lastSyncedAt:Date.now(),remoteId:s.session_id||s.id,origin:s.source||r&&r.origin||"cloud",version:2},e[n].seq=nextSeq(e),t+=1)}return t}):0}function listSummaries(e,t=8){return listSessions(e).slice(0,t).map(e=>{const t=Array.isArray(e.messages)?e.messages:[],n=t.find(e=>e&&"user"===e.role);return{id:e.id,cwd:(e.cwd||"").split(/[\\/]/).filter(Boolean).pop()||"~",summary:String(e.title||n&&n.content||"").slice(0,60),time:new Date(e.updatedAt||Date.now()).toISOString(),own:!0,origin:e.origin||"unknown",messages:t.length,pending:!0===e.pending,dir:String(e.cwd||"")}})}function readTranscript(e,t){const n=getSession(e,t);return n?(Array.isArray(n.messages)?n.messages:[]).filter(e=>e&&("user"===e.role||"assistant"===e.role)).map(e=>({role:e.role,text:null==e.content?"":String(e.content)})):[]}function adopt(e,t){const n=storeFile(t);if(!(()=>{try{return fs.existsSync(n)}catch{return!1}})())return{adopted:!1,sessions:0,from:n,reason:"no legacy store"};const s=(()=>{try{const e=JSON.parse(fs.readFileSync(n,"utf8"));return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}})(),r=Object.values(s).filter(e=>e&&e.id);if(!r.length)return{adopted:!1,sessions:0,from:n,reason:"legacy store empty"};let i=0;return mutate(e,e=>{for(const t of r)e[t.id]||(e[t.id]={...t,adoptedFrom:n,version:2},e[t.id].seq=nextSeq(e),i+=1);return e.__seq=Math.max(e.__seq||0,s.__seq||0),e.version=2,null}),i?{adopted:!0,sessions:i,from:n}:{adopted:!1,sessions:0,from:n,reason:"already adopted"}}function toMarkdown(e){const t=e&&(e.title||e.id)||"session",n=e&&Array.isArray(e.messages)?e.messages:[],s=[`# ${t}`,""];for(const e of n){const t=e&&e.role||"unknown",n=t.charAt(0).toUpperCase()+t.slice(1),r=e&&(e.content||e.text)||"";s.push(`## ${n}`,"",r,"")}return s.join("\n")}function toJson(e){return JSON.stringify(e,null,2)}module.exports={STORE_FILE:STORE_FILE,STORE_VERSION:2,MAX_MESSAGES_PER_SESSION:2e3,storeDir:storeDir,storeFile:storeFile,lockFile:lockFile,LOCK_STALE_MS:3e4,LOCK_WAIT_MS:LOCK_WAIT_MS,toEpochMs:toEpochMs,load:load,save:save,upsertSession:upsertSession,appendMessage:appendMessage,recordExchange:recordExchange,setTitle:setTitle,listSessions:listSessions,getSession:getSession,deleteSession:deleteSession,markSynced:markSynced,markPending:markPending,listPending:listPending,mergeRemoteSessions:mergeRemoteSessions,listSummaries:listSummaries,readTranscript:readTranscript,adopt:adopt,toMarkdown:toMarkdown,toJson:toJson};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),STORE_FILE="sessions.json",STORE_VERSION=2,MAX_MESSAGES_PER_SESSION=2e3;function storeDir(e){return e||aegisHome()}function storeFile(e){return path.join(storeDir(e),STORE_FILE)}function nextSeq(e){const t=("number"==typeof e.__seq?e.__seq:0)+1;return e.__seq=t,t}function toEpochMs(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.trim()){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function load(e){try{const t=JSON.parse(fs.readFileSync(storeFile(e),"utf8"));if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}return{}}function atomicWrite(e,t){fs.mkdirSync(path.dirname(e),{recursive:!0});const n=`${e}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),fs.renameSync(n,e);try{fs.chmodSync(e,384)}catch{}}const LOCK_STALE_MS=3e4,LOCK_WAIT_MS=(()=>{const e=Number(process.env.AEGIS_STORE_LOCK_WAIT_MS);return Number.isFinite(e)&&e>0?e:15e3})(),SLEEP_CELL=new Int32Array(new SharedArrayBuffer(4));function lockFile(e){return`${storeFile(e)}.lock`}function acquireLock(e){const t=lockFile(e);try{fs.mkdirSync(path.dirname(t),{recursive:!0})}catch{return!1}const n=Date.now()+LOCK_WAIT_MS,s=Math.max(200,Math.ceil(LOCK_WAIT_MS/5)+200);for(let e=0;e<s;e++)try{const e=fs.openSync(t,"wx");return fs.writeSync(e,String(process.pid)),fs.closeSync(e),!0}catch{let e=null;try{e=Date.now()-fs.statSync(t).mtimeMs}catch{continue}if(lockAbandoned(t,e)){try{fs.unlinkSync(t)}catch{}continue}if(Date.now()>=n)return!1;Atomics.wait(SLEEP_CELL,0,0,5)}return!1}function pidAlive(e){try{return process.kill(e,0),!0}catch(e){return e&&"EPERM"===e.code}}function lockAbandoned(e,t){let n=0;try{n=Number(String(fs.readFileSync(e,"utf8")).trim())}catch{n=0}return Number.isInteger(n)&&n>0?!pidAlive(n):t>3e4}function releaseLock(e){try{fs.unlinkSync(lockFile(e))}catch{}}function mutate(e,t){if(!acquireLock(e))throw new Error(`session store is locked by another writer: ${lockFile(e)} (waited ${LOCK_WAIT_MS}ms — refusing to write unlocked and overwrite it)`);try{const n=load(e),s=t(n);return save(e,n),s}finally{releaseLock(e)}}function save(e,t){atomicWrite(storeFile(e),t)}function trimMessages(e){return Array.isArray(e)?e.length<=2e3?e:e.slice(e.length-2e3):[]}function upsertSession(e,t){const n=t&&t.id;if(!n)throw new Error("session.id is required");return mutate(e,e=>{const s=e[n]||{messages:[]};e[n]={...s,...t,id:n,version:2};const r=t&&!0===t.seed,i="string"==typeof s.title&&s.title;return!0===s.named&&i?(e[n].title=s.title,e[n].named=!0):r&&i&&s.title&&(e[n].title=s.title),delete e[n].seed,!1!==t.pending&&(e[n].pending=!0),e[n].updatedAt||(e[n].updatedAt=Date.now()),e[n].seq=nextSeq(e),e[n]})}function appendMessage(e,t,n){if(!t)throw new Error("sessionId is required");return mutate(e,e=>{const s=e[t]||{id:t,messages:[]},r=Array.isArray(s.messages)?s.messages:[];return s.messages=trimMessages(r.concat(n)),s.updatedAt=Date.now(),s.pending=!0,s.seq=nextSeq(e),e[t]=s,s})}function recordExchange(e,t){const n=t||{};if(!n.sessionId)return null;const s=n.sessionId,r=null==n.reply?"":String(n.reply),i=""!==r.trim()&&"(no response)"!==r.trim();return mutate(e,e=>{if(!i&&!e[s])return null;const t=e[s]||{id:s,messages:[]},r=Array.isArray(t.messages)?t.messages:[],o=n.ts||(new Date).toISOString(),a={role:"user",content:null==n.prompt?"":String(n.prompt),ts:o},c={role:"assistant",content:null==n.reply?"":String(n.reply),ts:o};return n.tokens&&(c.tokens=n.tokens),"number"==typeof n.costUsd&&(c.costUsd=n.costUsd),n.status&&(c.status=n.status),n.model&&(c.model=n.model),n.provider&&(c.provider=n.provider),n.origin&&(a.origin=n.origin,c.origin=n.origin),t.messages=trimMessages(r.concat([a,c])),t.title=t.title||String(n.prompt||"").slice(0,60),n.cwd&&(t.cwd=n.cwd),t.origin=n.origin||t.origin||"unknown",t.updatedAt=Date.now(),t.pending=!0===n.pending,t.seq=nextSeq(e),e[s]=t,t})}function setTitle(e,t,n,s){const r=String(null==n?"":n).trim().slice(0,200);if(!t||!r)return null;const i=s&&!0===s.named;return mutate(e,e=>{const n=e[t];return n?(n.title=r,i&&(n.named=!0),n.updatedAt=Date.now(),n.seq=nextSeq(e),n):null})}function listSessions(e){const t=load(e);return Object.values(t).filter(e=>e&&e.id&&"string"==typeof e.id).sort((e,t)=>(t.updatedAt||0)-(e.updatedAt||0)||(t.seq||0)-(e.seq||0))}function getSession(e,t){return t&&t!==DELETED_KEY&&load(e)[t]||null}function deleteSession(e,t){return t?mutate(e,e=>{const n=e[t];if(!n)return{ok:!1};const s=deletedMap(e);return s[t]={at:Date.now(),remoteId:n.remoteId||null},e[DELETED_KEY]=s,nextSeq(e),delete e[t],{ok:!0}}):{ok:!1}}function markSynced(e,t,n){return mutate(e,e=>{const s=e[t];return s?(s.pending=!1,s.lastSyncedAt=Date.now(),n&&n.remoteId&&(s.remoteId=n.remoteId),s.seq=nextSeq(e),s):null})}function markPending(e,t){return mutate(e,e=>{const n=e[t];return n?(n.pending=!0,n.seq=nextSeq(e),n):null})}function listPending(e){return listSessions(e).filter(e=>!1!==e.pending)}const DELETED_KEY="__deleted";function deletedMap(e){const t=e&&e[DELETED_KEY];return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}function isDeleted(e,t){return!!t&&Boolean(deletedMap(load(e))[t])}function mergeRemoteSessions(e,t){const n=Array.isArray(t)?t:[];return n.length?mutate(e,e=>{let t=0;const s=deletedMap(e);for(const r of n){const n=r&&(r.session_id||r.id);if(!n)continue;if(s[n]&&!e[n])continue;const i=e[n],o=toEpochMs(r.updated_at??r.updatedAt);i&&(i.pending||(i.updatedAt||0)>=o)||(e[n]={id:n,title:r.title||i&&i.title||"",messages:Array.isArray(r.messages)?r.messages:[],updatedAt:o||Date.now(),pending:!1,lastSyncedAt:Date.now(),remoteId:r.session_id||r.id,origin:r.source||i&&i.origin||"cloud",version:2},e[n].seq=nextSeq(e),t+=1)}return t}):0}function listSummaries(e,t=8){return listSessions(e).slice(0,t).map(e=>{const t=Array.isArray(e.messages)?e.messages:[],n=t.find(e=>e&&"user"===e.role);return{id:e.id,cwd:(e.cwd||"").split(/[\\/]/).filter(Boolean).pop()||"~",summary:String(e.title||n&&n.content||"").slice(0,60),time:new Date(e.updatedAt||Date.now()).toISOString(),own:!0,origin:e.origin||"unknown",messages:t.length,pending:!0===e.pending,dir:String(e.cwd||"")}})}function readTranscript(e,t){const n=getSession(e,t);return n?(Array.isArray(n.messages)?n.messages:[]).filter(e=>e&&("user"===e.role||"assistant"===e.role)).map(e=>({role:e.role,text:null==e.content?"":String(e.content)})):[]}function adopt(e,t){const n=storeFile(t);if(!(()=>{try{return fs.existsSync(n)}catch{return!1}})())return{adopted:!1,sessions:0,from:n,reason:"no legacy store"};const s=(()=>{try{const e=JSON.parse(fs.readFileSync(n,"utf8"));return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}})(),r=Object.values(s).filter(e=>e&&e.id);if(!r.length)return{adopted:!1,sessions:0,from:n,reason:"legacy store empty"};let i=0;return mutate(e,e=>{const t=deletedMap(e);for(const s of r)e[s.id]||t[s.id]||(e[s.id]={...s,adoptedFrom:n,version:2},e[s.id].seq=nextSeq(e),i+=1);return e.__seq=Math.max(e.__seq||0,s.__seq||0),e.version=2,null}),i?{adopted:!0,sessions:i,from:n}:{adopted:!1,sessions:0,from:n,reason:"already adopted"}}function toMarkdown(e){const t=e&&(e.title||e.id)||"session",n=e&&Array.isArray(e.messages)?e.messages:[],s=[`# ${t}`,""];for(const e of n){const t=e&&e.role||"unknown",n=t.charAt(0).toUpperCase()+t.slice(1),r=e&&(e.content||e.text)||"";s.push(`## ${n}`,"",r,"")}return s.join("\n")}function toJson(e){return JSON.stringify(e,null,2)}module.exports={STORE_FILE:STORE_FILE,STORE_VERSION:2,MAX_MESSAGES_PER_SESSION:2e3,storeDir:storeDir,storeFile:storeFile,lockFile:lockFile,LOCK_STALE_MS:3e4,LOCK_WAIT_MS:LOCK_WAIT_MS,toEpochMs:toEpochMs,load:load,save:save,upsertSession:upsertSession,appendMessage:appendMessage,recordExchange:recordExchange,setTitle:setTitle,listSessions:listSessions,getSession:getSession,deleteSession:deleteSession,DELETED_KEY:DELETED_KEY,isDeleted:isDeleted,markSynced:markSynced,markPending:markPending,listPending:listPending,mergeRemoteSessions:mergeRemoteSessions,listSummaries:listSummaries,readTranscript:readTranscript,adopt:adopt,toMarkdown:toMarkdown,toJson:toJson};
@@ -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{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 r=0;r<e.length;r++){const n=parseInt(e[r],16),i=parseInt(PAD_HEX[r%PAD_HEX.length],16);if(Number.isNaN(n)||Number.isNaN(i))return null;t+=(n^i).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")},{id:"d5",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3guanM=","base64").toString("utf8")},{id:"d6",rel:Buffer.from("bGliL2xvY2FsL3Blcm0tcnVsZXMuanM=","base64").toString("utf8")},{id:"d7",rel:Buffer.from("bGliL2xvY2FsL3Blcm0td3JpdGUuanM=","base64").toString("utf8")},{id:"d8",rel:Buffer.from("bGliL2xvY2FsL3Blcm0tc3RvcmUuanM=","base64").toString("utf8")},{id:"d9",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtc2VhdGJlbHQuanM=","base64").toString("utf8")},{id:"d10",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtYXBwY29udGFpbmVyLmpz","base64").toString("utf8")},{id:"d11",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtYndyYXAuanM=","base64").toString("utf8")}]),SEALED="7f70b35884b9c2d7aee50510bf9603138af4d55e746a875774a0c68f1b1e566a";function check(){const e=[];for(const t of UNITS){const r=path.join(PACKAGE_ROOT,t.rel);if(!existsSync(r))return{tripped:!0,code:"d1",units:UNITS.length};try{e.push(sha256(readFileSync(r)))}catch{return{tripped:!0,code:"d1",units:UNITS.length}}}const t=sha256(`${SALT}\n${e.join("\n")}`),r=SEALED.trim();return 64!==r.length?{tripped:!0,code:"d2",units:UNITS.length}:unmask(r)!==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};
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 r=0;r<e.length;r++){const n=parseInt(e[r],16),i=parseInt(PAD_HEX[r%PAD_HEX.length],16);if(Number.isNaN(n)||Number.isNaN(i))return null;t+=(n^i).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")},{id:"d5",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3guanM=","base64").toString("utf8")},{id:"d6",rel:Buffer.from("bGliL2xvY2FsL3Blcm0tcnVsZXMuanM=","base64").toString("utf8")},{id:"d7",rel:Buffer.from("bGliL2xvY2FsL3Blcm0td3JpdGUuanM=","base64").toString("utf8")},{id:"d8",rel:Buffer.from("bGliL2xvY2FsL3Blcm0tc3RvcmUuanM=","base64").toString("utf8")},{id:"d9",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtc2VhdGJlbHQuanM=","base64").toString("utf8")},{id:"d10",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtYXBwY29udGFpbmVyLmpz","base64").toString("utf8")},{id:"d11",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtYndyYXAuanM=","base64").toString("utf8")}]),SEALED="362fcd58ba5304cb63685a67c99f3001b2a4b677a482fdfc501bf83a663eba62";function check(){const e=[];for(const t of UNITS){const r=path.join(PACKAGE_ROOT,t.rel);if(!existsSync(r))return{tripped:!0,code:"d1",units:UNITS.length};try{e.push(sha256(readFileSync(r)))}catch{return{tripped:!0,code:"d1",units:UNITS.length}}}const t=sha256(`${SALT}\n${e.join("\n")}`),r=SEALED.trim();return 64!==r.length?{tripped:!0,code:"d2",units:UNITS.length}:unmask(r)!==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};
@@ -5,4 +5,4 @@
5
5
  // gdrive:AEGIS-AGPL/records and writes the `.anchor.json` link beside the
6
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:n=>{const r=s&&"function"==typeof s.capabilities?s.capabilities():null,o=n&&n.limit,a=Number.isFinite(o)?o:r&&Number.isFinite(r.recallEntries)?r.recallEntries:void 0;return normalizeMemoryReadWithFallback(e.memorySearch(n&&n.query,a),memoryIndex(t),n&&n.query,a)},memorySave:n=>saveMemoryWithQueue(e,t,n&&n.entry,s,memoryIndex(t)),memoryList:n=>normalizeMemoryReadWithFallback(e.memoryList(n&&n.limit),memoryIndex(t),"",n&&n.limit),verifyToken:t=>e.verifyToken(t&&t.token),memoryActivate:t=>e.memoryActivate(t&&t.token),memoryPull:n=>indexPulledMemory(e.memoryPull(n&&n.since),memoryIndex(t)),memorySaveBatch:t=>e.memorySaveBatch(t&&t.entries),memoryImport:n=>importForeignMemory(e,t,n,s,memoryIndex(t)),sessionsImportScan:()=>importForeignSessions(t,{confirm:!1}),sessionsImport:e=>importForeignSessions(t,e),importConversation:t=>e.importConversation(t||{}),personaRead:()=>{if(!s)return{ok:!1,reason:"no avatar store in this build"};try{const e=s.readPersona();return{ok:!0,persona:e.persona,warnings:e.warnings||[],capabilities:"function"==typeof s.capabilities?s.capabilities():null}}catch(e){return{ok:!1,reason:errorText(e)}}},personaPatch:e=>{if(!s)return{ok:!1,reason:"no avatar store in this build"};const t=e&&e.patch;if(!t||"object"!=typeof t)return{ok:!1,reason:"no patch"};try{const e=s.writePersona(t);return{ok:!0,saved:!0,persona:e.persona,warnings:e.warnings||[]}}catch(e){return{ok:!1,reason:errorText(e)}}},openExternal:e=>{const t=e&&e.url;return isSafeExternalUrl(t)?Promise.resolve(u(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,c){const l=createIpcDispatch(t,n,r,o,a,c,i);for(const[t,n]of Object.entries(l))"chatCompletion"!==t?e.handle(`aegis:${t}`,(e,t)=>n(t)):e.handle(`aegis:${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("aegis:chatDelta",taggedChunk(e,r.sessionId))}}),e,s)});return l}function createAccentDispatch(e){if(!e)throw new Error("createAccentDispatch requires a settings store");return{getAccent:()=>({name:e.getAccent()}),setAccent:t=>{const n=t&&t.name;return"string"!=typeof n?{name:e.getAccent()}:{name:e.setAccent(n)}}}}function createFontScaleDispatch(e){if(!e)throw new Error("createFontScaleDispatch requires a settings store");return{getFontScale:()=>({scale:e.getFontScale()}),setFontScale:t=>{const n=t&&t.scale;return"number"!=typeof n?{scale:e.getFontScale()}:{scale:e.setFontScale(n)}}}}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 createDevModeDispatch(e){if(!e)throw new Error("createDevModeDispatch requires a settings store");return{getDevMode:()=>({enabled:e.getDevMode()}),setDevMode:t=>{const n=t&&t.enabled;return"boolean"!=typeof n?{enabled:e.getDevMode()}:{enabled:e.setDevMode(n)}},getAccountUsername:()=>({username:e.getAccountUsername()}),setAccountUsername:t=>{const n=t&&"string"==typeof t.username?t.username:null;return{username:e.setAccountUsername(n)}}}}function createModelAutoSyncDispatch(e,t){if(!e)throw new Error("createModelAutoSyncDispatch requires a settings store");return{getModelAutoSync:()=>{const e=t&&"function"==typeof t.modelAutoSyncStatus?t.modelAutoSyncStatus():{enabled:!1};return{enabled:Boolean(e&&e.enabled),status:e}},setModelAutoSync:n=>{const r=n&&n.enabled;if("boolean"!=typeof r){const e=t&&"function"==typeof t.modelAutoSyncStatus?t.modelAutoSyncStatus():{enabled:!1};return{enabled:Boolean(e&&e.enabled),status:e}}return e.setSharedPref("modelAutoSync",r),{enabled:r,status:t&&"function"==typeof t.modelAutoSyncStatus?t.modelAutoSyncStatus():{enabled:r}}}}}function createPermissionModeDispatch(e){if(!e)throw new Error("createPermissionModeDispatch requires a settings store");return{getPermissionMode:()=>({mode:e.getPermissionMode()}),setPermissionMode:t=>{const n=t&&t.mode;return"plan"!==n&&null!=n?{mode:e.getPermissionMode()}:{mode:e.setPermissionMode("plan"===n?"plan":null)}}}}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 createPermRulesDispatch(e){if(!e)throw new Error("createPermRulesDispatch requires a rule store");const t=(e,t)=>{try{return e()}catch(e){return{...t,ok:!1,reason:e&&e.message||String(e)}}};return{permRulesList:()=>t(()=>e.listRules(),{}),permRulesAdd:n=>{const r=n&&n.list,o=n&&n.rule;return"string"!=typeof r||"string"!=typeof o?t(()=>e.listRules(),{reason:"a rule needs a list and a pattern"}):t(()=>e.addRule(r,o),{})},permRulesRemove:n=>{const r=n&&n.list,o=n&&n.rule;return"string"!=typeof r||"string"!=typeof o?t(()=>e.listRules(),{reason:"a rule needs a list and a pattern"}):t(()=>e.removeRule(r,o),{})}}}function createCliFaceDispatch(e){const t=e||{},n=t.face||require("./lib/local/cli-face.js"),r=t.platform||require("./vendor/platform.js"),o=t.spawn||require("node:child_process").spawn,s=e=>{try{return Boolean(r.resolveExecutable(e,{platform:t.hostPlatform||process.platform,env:t.env||process.env}))}catch{return!1}},a=t.entryExists||(e=>{try{return require("node:fs").existsSync(e)}catch{return!1}});return{openCliFace:e=>{const r=t.appInfo||{};let i;try{i=n.plan({packaged:r.packaged,resourcesPath:r.resourcesPath,appDir:r.appDir,execPath:r.execPath,nodePath:r.nodePath,platform:t.hostPlatform||process.platform,exists:s,entryExists:a,args:e&&Array.isArray(e.args)?e.args:[]})}catch(e){return{ok:!1,reason:`could not plan the terminal face: ${e&&e.message||e}`,command:n.CLI_BIN}}if(!i||!i.ok)return{ok:!1,reason:i&&i.reason||"could not open a terminal",command:i&&i.command||n.CLI_BIN};try{const e=o(i.exec,i.args,{detached:!0,stdio:"ignore",env:Object.assign({},t.env||process.env,i.env||{})});e&&"function"==typeof e.unref&&e.unref()}catch(e){return{ok:!1,reason:`could not start ${i.exec}: ${e&&e.message||e}`,command:i.command}}return{ok:!0,emulator:i.exec,command:i.command}}}}function createPtyIpc(e,t){const n=t||{},r=n.ptyHostModule||require("./lib/local/pty-host.js"),o=void 0!==n.nodePty?n.nodePty:r.probeNodePty(),s=r.createPtyHost({nativePty:Boolean(o),appInfo:n.appInfo,spawnPty:o?(e,t)=>o.spawn(e[0],e.slice(1),{name:"xterm-color",cols:t.cols||80,rows:t.rows||24,cwd:t.cwd||process.cwd(),env:Object.assign({},process.env,t.env||{})}):void 0});return e.handle("aegis:ptyHello",(e,t)=>s.hello(t&&t.id||0)),e.handle("aegis:ptyExec",(e,t)=>{const n=t||{},r=e&&e.sender;return s.exec(n.id,n.params,e=>{r&&!r.isDestroyed()&&r.send("aegis:ptyEvent",e)})}),e.handle("aegis:ptyWrite",(e,t)=>{const n=t||{};return s.write(n.id,n.data)}),e.handle("aegis:ptyResize",(e,t)=>{const n=t||{};return s.resize(n.id,n.cols,n.rows)}),e.handle("aegis:ptyCancel",(e,t)=>s.cancel((t||{}).id)),s}function createSandboxPolicyDispatch(e,t,n){if(!e)throw new Error("createSandboxPolicyDispatch requires a settings store");const r=t||{},o=(Array.isArray(r.MODES)?r.MODES:["off","read-only","workspace-write","managed"]).filter(e=>"managed"!==e),s=n&&n.appDir,a=()=>{const t=e.getSandboxPolicy(),n=t&&o.includes(t.mode)?t.mode:"workspace-write",a=t&&"open"===t.network?"open":"restricted";let i=null,c=null,l=null;try{const e=(e=>{const t=r.detectCached||r.detect;if("function"!=typeof t||"function"!=typeof r.describe)return null;try{const n=t({appDir:s}),o=r.describe(n,e);return{mechanism:n&&(n.mechanism||(n.path?"bwrap":null))||null,enforced:Boolean(n&&n.available)&&"off"!==e.mode,sentence:"string"==typeof o?o:null}}catch{return{mechanism:null,enforced:null,sentence:null}}})("function"==typeof r.normalize?r.normalize(t,void 0):{mode:n,network:a});e&&({sentence:i,enforced:c,mechanism:l}=e)}catch{}return{ok:!0,mode:n,network:a,modes:o,stored:!!t,sentence:i,enforced:c,mechanism:l}};return{getSandboxPolicy:()=>a(),setSandboxPolicy:t=>{const n=t&&t.mode,i=t&&t.network;if("string"!=typeof n||!o.includes(n))return a();if(void 0!==i&&"open"!==i&&"restricted"!==i)return a();const c=e.getSandboxPolicy(),l=c&&c.fileSystem&&Array.isArray(c.fileSystem.entries)?{entries:c.fileSystem.entries}:{entries:[]},u=void 0===i?c&&"open"===c.network?"open":"restricted":i;try{e.setSandboxPolicy({mode:n,fileSystem:l,network:u})}catch{return a()}if("function"==typeof r.invalidateProbe)try{r.invalidateProbe(s)}catch{}return a()}}}function registerConfirmModeIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`aegis:${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(`aegis:${n}`,(e,t)=>r(t));return t}function registerTelemetryIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`aegis:${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),l="json"===a?"json":"md",u="json"===a?[{name:"JSON",extensions:["json"]}]:[{name:"Markdown",extensions:["md"]}],d=await n({defaultPath:`${safeExportBasename(i)}.${l}`,filters:u});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(`aegis:${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:${n}`,(e,t)=>r(t)):e.handle(`quick:${n}`,(e,t)=>r(t,e));return t}function resolveUserDataDir(e){if(e&&"function"==typeof e.getPath)try{return e.getPath("userData")}catch{}try{const e=require("../one/src/iface/paths.js").plan({platform:process.platform,env:process.env});if(e&&e.ok)return e.state}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}),i=avatarStore.createAvatarStore({dir:s,log:()=>{}});try{i.verifyAtBoot()}catch(e){console.error("aegis: avatar carve-out violation",e&&e.message)}a.migrateLegacyAegisKey();const c=()=>{try{return i.capabilities()}catch{return null}};return{engine:createLocalEngine({aegis:e,settings:a,recallProvider:({system:e})=>require("./lib/avatar/turn.js").composeSystemPrompt(e,{capabilities:c(),persona:i.readPersona().persona,deep:!1}).system,sandbox:{policy:()=>"function"==typeof a.getSandboxPolicy?a.getSandboxPolicy():null,strict:!1,appDir:__dirname},permissionRules:{rulesVerdict:require("./lib/local/perm-rules.js").rulesVerdict,subjectFor:require("./lib/local/perm-rules.js").subjectFor,alwaysAllow:require("./lib/local/perm-write.js").alwaysAllow}}),sessionsDir:o||sessionStore.resolveStoreDir(s),settingsDir:s,settings:a,avatar: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 a=fs.statSync(o);if(!a.isFile())return null;if(a.size<=524288)return{text:fs.readFileSync(o,"utf8"),truncated:!1};const i=fs.openSync(o,"r");try{const e=Buffer.alloc(524288),t=fs.readSync(i,e,0,524288,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(),"userModels.syncPlan":t=>e.modelSyncPlan(t&&t.only),"userModels.syncApply":t=>e.modelSyncApply(t&&t.plan,t&&t.only),"userModels.syncStatus":()=>e.modelAutoSyncStatus(),"userModels.syncNow":t=>e.modelAutoSyncRun(t&&t.only),"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),listUndoable:t=>"function"==typeof e.listUndoable?e.listUndoable(t&&t.sessionId):[],undoMutation:t=>"function"==typeof e.undoMutation?e.undoMutation(t&&t.sessionId,t&&t.id):{ok:!1,error:"undo is not available on this engine"}};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,o){let s=null;function a(){return Boolean(n&&n.apiKey)}async function i(){const r=e.listPending(t);if(!a())return{ok:!1,queued:r.length,reason:"no AEGIS key configured"};const o=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 a=0;a<e.length;a+=1)try{await n.memorySave(e[a]),o+=1;const r=memoryIndex(t);if(r)try{r.upsert(e[a])}catch{}}catch(t){const n=upgradeInfo(t);if(n){s=n,r.push(...e.slice(a));break}r.push(e[a])}return memoryQueue.save(t,r),{flushed:o,remaining:r.length,upgrade:s}}();if(!r.length)return{ok:!0,queued:0,pushed:0,memoryFlushed:o.flushed,upgrade:o.upgrade};let i=0,c=null,l=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,l=describeSyncError(e),"quota"===l.kind||"auth"===l.kind)break}const u=e.listPending(t).length;i&&(s=Date.now());const d=(c?upgradeInfo(c):null)||o.upgrade;return 0===i&&c?{ok:!1,queued:u,reason:syncErrorReason(l),failed:l?[l]:[],kind:l?l.kind:"error",status:l?l.status:0,hint:l?l.hint:null,memoryFlushed:o.flushed,upgrade:d}:{ok:!0,queued:u,pushed:i,failed:l?[l]:[],memoryFlushed:o.flushed,upgrade:d}}const c=persistGate.createAutoPush({push:i,dir:r||t}),l=["id","title","updatedAt","pending","named","seq","cwd","dir","origin","remoteId","lastSyncedAt"];return{auto:()=>c.auto(),memoryPersistState:()=>c.gate(),listSessions:()=>{return{sessions:(n=e.listSessions(t),(Array.isArray(n)?n:[]).filter(e=>e&&e.id).map(e=>{const t={};for(const n of l)void 0!==e[n]&&(t[n]=e[n]);const n=Array.isArray(e.messages)?e.messages:[];t.messages=n.length;const r=n.find(e=>e&&"user"===e.role&&e.content);return t.firstPrompt=r?String(r.content):"",t}))};var n},searchSessions:n=>{const r=n&&"string"==typeof n.query?n.query:"",o=Number.isInteger(n&&n.limit)?n.limit:50,s=Math.max(1,o),a=e.listSessions(t)||[],i=sessionSearch.rankSessions(r,a).slice(0,s);let c=[],l=0,u="ok";try{const e=memoryIndex(t);if(e){const t=e.search(r,{limit:s});t&&t.ok?(c=(t.results||[]).map(e=>({id:e.id,content:e.body||"",scope:e.scope||"",tags:Array.isArray(e.tags)?e.tags:[],updated:e.updated||null})),l=e.count()):u="error"}else u=memoryStore.isAvailable()&&t?"error":"unavailable"}catch{c=[],l=0,u="error"}return{query:r,total:a.length,memoryStatus:u,memoryTotal:l,memory:c,sessions:i.map(e=>({id:e&&e.id,title:e&&e.title||e&&e.id||"untitled",updatedAt:e&&e.updatedAt||null,messages:e&&Array.isArray(e.messages)?e.messages.map(e=>({role:e&&e.role,content:"string"==typeof(e&&e.content)?e.content.slice(0,400):""})):[],reason:sessionSearch.matchReason(r,e)}))}},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),rename:n=>e.renameSession(t,n&&n.sessionId,n&&n.title),nameSession:async n=>{const r=n&&n.sessionId,s=n&&n.prompt;if(!r||!String(null==s?"":s).trim())return null;let a;for(const e of["../client/naming.js","./vendor/naming.js","./vendor/client/naming.js"])try{a=require(e);break}catch{}if(!a)return null;const i=async(e,t={})=>{if(!o||"function"!=typeof o.chat)return null;try{const s=await o.chat({class:n&&n.class||"aegis",model:n&&n.model,prompt:e,system:t.system,maxTokens:64,sessionId:`${r}:naming`,tools:!1}),a=s&&s.choices&&s.choices[0]||{};return a.message&&a.message.content||null}catch{return null}};try{return await a.nameSession(e.namingStore,t,r,s,{callModel:i})}catch{return null}},push:i,pull:async function(){if(!a())return{ok:!1,merged:0,reason:"no AEGIS key configured"};try{const r=await n.conversationSyncPull(),o=e.mergeRemoteSessions(t,r&&r.sessions||[]);return s=Date.now(),{ok:!0,merged:o,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:a(),lastSyncAt:s})}}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):5e3,o=Number(t.maxMs)>0?Number(t.maxMs):3e4;let s=0,a=0,i=null,c=!1;function l(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?l(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 l(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=>l(errorText(e))}}function registerModelIpc(e,t,n,r,o,s,a,i){const c=createModelDispatch(t),l=createSyncDispatch(sessionStore,n,r,a,c),u=createHeartbeatRetry(()=>l.push(),s);function d(){const e=u.run();e&&"function"==typeof e.catch&&e.catch(e=>u.recordFailure(e))}for(const[t,n]of Object.entries(c))"chat"!==t?"listModels"!==t?e.handle(`model:${t}`,(e,t)=>n(t)):e.handle(`model:${t}`,(e,t)=>(d(),n(t))):e.handle(`model:${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 c=e&&e.sender,l=r.class||"model",u=n({...r,onStream:e=>{c&&"function"==typeof c.send&&!c.isDestroyed()&&c.send("aegis:chatDelta",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 backgroundLaneLogs(i)&&console.warn(`[model] background ${l} 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))return backgroundLaneLogs(i)&&console.warn(`[model] ${l} turn stopped before it finished: ${errorText(e)} [ABORT_ERR]`),abortedTurnPayload(e);const t=e&&"number"==typeof e.status?e.status:0,n=e&&e.code||"";return backgroundLaneLogs(i)&&console.error(`[model] ${l} turn failed: ${errorText(e)}${t?` (status ${t})`:""}${n?` [${n}]`:""}`,e&&e.stack?e.stack:""),{providerFailed:!0,status:t,code:n||void 0,message:errorText(e),choices:[{message:{content:""}}]}})});e.on("model:readTextFile",(e,t)=>{e.returnValue=readTextFileForPreview(t)}),e.handle("aegis:attachments:ingest",async(e,t)=>ingestAttachment(t));for(const[t,n]of Object.entries(l))"status"!==t?e.handle(`sync:${t}`,(e,t)=>n(t)):e.handle(`sync:${t}`,(e,t)=>{d();const r=n(t);return r&&"object"==typeof r?{...r,retry:u.state()}:r});return{modelDispatch:c,syncDispatch:l,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 l=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 u(){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,8),fanout:Boolean(e&&!0===e.fanout)});if(!s.ok)return{...s,...u()};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>8e3)return{error:`task text is too long (${n.length} > 8000 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,8),maxRounds:clampInt(t.maxRounds,1,200),singlePass:!(!0===t.fanout||!0===t.autonomous),commit:Boolean(t.commit),source:"desktop"}}}(e);return i?{ok:!1,reason:i,...u()}:{ok:!0,item:n.addTask(t,a),...u()}},list:()=>u(),entitlement:async e=>(await o.refresh({force:Boolean(e&&!0===e.force)}),{ok:!0,...u()}),clear:e=>({...n.clearQueue(t,{all:Boolean(e&&e.all)}),ok:!0,...u()}),retry:e=>{const r=e&&e.id,o=n.retryTask(t,r);return o?{ok:!0,item:o,...u()}:{ok:!1,reason:`no task #${r}`,...u()}},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`,...u()}:(n.saveQueue(t,o.filter(e=>Number(e&&e.id)!==Number(s.id))),{ok:!0,removed:s.id,...u()}):{ok:!1,reason:`no task #${r}`,...u()}},drain:()=>async function(){if(c)return{ok:!1,reason:"a drain is already running in this window",...u()};let e;c=!0,i=!1;try{const t=await l.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,...u()}}(),proceed:()=>async function(){if(c)return{ok:!1,reason:"a drain is already running in this window",...u()};c=!0,i=!1;const e=[];let t;try{for(;;){const n=await l.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,...u()}}(),stop:e=>{i=!0;const t=e&&null!=e.id?e.id:a,n=null==t?null:l.cancel(t);return{ok:!0,wasDraining:c,cancelled:n,...u()}}}}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 liveAppWindows(){try{const e=require("electron"),t=e&&e.BrowserWindow;return t&&"function"==typeof t.getAllWindows?t.getAllWindows().filter(e=>e&&"function"==typeof e.send&&!("function"==typeof e.isDestroyed&&e.isDestroyed())):[]}catch{return[]}}function registerQueueIpc(e,{engine:t,env:n,queue:r,autonomous:o,entitlement:s,aegis:a,windows:i=liveAppWindows}={}){let c=null;const l=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}),u=()=>{let e=[];try{e=i()||[]}catch{e=[]}for(const t of e)try{t.send("queue:changed",{at:Date.now()})}catch{}},d=createQueueDispatch({engine:t,env:n,queue:r,autonomous:o,entitlement:l,log:e=>{e&&"finish"===e.type&&u(),c&&"function"==typeof c.send&&("function"==typeof c.isDestroyed&&c.isDestroyed()||c.send("queue:progress",e))}});for(const[t,n]of Object.entries(d))e.handle(`queue:${t}`,(e,r)=>{c=e&&e.sender||null;const o=n(r);return QUEUE_MUTATING_METHODS.has(t)?o&&"function"==typeof o.then?o.then(e=>(u(),e),e=>{throw u(),e}):(u(),o):o});return d}function registerAutoIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`auto:${n}`,(e,t)=>r(t));return t}const UPDATE_STATUS_CHANNEL="aegis:updateStatus",ACCOUNT_STATUS_CHANNEL="aegis: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 resolveUpdateOwner({dir:e=__dirname,readJson:t=e=>JSON.parse(fs.readFileSync(e,"utf8"))}={}){const n=`${path.sep}vendor${path.sep}desktop`,r=String(e).lastIndexOf(n);if(r>0){const n=String(e).slice(0,r);try{const e=t(path.join(n,"package.json")).version;if(e)return{pkg:"aegisone",current:String(e),productDir:n}}catch{}}try{const n=t(path.join(e,"package.json")).version;if(n)return{pkg:"aegis-desktop",current:String(n),productDir:null}}catch{}return{pkg:"aegis-desktop",current:"unknown",productDir:null}}function installFailureText(e,t="the installer failed"){const n=String(null==e?"":e).split("\n").map(e=>e.replace(/^\s*npm\s+(error|ERR!)\s*/i,"").trim()).filter(Boolean).filter(e=>!/^A complete log of this run can be found/i.test(e)).filter(e=>!/^In most cases you or one of your dependencies/i.test(e)).filter(e=>!/^a package version that doesn't exist\.?$/i.test(e));if(!n.length)return t;const r=n.findIndex(e=>/^code\s+[A-Z]/i.test(e)),o=r>=0&&n[r+1]?n[r+1]:n[0],s=r>=0?n[r].replace(/^code\s+/i,""):"";return s?`${o} (${s})`:o}function createNpmUpdateManager({onStatus:e,packaged:t=!1,now:n=()=>Date.now(),fetchImpl:r,setTimeoutImpl:o=setTimeout,clearTimeoutImpl:s=clearTimeout,runUpgrade:a,relaunch:i,owner:c}={}){const l=c||resolveUpdateOwner(),u=l.pkg;let d=l.current,p={status:"idle",version:null,error:null,phase:null,channel:"npm",reason:null,transient:!1,attempts:0,retryInMs:0,command:null,plan:null,method:null,canDownload:!1,decomposed:!1};const m=t=>(p={...p,...t},e&&e(p),p);let f=null;try{f=require("../client/update.js")}catch{try{f=require("./vendor/update.js")}catch{f=null}}let g=0,h=0,y=null,k=null,b=null,v=null;function S(){y&&s(y),y=null}const w=(e,t)=>"function"==typeof f.isTransientReason?f.isTransientReason(e,t):"unknown"===e;let E=null;async function A({announce:e=!1}={}){if(!f)return m({status:"disabled",error:"update checker unavailable"});if(k)return k;k=(async()=>{const s=p.status,a=p.version;let i;m({status:"checking",error:null,reason:null,transient:!1,phase:null});try{i=await async function(){if(r)return r({pkg:u});if(f&&"function"==typeof f.checkPublished){const e=await f.checkPublished({current:d,pkg:u,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(g=0,h=0,S(),await async function(){if(null!==E)return E;if(!f||"function"!=typeof f.serverUpdateVerdict)return null;try{const e=await f.serverUpdateVerdict({current:d});return e&&e.ok&&(E=Boolean(e.decomposed)),E}catch{return null}}())return m({status:"decomposed",version:i.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0,decomposed:!0});if(!f.isNewer(i.latest,d))return m({status:"up-to-date",version:i.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0});const e=function(){if(v)return v;const e=f&&f.detectInstallMethod;if("function"!=typeof e)return v="npm",v;try{v=e({env:process.env,argv:process.argv,pkg:u,entry:__dirname,fileExists:e=>fs.existsSync(path.resolve(__dirname,"..",e))})}catch{v="npm"}return v}(),n="function"==typeof f.updatePlan?f.updatePlan({current:d,latest:i.latest,behind:!0,channel:"npm",pkg:u,method:e}):null;return m({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 one from the installer to pick it up`:n&&n.instruction||`npm i -g ${u}@latest`,commandIsSentence:t||Boolean(n&&!n.apply),canDownload:Boolean(n&&n.apply)&&!t})}g+=1;const c=i.error||describeRegistryFailure(i.reason,i.status,u);return w(i.reason,i.status)?(function(){S();const e=UPDATE_RETRY_BACKOFF_MS[Math.min(Math.max(g-1,0),UPDATE_RETRY_BACKOFF_MS.length-1)];h=n()+e,y=o(()=>{y=null,A().catch(()=>{})},e),y&&y.unref&&y.unref(),m({retryInMs:e})}(),m(e?{status:"error",phase:"check",error:c,reason:i.reason,transient:!0,attempts:g}:{status:"available"===s?"available":"unavailable",version:a,error:c,reason:i.reason,transient:!0,attempts:g})):(S(),h=0,m({status:"error",phase:"check",error:c,reason:i.reason,transient:!1,attempts:g,retryInMs:0}))})();try{return await k}finally{k=null}}return{status:()=>p,check:A,download:async()=>{const e=!t&&p.plan&&p.plan.apply;if(!e)return m({status:"available"===p.status?"available":p.status,command:p.plan&&p.plan.instruction||p.command,canDownload:!1});m({status:"downloading",error:null,progress:0,phase:null});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&&f&&"function"==typeof f.installSpawn?f.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?m({status:"downloaded",version:p.version,error:null,progress:100,command:`npm i -g ${u}@latest`,canDownload:!1}):m({status:"error",transient:!1,phase:"install",error:installFailureText(n.output),command:`${e.command} ${e.args.join(" ")}`})},quitAndInstall:()=>{"downloaded"===p.status&&(i||(()=>{try{const{app:e}=require("electron");e.relaunch(),e.exit(0)}catch{}}))()},start:()=>{A().catch(()=>{}),b=setInterval(()=>A().catch(()=>{}),144e5),b.unref&&b.unref()},stop:()=>{S(),b&&clearInterval(b),b=null},retryState:()=>({attempts:g,retryAt:h,inFlight:!!k,hasTimer:!!y})}}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(`aegis:${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("aegis:deepLink",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(),
7
7
  // The licence and the copyright, where the OS shows them. macOS draws
8
- copyright:creditsLib.COPYRIGHT,credits:`${creditsLib.LICENCE_NAME}\n${creditsLib.COPYRIGHT}\nSource: ${creditsLib.SOURCE_URL}\nHelp > Credits & licence lists the vendored third-party code and fonts.`});const a={label:"Check for Updates…",click:()=>r.check({announce:!0})},i={label:"New Chat",accelerator:"CmdOrCtrl+N",click:()=>sendToAppWindow(n,"aegis:menuNewChat")},c={label:"Search",accelerator:"CmdOrCtrl+K",click:()=>sendToAppWindow(n,"aegis:menuSearch")},l={label:"Command palette…",accelerator:"CmdOrCtrl+P",click:()=>sendToAppWindow(n,"aegis:menuPalette")},u={label:"Toggle sidebar",accelerator:"CmdOrCtrl+B",click:()=>sendToAppWindow(n,"aegis:menuToggleSidebar")},d={label:"Find in conversation",accelerator:"CmdOrCtrl+F",click:()=>sendToAppWindow(n,"aegis:menuFind")},p={label:"Go Back",accelerator:s?"Cmd+[":"Alt+Left",enabled:navState.back,click:()=>sendToAppWindow(n,"aegis:menuGoBack")},m={label:"Go Forward",accelerator:s?"Cmd+]":"Alt+Right",enabled:navState.forward,click:()=>sendToAppWindow(n,"aegis:menuGoForward")},f={label:"Search memory",accelerator:"CmdOrCtrl+Shift+K",visible:!1,click:()=>sendToAppWindow(n,"aegis:menuSearchMemory")},g={label:"Credits & Licence…",click:()=>sendToAppWindow(n,"aegis:menuCredits")},h={label:"Source Code",click:()=>{try{require("electron").shell.openExternal(creditsLib.SOURCE_URL)}catch{}}},y={label:"Save as…",accelerator:"CmdOrCtrl+S",click:()=>sendToAppWindow(n,"aegis:menuExportMarkdown")},k={label:"Export Session…",click:()=>sendToAppWindow(n,"aegis:menuExportJson")},b={label:"Authorship Panel…",click:()=>sendToAppWindow(n,"aegis:menuFingerprint")},v={label:"Google Drive Backup…",enabled:Boolean(o),click:()=>sendToAppWindow(n,"aegis:menuGoogleDrive")},S=[...s?[{label:e.getName(),submenu:[{role:"about"},a,{type:"separator"},g,h,{type:"separator"},{role:"services"},{type:"separator"},{role:"hide"},{role:"hideOthers"},{role:"unhide"},{type:"separator"},{role:"quit"}]}]:[],{label:"File",submenu:[i,{type:"separator"},y,k,{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"},{type:"separator"},d]},{label:"View",submenu:[l,c,f,{type:"separator"},u,{type:"separator"},p,m,{type:"separator"},b,v,{type:"separator"},{role:"reload",accelerator:"CmdOrCtrl+R"},{role:"forceReload"},{type:"separator"},{role:"toggleDevTools",accelerator:"CmdOrCtrl+Shift+I"}]},{label:"Help",submenu:[g,h,{type:"separator"},...s?[]:[{role:"about"}]]}];return t.buildFromTemplate(S)}function bootstrap(){let e=null;const t=electron&&electron.app,n=electron&&electron.BrowserWindow,r=(n,r)=>{const o=r&&(r.stack||r.message)||r&&String(r)||String(r),s=`[${(new Date).toISOString()}] ${n}: ${o}\n`;try{process.stderr.write(`aegis-desktop: ${s}`)}catch{}try{e=e||path.join(t.getPath("userData"),"crash.log"),fs.appendFileSync(e,s,{mode:384})}catch{}return o};process.on("uncaughtException",e=>{r("uncaughtException",e),process.exitCode=1,t?t.exit(1):process.exit(1)}),process.on("unhandledRejection",e=>{r("unhandledRejection",e)}),t&&"function"==typeof t.on&&t.on("render-process-gone",(e,t,o)=>{if(r("render-process-gone",new Error(JSON.stringify(o))),o&&"clean-exit"!==o.reason)try{const e=n.getFocusedWindow&&n.getFocusedWindow()||(n.getAllWindows?n.getAllWindows()[0]:null);e&&!e.isDestroyed()&&e.reload()}catch{}});let o=!1;try{o=require("./lib/local/integrity.js").armed()}catch{o=!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(o){try{const{app:e}=electron;e&&"function"==typeof e.quit&&e.quit()}catch{}return}const{app:s,BrowserWindow:a,ipcMain:i,safeStorage:c,shell:l,Menu:u,Notification:d,screen:p,dialog:m,globalShortcut:f}=electron;try{let e;try{e=require("./vendor/selfhost.js")}catch{e=require("../one/src/selfhost.js")}const t=e.plan({packaged:s.isPackaged,execPath:process.execPath,resourcesPath:process.resourcesPath,argv:process.argv.slice(1),invokedAs:path.basename(process.argv[1]||process.execPath)});if(t){const n=e.spawnOptions(t,process.env),r=require("node:child_process").spawnSync(n.exec,n.args,{stdio:"inherit",env:n.env}),o="number"==typeof r.status?r.status:1;return void s.exit(o)}}catch(e){s.isPackaged&&!/MODULE_NOT_FOUND/.test(String(e&&e.message))&&process.stderr.write(`aegis: terminal face hand-off failed: ${e&&e.message||e}\n`)}const g=gpuUsable({platform:process.platform,exists:e=>fs.existsSync(e),readdir:e=>fs.readdirSync(e)});if(g.usable?s.commandLine.appendSwitch("ignore-gpu-blocklist"):(s.disableHardwareAcceleration(),s.commandLine.appendSwitch("disable-gpu"),s.commandLine.appendSwitch("disable-software-rasterizer"),s.commandLine.appendSwitch("disable-gpu-compositing")),g.usable||s.commandLine.appendSwitch("disable-gpu-program-cache"),s.commandLine.appendSwitch("disable-features","UsePortalAccentColor,VaapiVideoDecoder,VaapiVideoEncoder"),process.argv.some(e=>/^--(log-level|enable-logging)/.test(e))||process.env.ELECTRON_ENABLE_LOGGING||s.commandLine.appendSwitch("log-level","3"),!s.requestSingleInstanceLock())return void s.quit();s.setName("aegis one");try{const e=s.getPath("userData"),t=path.dirname(e),n=["sessions.json","avatar","xp.json","queue.jsonl","memory.db","settings.json"],r=e=>{try{return fs.statSync(e).isDirectory()}catch{return!1}},o=e=>{try{return fs.statSync(e).size}catch{return-1}},a=e=>{try{return fs.readFileSync(path.join(e,"settings.json"),"utf8").includes('"__aegis"')}catch{return!1}},i=e=>{if(!r(e))return!1;let t;try{t=fs.readdirSync(e)}catch{return!1}return!!["sessions.json","avatar","xp.json","queue.jsonl"].some(e=>t.includes(e))||a(e)},c=t=>(()=>{try{return fs.realpathSync(t)===fs.realpathSync(e)}catch{return!1}})(),l=e=>r(e)&&0===fs.readdirSync(e).length,u=["AEGIS Desktop","AEGIS One","Electron","aegiscode-gui"].map(e=>path.join(t,e)).filter(e=>i(e)&&!c(e)).sort((e,t)=>o(path.join(t,"sessions.json"))-o(path.join(e,"sessions.json")))[0];if(u&&!i(e))try{if(!fs.existsSync(e)||l(e))fs.existsSync(e)&&fs.rmdirSync(e),fs.renameSync(u,e);else{const t=[];for(const r of n){const n=path.join(u,r),s=path.join(e,r);if(fs.existsSync(n)){if(fs.existsSync(s)){if(!("settings.json"===r&&a(u)&&!a(e)||"memory.db"===r&&o(n)>o(s)))continue;fs.rmSync(s,{recursive:!0,force:!0})}fs.renameSync(n,s),t.push(r)}}t.length&&console.warn(`aegis: adopted user state from ${u}: ${t.join(", ")}`)}}catch(t){console.warn(`aegis: could not move ${u} -> ${e} (${t&&t.message}); reading the old location instead`),s.setPath("userData",u)}try{const e=path.join(os.homedir(),".aegiscode","native-chat-history");if((e=>{try{return fs.statSync(e).isDirectory()}catch{return!1}})(e)){const t=fs.readdirSync(e).filter(e=>e.endsWith(".json")).sort(),n=new Set((sessionStore.listSessions(sessionStore.resolveStoreDir(null))||[]).map(e=>e&&e.id).filter(Boolean));let r=0;for(const o of t){let t=null;try{t=JSON.parse(fs.readFileSync(path.join(e,o),"utf8"))}catch{}if(!t||"object"!=typeof t||Array.isArray(t))continue;const s="string"==typeof t.createdAt&&t.createdAt||"string"==typeof t.created_at&&t.created_at||String(t.timestamp||"");if(!s)continue;let a=`native-${s.replace(/[^0-9T:.Z+-]/g,"")}`.slice(0,80);if(n.has(a)&&(a=`${a}-${o.replace(/\.json$/,"").slice(-24)}`),n.has(a))continue;const i=(Array.isArray(t.messages)?t.messages:t.history&&Array.isArray(t.history.messages)?t.history.messages:t.history&&Array.isArray(t.history)?t.history:t.entries&&Array.isArray(t.entries)?t.entries:[]).map(e=>{const t=void 0!==(e&&(e.content||e.text))?e.content||e.text:e&&"string"==typeof e.prompt?e.prompt:e&&"string"==typeof e.reply?e.reply:null;return null==t||""===t?null:{role:!e||"user"!==e.role&&"assistant"!==e.role?e&&"string"==typeof e.prompt?"user":e&&"string"==typeof e.reply?"assistant":"unknown":e.role,content:String(t)}}).filter(Boolean);if(!i.length)continue;const c=String(t.title||t.session&&t.session.title||"").trim();sessionStore.upsertSession(sessionStore.resolveStoreDir(null),{id:a,title:c||String((i.find(e=>"user"===e.role)||{}).content||"").slice(0,60),messages:i,cwd:"string"==typeof t.cwd?t.cwd:"",updatedAt:Date.parse(t.updatedAt||t.updated_at||t.createdAt||t.created_at||0)||Date.now(),origin:"native-chat",pending:!1}),n.add(a),r+=1}r&&console.warn(`aegis: imported ${r} conversation(s) from ${e}`)}}catch(e){console.warn(`aegis: native-chat import skipped: ${e&&e.message}`)}}catch(e){console.warn(`aegis: userData adoption skipped: ${e&&e.message}`)}if(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}`)}s.setAsDefaultProtocolClient(deepLink.PROTOCOL);let h=deepLink.parseDeepLinkArgv(process.argv);s.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):h=n});const y=createClient(credentials.clientOptions()),k=resolveUserDataDir(s),{engine:b,sessionsDir:v,settingsDir:S,settings:w,avatar:E}=createEngine(y,{app:s,safeStorage:c,dir:k}),A=createAccountKey({aegis:y,credentials:credentials,persistKey:e=>w.setAegisKey(e),provision:(e,t)=>autoProvision.autoProvisionApiKey(e,t,{app:"desktop"}),describeFailure:autoProvision.provisionFailureText,onChange:e=>K(e)});let M=null;const _=createGoogleConnect({aegis:y,credentials:credentials,persistKey:e=>w.setAegisKey(e),openUrl:e=>!!isSafeExternalUrl(e)&&(l.openExternal(e),!0),googleSignIn:googleSignIn,driveConnect:driveConnectLib,driveUpload:driveUploadLib,conversationExport:conversationExportLib?{...conversationExportLib,toTranscript:e=>sessionStore.toMarkdown(e)}:null,getSession:e=>sessionStore.getSession(v,e),getAuthor:()=>{try{M||(M=createFingerprintService({dir:k,getVaultBackend:()=>w.vaultBackendConfig().backend}));const e=M.status();return e&&e.ok?e:null}catch{return null}},onAccountChange:()=>K(A.status()),machineFingerprint:()=>sharedFingerprint.machineFingerprint()}),D=Boolean(y.apiKey),P=autoProvision.autoProvisionApiKey(y,credentials,{app:"desktop"}).then(e=>{if(A.recordStartup(e),!e.key&&!y.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(w,envFile,{onWarn:t}),b&&b.settings&&b.settings!==w&&e(b.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not wire the shared env-file key mirror: ${e&&e.message}`)}let C=null;const I=(e,t)=>{if(function(e){const t=e&&e.sender,n=t&&a.fromWebContents(t);if(!n||n.isDestroyed())return;if(n.isFocused()&&n.isVisible())return;if(!d||!d.isSupported())return;const r=new d({title:"aegis one",body:"Reply ready"});r.on("click",()=>{n.isDestroyed()||(n.isMinimized()&&n.restore(),n.isVisible()||n.show(),n.focus())}),r.show()}(e),C&&"function"==typeof C.note){const e=t&&(t.model||t.modelId)||void 0;C.note({sessionId:t&&t.sessionId||null,model:e})}};registerIpc(i,y,k,e=>{const t=w.setAegisKey(e);return e?credentials.saveApiKey(e):credentials.clearApiKey(),t},e=>l.openExternal(e),I,()=>providerRouteConfigured(b),()=>w.vaultBackendConfig().backend,E);const T=registerModelIpc(i,b,v,y,I,void 0,S,w);registerConfirmModeIpc(i,withAutoRoundsSwitch(createConfirmModeDispatch(w),T.modelDispatch)),registerConfirmModeIpc(i,createPermissionModeDispatch(w)),registerConfirmModeIpc(i,createFontScaleDispatch(w)),registerConfirmModeIpc(i,createAccentDispatch(w)),registerConfirmModeIpc(i,createDevModeDispatch(w)),registerConfirmModeIpc(i,createModelAutoSyncDispatch(w,b)),registerConfirmModeIpc(i,createVaultBackendDispatch(w)),registerConfirmModeIpc(i,createPermRulesDispatch(require("./lib/local/perm-store.js"))),registerConfirmModeIpc(i,createSandboxPolicyDispatch(w,require("./lib/local/sandbox.js"),{appDir:__dirname})),registerConfirmModeIpc(i,createCliFaceDispatch({appInfo:{packaged:s.isPackaged,resourcesPath:process.resourcesPath,appDir:__dirname,execPath:process.execPath,nodePath:process.execPath}}));const x=createPtyIpc(i,{appInfo:{packaged:s.isPackaged,resourcesPath:process.resourcesPath,appDir:__dirname,execPath:process.execPath,nodePath:process.execPath}}),R=new Set;i.handle("aegis:openPtyWindow",()=>{const e=x.hello(0);if(!(e&&e.ok&&e.r&&e.r.caps||[]).includes("pty"))return{ok:!1,reason:"no PTY backend in this build"};const t=iconForPlatform(resolveIconsDir(s.isPackaged,process.resourcesPath,__dirname),process.platform),n=R.size%6*28,r=U&&!U.isDestroyed()?U.getBounds():{x:80,y:80},o=new a({width:900,height:560,x:r.x+60+n,y:r.y+60+n,minWidth:380,minHeight:240,show:!1,backgroundColor:"#0d1117",title:"Terminal — aegiscode",icon:t,webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0,additionalArguments:g.usable?["--aegis-pty-gpu=1"]:[]}});return o.setMenuBarVisibility(!1),R.add(o),o.on("closed",()=>R.delete(o)),o.once("ready-to-show",()=>{o.isDestroyed()||o.show()}),o.loadFile(path.join(__dirname,"renderer","pty-window.html")),{ok:!0}}),i.handle("aegis:closePtyWindow",e=>{const t=e&&e.sender?a.fromWebContents(e.sender):null;return t&&R.has(t)&&!t.isDestroyed()&&t.close(),{ok:!0}}),registerTelemetryIpc(i,createTelemetryDispatch(createTelemetry({dir:S,enabled:telemetryEnabled(process.env,w),appVersion:(()=>{try{return"function"==typeof s.getVersion?s.getVersion():""}catch{return""}})()}))),registerCovenantIpc(i,createCovenantDispatch(covenantModule));const L=registerQueueIpc(i,{engine:createQueueEngine(y,w),aegis:y}),N=createAutoDrain({proceed:()=>L.proceed(),settings:w,queue:queueModule,env:process.env,log:e=>{e&&"skip"!==e.type&&(("auto-drain-armed"===e.type||"auto-drain-disarmed"===e.type)&&!process.env.ELECTRON_ENABLE_LOGGING||console.log("[auto-drain]",e.type,e.reason||e.error||""))}});let q=null;C=createAutoMint({mint:e=>(q||(q=createFingerprintService({dir:k,getVaultBackend:()=>w.vaultBackendConfig().backend})),q.mint(e||{})),settings:w}),registerAutoIpc(i,createAutoDispatch({autoDrain:N,autoMint:C})),N.start(),C.start();let U=null,F=null;function j(){return F&&!F.isDestroyed()||(F=new a({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(s.isPackaged,process.resourcesPath,__dirname),process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0}}),F.setMenuBarVisibility(!1),F.loadFile(path.join(__dirname,"renderer","quick.html")),F.webContents.on("before-input-event",(e,t)=>{"keyDown"!==t.type||"Escape"!==t.key||F.isDestroyed()||F.hide()}),F.on("blur",()=>{!F.isDestroyed()&&F.isVisible()&&F.hide()}),F.on("closed",()=>{F=null})),F}function O(){const e=j();e.isVisible()?e.hide():function(){const e=j(),t=p.getCursorScreenPoint(),n=p.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(U&&!U.isDestroyed())return U;const e=a.getFocusedWindow();return e&&!e.isDestroyed()&&e!==F?e:a.getAllWindows().find(e=>e!==F)||null};const B=createQuickLauncherDispatch(w,{isPackaged:s.isPackaged,applyConfig:function(e){if(f.unregisterAll(),!quickLauncherLib.shouldEnableGlobalShortcut({isPackaged:s.isPackaged,enabled:e.enabled}))return{active:!1,reason:null};try{if(!f.register(e.shortcut,O)){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 n=t&&t.sender&&a.fromWebContents(t.sender);n&&!n.isDestroyed()&&n.hide();const r=U&&!U.isDestroyed()?U:a.getAllWindows().find(e=>e!==n)||null;return r?(r.webContents.send("aegis:quickLauncherPush",e||{}),r.isMinimized()&&r.restore(),r.isVisible()||r.show(),r.focus(),{ok:!0}):{ok:!1,reason:"no main window is open"}}});registerQuickLauncherIpc(i,B);let $=null;s.on("will-quit",()=>{$&&"function"==typeof $.stop&&$.stop(),closeMemoryIndex(),f.unregisterAll(),G&&"function"==typeof G.stop&&G.stop(),V&&clearInterval(V),V=null});let H=!1;s.on("before-quit",e=>{!H&&b&&"function"==typeof b.unloadLocalModels&&(e.preventDefault(),Promise.resolve().then(()=>b.unloadLocalModels()).catch(()=>{}).finally(()=>{H=!0,s.quit()}))});const W=new Set;function K(e){for(const t of W)t.isDestroyed()||t.webContents.send(ACCOUNT_STATUS_CHANNEL,e);Q()}function Q(){u.setApplicationMenu(buildAppMenu({app:s,Menu:u,BrowserWindow:a,updateManager:G,loggedIn:Boolean(y.apiKey)}))}const G=createUpdateManager({isPackaged:s.isPackaged,onStatus:function(e){for(const t of W)t.isDestroyed()||t.webContents.send("aegis:updateStatus",e)}});let V=null;registerUpdateIpc(i,G),i.handle("aegis:accountStatus",()=>A.status()),i.handle("aegis:setNavState",(e,t)=>{const n=t&&"object"==typeof t?t:{},r=Boolean(n.back),o=Boolean(n.forward);return r===navState.back&&o===navState.forward||(navState.back=r,navState.forward=o,Q()),{ok:!0}}),i.handle("aegis:registerAccount",()=>A.registerAccount()),i.handle("aegis:driveSignIn",()=>_.signInWithGoogle()),i.handle("aegis:driveConnect",()=>_.connectDrive()),i.handle("aegis:driveStatus",()=>_.status()),i.handle("aegis:driveSyncMemory",()=>_.syncMemoryNow()),i.handle("aegis:driveBackupConversation",(e,t)=>_.backupConversation({sessionId:t&&t.sessionId})),i.handle("aegis:speechStatus",()=>{try{return speechHost.status({settings:readSpeechSettings(w)})}catch(e){return{enabled:!1,engine:"none",reason:e&&e.message||"dictation status failed"}}}),i.handle("aegis:speechSet",(e,t)=>{try{const e=t&&"object"==typeof t?t:{},n={...readSpeechSettings(w)};if("boolean"==typeof e.enabled&&(n.enabled=e.enabled),"string"==typeof e.engine&&(n.engine="local"===e.engine?"local":"none"),"string"==typeof e.model&&(n.model=e.model.trim()),"string"==typeof e.language&&(n.language=e.language.trim()||"auto"),null!=e.maxSeconds&&Number.isFinite(Number(e.maxSeconds))&&(n.maxSeconds=Math.min(600,Math.max(5,Math.round(Number(e.maxSeconds))))),!0===n.enabled){const e=speechHost.status({settings:{...n,enabled:!0}});if(!e.enabled)return{ok:!1,...e,settings:e.settings}}return w.setSharedPref("speech",n),{ok:!0,...speechHost.status({settings:n})}}catch(e){return{ok:!1,error:e&&e.message||"could not save dictation settings"}}}),i.handle("aegis:speechTranscribe",(e,t)=>{const n=t&&"object"==typeof t?t:{};return speechHost.transcribe(n.audio,{settings:readSpeechSettings(w),ext:n.ext}).catch(e=>({ok:!1,reason:e&&e.message||"transcription failed"}))}),i.handle("aegis:skillsList",()=>skillsHost.list()),i.handle("aegis:skillsRead",(e,t)=>skillsHost.read(t||{})),i.handle("aegis:skillsCreate",(e,t)=>skillsHost.create(t||{})),i.handle("aegis:skillsRemove",(e,t)=>skillsHost.remove(t||{})),i.handle("aegis:skillsImport",(e,t)=>skillsHost.importFromUrl(t||{})),registerExportIpc(i,sessionStore,v,e=>m.showSaveDialog(a.getFocusedWindow(),e),(e,t)=>fs.promises.writeFile(e,t,"utf8")),i.handle("aegis:credits",()=>{try{return creditsLib.creditsFromDisk({readText:e=>{const t=[path.join(__dirname,"..",e),path.join(__dirname,e),path.join(process.resourcesPath||"","app",e)];for(const e of t)try{return{path:e,text:fs.readFileSync(e,"utf8")}}catch{}return null}})}catch(e){return{program:{licence:creditsLib.LICENCE_ID,name:creditsLib.LICENCE_NAME,url:creditsLib.LICENCE_URL,source:creditsLib.SOURCE_URL,copyright:creditsLib.COPYRIGHT,notice:creditsLib.COPYRIGHT},documents:[],code:[],fonts:[],missing:["licensing","vendor","fonts"],error:String(e&&e.message||e)}}}),Q();const z=pathToFileURL(path.join(__dirname,"renderer","index.html")).href;function X(){const e=windowState.load(k),t=windowState.clampToDisplay(e,p.getAllDisplays(),{width:1080,height:720}),n=resolveIconsDir(s.isPackaged,process.resourcesPath,__dirname),r=new a({...t,minWidth:720,minHeight:480,show:!0,backgroundColor:"#0d1117",title:"aegis one",titleBarStyle:"hidden",titleBarOverlay:{color:"#111114",symbolColor:"#94a2b6",height:35},icon:iconForPlatform(n,process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0,spellcheck:!0,additionalArguments:g.usable?["--aegis-pty-gpu=1"]:[]}});e&&e.isMaximized&&r.maximize(),r.webContents.setWindowOpenHandler(({url:e})=>(isSafeExternalUrl(e)&&l.openExternal(e),{action:"deny"})),r.webContents.on("will-navigate",(e,t)=>{t!==z&&(e.preventDefault(),isSafeExternalUrl(t)&&l.openExternal(t))});let o=null;function i(){if(r.isDestroyed())return;const e=r.isMaximized(),t=e?r.getNormalBounds():r.getBounds();windowState.save(k,{...t,isMaximized:e})}function c(){o&&clearTimeout(o),o=setTimeout(i,500)}return r.on("resize",c),r.on("move",c),r.on("close",()=>{o&&clearTimeout(o),i()}),r.loadFile(path.join(__dirname,"renderer","index.html")),W.add(r),U=r,r.on("closed",()=>{W.delete(r),U===r&&(U=null)}),r}s.whenReady().then(async()=>{const e=e=>{if("string"!=typeof e||!e)return!1;try{const t=new URL(e);return"file:"===t.protocol||/^(localhost|127\.0\.0\.1)$/.test(t.hostname)}catch{return!1}},t=t=>{if(!t||"function"!=typeof t.getURL)return!1;const n=t.getURL();return!!e(n)&&!/quick\.html(?:[?#]|$)/.test(n)};try{const n=electron.session;n.defaultSession.setPermissionRequestHandler((n,r,o,s)=>{if("clipboard-sanitized-write"===r){const t=n&&"function"==typeof n.getURL?n.getURL():null;return o(e(t))}if("media"!==r)return o(!1);if(!t(n))return o(!1);const a=s&&s.mediaTypes||[];return Array.isArray(a)&&a.length&&!a.includes("audio")||Array.isArray(a)&&a.includes("video")?o(!1):o(!0)}),n.defaultSession.setPermissionCheckHandler((n,r,o)=>("clipboard-sanitized-write"===r||"media"===r&&!!t(n))&&e(o))}catch(e){console.warn(`aegis: could not install the microphone permission handler: ${e&&e.message}`)}if(!credentials.normalizeApiKey(process.env[credentials.KEY_ENV])){const e=await P,t=startupKeyOverride({mintedKey:D?"":e.key,hostKey:credentials.normalizeApiKey(w.aegisRawKey())});if(t)credentials.saveApiKey(t),y.setApiKey(t);else{const e=credentials.preferNewest(w.aegisRawKey(),w.aegisKeySavedAt());e.key&&(y.setApiKey(e.key),"shared"===e.source&&w.setAegisKey(e.key))}}try{$&&"function"==typeof $.stop&&$.stop(),$=sharedPresence.createPresence({apiKey:y.apiKey,app:"desktop",version:s.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)}}),$.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(w,envFile,{onWarn:t});n.mirrored.length&&console.warn(`aegis: shared ${n.mirrored.join(", ")} key(s) with the other hosts (${envFile.envFileFor()})`),b&&b.settings&&b.settings!==w&&e(b.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not backfill the shared env-file key mirror: ${e&&e.message}`)}B.setConfig(w.quickLauncherConfig());const n=X();G.start(),function(){if(V)return;const e=()=>{Promise.resolve(b.modelAutoSyncRun()).then(e=>{if(e&&e.ran){if(e.added>0&&"function"==typeof b.refreshByokModels)try{b.refreshByokModels()}catch{}for(const t of W)t.isDestroyed()||t.webContents.send("aegis:modelSyncReport",e)}}).catch(()=>{})},t=setTimeout(e,6e5);"function"==typeof t.unref&&t.unref(),V=setInterval(e,216e5),"function"==typeof V.unref&&V.unref()}(),h&&sendDeepLinkToWindow(n,h)}),s.on("window-all-closed",()=>{"darwin"!==process.platform&&s.quit()}),s.on("activate",()=>{const e=a.getAllWindows();if(0===e.length)return void X();const t=resolveTargetWindow()||e[0];t.isMinimized()&&t.restore(),t.isVisible()||t.show(),t.focus()}),s.on("second-instance",(e,t)=>{const n=resolveTargetWindow(),r=deepLink.parseDeepLinkArgv(t);if(!n){const e=X();return void(r&&sendDeepLinkToWindow(e,r))}n.isMinimized()&&n.restore(),n.isVisible()||n.show(),n.focus(),r&&sendDeepLinkToWindow(n,r)})}electron&&electron.app&&bootstrap(),module.exports={memoryIndex:memoryIndex,closeMemoryIndex:closeMemoryIndex,createIpcDispatch:createIpcDispatch,registerIpc:registerIpc,providerRouteConfigured:providerRouteConfigured,IPC_PREFIX:"aegis:",MODEL_PREFIX:"model:",SYNC_PREFIX:"sync:",watchTopupCredit:watchTopupCredit,bankAmount:bankAmount,TOPUP_POLL_MS:TOPUP_POLL_MS,TOPUP_POLL_TRIES:TOPUP_POLL_TRIES,CHAT_DELTA_CHANNEL:"aegis:chatDelta",PTY_EVENT_CHANNEL:"aegis:ptyEvent",createPtyIpc:createPtyIpc,MENU_NEW_CHAT_CHANNEL:"aegis:menuNewChat",MENU_SEARCH_CHANNEL:"aegis:menuSearch",MENU_SEARCH_MEMORY_CHANNEL:"aegis:menuSearchMemory",MENU_CREDITS_CHANNEL:"aegis:menuCredits",MENU_PALETTE_CHANNEL:"aegis:menuPalette",MENU_TOGGLE_SIDEBAR_CHANNEL:"aegis:menuToggleSidebar",MENU_EXPORT_MARKDOWN_CHANNEL:"aegis:menuExportMarkdown",MENU_EXPORT_JSON_CHANNEL:"aegis:menuExportJson",MENU_FINGERPRINT_CHANNEL:"aegis:menuFingerprint",MENU_GOOGLE_DRIVE_CHANNEL:"aegis:menuGoogleDrive",DEEP_LINK_CHANNEL:"aegis:deepLink",UPDATE_STATUS_CHANNEL:"aegis:updateStatus",UPDATE_CHECK_INTERVAL_MS:144e5,taggedChunk:taggedChunk,maskKey:maskKey,createModelDispatch:createModelDispatch,DESKTOP_CLASSES:DESKTOP_CLASSES,readTextFileForPreview:readTextFileForPreview,PREVIEW_READ_MAX_BYTES:524288,ingestAttachment:ingestAttachment,nativeImageResizer:nativeImageResizer,createSyncDispatch:createSyncDispatch,registerModelIpc:registerModelIpc,createHeartbeatRetry:createHeartbeatRetry,describeSyncError:describeSyncError,HEARTBEAT_RETRY_BASE_MS:5e3,HEARTBEAT_RETRY_MAX_MS:3e4,createEngine:createEngine,resolveUserDataDir:resolveUserDataDir,importForeignMemory:importForeignMemory,importForeignSessions:importForeignSessions,isSafeExternalUrl:isSafeExternalUrl,createUpdateManager:createUpdateManager,createNpmUpdateManager:createNpmUpdateManager,installFailureText:installFailureText,resolveUpdateOwner:resolveUpdateOwner,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:",QUICK_LAUNCHER_PUSH_CHANNEL:"aegis:quickLauncherPush",createQuickLauncherDispatch:createQuickLauncherDispatch,registerQuickLauncherIpc:registerQuickLauncherIpc,createConfirmModeDispatch:createConfirmModeDispatch,createDevModeDispatch:createDevModeDispatch,createModelAutoSyncDispatch:createModelAutoSyncDispatch,createVaultBackendDispatch:createVaultBackendDispatch,createPermRulesDispatch:createPermRulesDispatch,createSandboxPolicyDispatch:createSandboxPolicyDispatch,withAutoRoundsSwitch:withAutoRoundsSwitch,createTelemetryDispatch:createTelemetryDispatch,registerTelemetryIpc:registerTelemetryIpc,createCovenantDispatch:createCovenantDispatch,registerCovenantIpc:registerCovenantIpc,registerConfirmModeIpc:registerConfirmModeIpc,QUEUE_PREFIX:"queue:",QUEUE_PROGRESS_CHANNEL:"queue:progress",QUEUE_CHANGED_CHANNEL:"queue:changed",QUEUE_MAX_TASK_CHARS:8e3,QUEUE_MAX_ROUNDS:200,createQueueEngine:createQueueEngine,queueEngineWithDeniedApprovals:queueEngineWithDeniedApprovals,createQueueDispatch:createQueueDispatch,registerQueueIpc:registerQueueIpc,AUTO_PREFIX:"auto:",createAutoDispatch:createAutoDispatch,registerAutoIpc:registerAutoIpc};
8
+ copyright:creditsLib.COPYRIGHT,credits:`${creditsLib.LICENCE_NAME}\n${creditsLib.COPYRIGHT}\nSource: ${creditsLib.SOURCE_URL}\nHelp > Credits & licence lists the vendored third-party code and fonts.`});const a={label:"Check for Updates…",click:()=>r.check({announce:!0})},i={label:"New Chat",accelerator:"CmdOrCtrl+N",click:()=>sendToAppWindow(n,"aegis:menuNewChat")},c={label:"Search",accelerator:"CmdOrCtrl+K",click:()=>sendToAppWindow(n,"aegis:menuSearch")},l={label:"Command palette…",accelerator:"CmdOrCtrl+P",click:()=>sendToAppWindow(n,"aegis:menuPalette")},u={label:"Toggle sidebar",accelerator:"CmdOrCtrl+B",click:()=>sendToAppWindow(n,"aegis:menuToggleSidebar")},d={label:"Find in conversation",accelerator:"CmdOrCtrl+F",click:()=>sendToAppWindow(n,"aegis:menuFind")},p={label:"Go Back",accelerator:s?"Cmd+[":"Alt+Left",enabled:navState.back,click:()=>sendToAppWindow(n,"aegis:menuGoBack")},m={label:"Go Forward",accelerator:s?"Cmd+]":"Alt+Right",enabled:navState.forward,click:()=>sendToAppWindow(n,"aegis:menuGoForward")},f={label:"Search memory",accelerator:"CmdOrCtrl+Shift+K",visible:!1,click:()=>sendToAppWindow(n,"aegis:menuSearchMemory")},g={label:"Credits & Licence…",click:()=>sendToAppWindow(n,"aegis:menuCredits")},h={label:"Source Code",click:()=>{try{require("electron").shell.openExternal(creditsLib.SOURCE_URL)}catch{}}},y={label:"Save as…",accelerator:"CmdOrCtrl+S",click:()=>sendToAppWindow(n,"aegis:menuExportMarkdown")},k={label:"Export Session…",click:()=>sendToAppWindow(n,"aegis:menuExportJson")},b={label:"Authorship Panel…",click:()=>sendToAppWindow(n,"aegis:menuFingerprint")},v={label:"Google Drive Backup…",enabled:Boolean(o),click:()=>sendToAppWindow(n,"aegis:menuGoogleDrive")},S=[...s?[{label:e.getName(),submenu:[{role:"about"},a,{type:"separator"},g,h,{type:"separator"},{role:"services"},{type:"separator"},{role:"hide"},{role:"hideOthers"},{role:"unhide"},{type:"separator"},{role:"quit"}]}]:[],{label:"File",submenu:[i,{type:"separator"},y,k,{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"},{type:"separator"},d]},{label:"View",submenu:[l,c,f,{type:"separator"},u,{type:"separator"},p,m,{type:"separator"},b,v,{type:"separator"},{role:"reload",accelerator:"CmdOrCtrl+R"},{role:"forceReload"},{type:"separator"},{role:"toggleDevTools",accelerator:"CmdOrCtrl+Shift+I"}]},{label:"Help",submenu:[g,h,{type:"separator"},...s?[]:[{role:"about"}]]}];return t.buildFromTemplate(S)}function bootstrap(){let e=null;const t=electron&&electron.app,n=electron&&electron.BrowserWindow,r=(n,r)=>{const o=r&&(r.stack||r.message)||r&&String(r)||String(r),s=`[${(new Date).toISOString()}] ${n}: ${o}\n`;try{process.stderr.write(`aegis-desktop: ${s}`)}catch{}try{e=e||path.join(t.getPath("userData"),"crash.log"),fs.appendFileSync(e,s,{mode:384})}catch{}return o};process.on("uncaughtException",e=>{r("uncaughtException",e),process.exitCode=1,t?t.exit(1):process.exit(1)}),process.on("unhandledRejection",e=>{r("unhandledRejection",e)}),t&&"function"==typeof t.on&&t.on("render-process-gone",(e,t,o)=>{if(r("render-process-gone",new Error(JSON.stringify(o))),o&&"clean-exit"!==o.reason)try{const e=n.getFocusedWindow&&n.getFocusedWindow()||(n.getAllWindows?n.getAllWindows()[0]:null);e&&!e.isDestroyed()&&e.reload()}catch{}});let o=!1;try{o=require("./lib/local/integrity.js").armed()}catch{o=!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(o){try{const{app:e}=electron;e&&"function"==typeof e.quit&&e.quit()}catch{}return}const{app:s,BrowserWindow:a,ipcMain:i,safeStorage:c,shell:l,Menu:u,Notification:d,screen:p,dialog:m,globalShortcut:f}=electron;try{let e;try{e=require("./vendor/selfhost.js")}catch{e=require("../one/src/selfhost.js")}const t=e.plan({packaged:s.isPackaged,execPath:process.execPath,resourcesPath:process.resourcesPath,argv:process.argv.slice(1),invokedAs:path.basename(process.argv[1]||process.execPath)});if(t){const n=e.spawnOptions(t,process.env),r=require("node:child_process").spawnSync(n.exec,n.args,{stdio:"inherit",env:n.env}),o="number"==typeof r.status?r.status:1;return void s.exit(o)}}catch(e){s.isPackaged&&!/MODULE_NOT_FOUND/.test(String(e&&e.message))&&process.stderr.write(`aegis: terminal face hand-off failed: ${e&&e.message||e}\n`)}const g=gpuUsable({platform:process.platform,exists:e=>fs.existsSync(e),readdir:e=>fs.readdirSync(e)});if(g.usable?s.commandLine.appendSwitch("ignore-gpu-blocklist"):(s.disableHardwareAcceleration(),s.commandLine.appendSwitch("disable-gpu"),s.commandLine.appendSwitch("disable-software-rasterizer"),s.commandLine.appendSwitch("disable-gpu-compositing")),g.usable||s.commandLine.appendSwitch("disable-gpu-program-cache"),s.commandLine.appendSwitch("disable-features","UsePortalAccentColor,VaapiVideoDecoder,VaapiVideoEncoder"),process.argv.some(e=>/^--(log-level|enable-logging)/.test(e))||process.env.ELECTRON_ENABLE_LOGGING||s.commandLine.appendSwitch("log-level","3"),!s.requestSingleInstanceLock())return void s.quit();s.setName("aegis one");try{const e=s.getPath("userData"),t=path.dirname(e),n=["sessions.json","avatar","xp.json","queue.jsonl","memory.db","settings.json"],r=e=>{try{return fs.statSync(e).isDirectory()}catch{return!1}},o=e=>{try{return fs.statSync(e).size}catch{return-1}},a=e=>{try{return fs.readFileSync(path.join(e,"settings.json"),"utf8").includes('"__aegis"')}catch{return!1}},i=e=>{if(!r(e))return!1;let t;try{t=fs.readdirSync(e)}catch{return!1}return!!["sessions.json","avatar","xp.json","queue.jsonl"].some(e=>t.includes(e))||a(e)},c=t=>(()=>{try{return fs.realpathSync(t)===fs.realpathSync(e)}catch{return!1}})(),l=e=>r(e)&&0===fs.readdirSync(e).length,u=["AEGIS Desktop","AEGIS One","Electron","aegiscode-gui"].map(e=>path.join(t,e)).filter(e=>i(e)&&!c(e)).sort((e,t)=>o(path.join(t,"sessions.json"))-o(path.join(e,"sessions.json")))[0];if(u&&!i(e))try{if(!fs.existsSync(e)||l(e))fs.existsSync(e)&&fs.rmdirSync(e),fs.renameSync(u,e);else{const t=[];for(const r of n){const n=path.join(u,r),s=path.join(e,r);if(fs.existsSync(n)){if(fs.existsSync(s)){if(!("settings.json"===r&&a(u)&&!a(e)||"memory.db"===r&&o(n)>o(s)))continue;fs.rmSync(s,{recursive:!0,force:!0})}fs.renameSync(n,s),t.push(r)}}t.length&&console.warn(`aegis: adopted user state from ${u}: ${t.join(", ")}`)}}catch(t){console.warn(`aegis: could not move ${u} -> ${e} (${t&&t.message}); reading the old location instead`),s.setPath("userData",u)}try{const e=path.join(os.homedir(),".aegiscode","native-chat-history");if((e=>{try{return fs.statSync(e).isDirectory()}catch{return!1}})(e)){const t=fs.readdirSync(e).filter(e=>e.endsWith(".json")).sort(),n=new Set((sessionStore.listSessions(sessionStore.resolveStoreDir(null))||[]).map(e=>e&&e.id).filter(Boolean));let r=0;for(const o of t){let t=null;try{t=JSON.parse(fs.readFileSync(path.join(e,o),"utf8"))}catch{}if(!t||"object"!=typeof t||Array.isArray(t))continue;const s="string"==typeof t.createdAt&&t.createdAt||"string"==typeof t.created_at&&t.created_at||String(t.timestamp||"");if(!s)continue;let a=`native-${s.replace(/[^0-9T:.Z+-]/g,"")}`.slice(0,80);if(n.has(a)&&(a=`${a}-${o.replace(/\.json$/,"").slice(-24)}`),n.has(a))continue;const i=(Array.isArray(t.messages)?t.messages:t.history&&Array.isArray(t.history.messages)?t.history.messages:t.history&&Array.isArray(t.history)?t.history:t.entries&&Array.isArray(t.entries)?t.entries:[]).map(e=>{const t=void 0!==(e&&(e.content||e.text))?e.content||e.text:e&&"string"==typeof e.prompt?e.prompt:e&&"string"==typeof e.reply?e.reply:null;return null==t||""===t?null:{role:!e||"user"!==e.role&&"assistant"!==e.role?e&&"string"==typeof e.prompt?"user":e&&"string"==typeof e.reply?"assistant":"unknown":e.role,content:String(t)}}).filter(Boolean);if(!i.length)continue;const c=String(t.title||t.session&&t.session.title||"").trim(),l=String((i.find(e=>"user"===e.role)||{}).content||"").slice(0,60);sessionStore.upsertSession(sessionStore.resolveStoreDir(null),{id:a,title:c||l,named:!!c||void 0,messages:i,cwd:"string"==typeof t.cwd?t.cwd:"",updatedAt:Date.parse(t.updatedAt||t.updated_at||t.createdAt||t.created_at||0)||Date.now(),origin:"native-chat",pending:!1}),n.add(a),r+=1}r&&console.warn(`aegis: imported ${r} conversation(s) from ${e}`)}}catch(e){console.warn(`aegis: native-chat import skipped: ${e&&e.message}`)}}catch(e){console.warn(`aegis: userData adoption skipped: ${e&&e.message}`)}if(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}`)}s.setAsDefaultProtocolClient(deepLink.PROTOCOL);let h=deepLink.parseDeepLinkArgv(process.argv);s.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):h=n});const y=createClient(credentials.clientOptions()),k=resolveUserDataDir(s),{engine:b,sessionsDir:v,settingsDir:S,settings:w,avatar:E}=createEngine(y,{app:s,safeStorage:c,dir:k}),A=createAccountKey({aegis:y,credentials:credentials,persistKey:e=>w.setAegisKey(e),provision:(e,t)=>autoProvision.autoProvisionApiKey(e,t,{app:"desktop"}),describeFailure:autoProvision.provisionFailureText,onChange:e=>K(e)});let M=null;const _=createGoogleConnect({aegis:y,credentials:credentials,persistKey:e=>w.setAegisKey(e),openUrl:e=>!!isSafeExternalUrl(e)&&(l.openExternal(e),!0),googleSignIn:googleSignIn,driveConnect:driveConnectLib,driveUpload:driveUploadLib,conversationExport:conversationExportLib?{...conversationExportLib,toTranscript:e=>sessionStore.toMarkdown(e)}:null,getSession:e=>sessionStore.getSession(v,e),getAuthor:()=>{try{M||(M=createFingerprintService({dir:k,getVaultBackend:()=>w.vaultBackendConfig().backend}));const e=M.status();return e&&e.ok?e:null}catch{return null}},onAccountChange:()=>K(A.status()),machineFingerprint:()=>sharedFingerprint.machineFingerprint()}),D=Boolean(y.apiKey),P=autoProvision.autoProvisionApiKey(y,credentials,{app:"desktop"}).then(e=>{if(A.recordStartup(e),!e.key&&!y.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(w,envFile,{onWarn:t}),b&&b.settings&&b.settings!==w&&e(b.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not wire the shared env-file key mirror: ${e&&e.message}`)}let C=null;const I=(e,t)=>{if(function(e){const t=e&&e.sender,n=t&&a.fromWebContents(t);if(!n||n.isDestroyed())return;if(n.isFocused()&&n.isVisible())return;if(!d||!d.isSupported())return;const r=new d({title:"aegis one",body:"Reply ready"});r.on("click",()=>{n.isDestroyed()||(n.isMinimized()&&n.restore(),n.isVisible()||n.show(),n.focus())}),r.show()}(e),C&&"function"==typeof C.note){const e=t&&(t.model||t.modelId)||void 0;C.note({sessionId:t&&t.sessionId||null,model:e})}};registerIpc(i,y,k,e=>{const t=w.setAegisKey(e);return e?credentials.saveApiKey(e):credentials.clearApiKey(),t},e=>l.openExternal(e),I,()=>providerRouteConfigured(b),()=>w.vaultBackendConfig().backend,E);const T=registerModelIpc(i,b,v,y,I,void 0,S,w);registerConfirmModeIpc(i,withAutoRoundsSwitch(createConfirmModeDispatch(w),T.modelDispatch)),registerConfirmModeIpc(i,createPermissionModeDispatch(w)),registerConfirmModeIpc(i,createFontScaleDispatch(w)),registerConfirmModeIpc(i,createAccentDispatch(w)),registerConfirmModeIpc(i,createDevModeDispatch(w)),registerConfirmModeIpc(i,createModelAutoSyncDispatch(w,b)),registerConfirmModeIpc(i,createVaultBackendDispatch(w)),registerConfirmModeIpc(i,createPermRulesDispatch(require("./lib/local/perm-store.js"))),registerConfirmModeIpc(i,createSandboxPolicyDispatch(w,require("./lib/local/sandbox.js"),{appDir:__dirname})),registerConfirmModeIpc(i,createCliFaceDispatch({appInfo:{packaged:s.isPackaged,resourcesPath:process.resourcesPath,appDir:__dirname,execPath:process.execPath,nodePath:process.execPath}}));const x=createPtyIpc(i,{appInfo:{packaged:s.isPackaged,resourcesPath:process.resourcesPath,appDir:__dirname,execPath:process.execPath,nodePath:process.execPath}}),R=new Set;i.handle("aegis:openPtyWindow",()=>{const e=x.hello(0);if(!(e&&e.ok&&e.r&&e.r.caps||[]).includes("pty"))return{ok:!1,reason:"no PTY backend in this build"};const t=iconForPlatform(resolveIconsDir(s.isPackaged,process.resourcesPath,__dirname),process.platform),n=R.size%6*28,r=U&&!U.isDestroyed()?U.getBounds():{x:80,y:80},o=new a({width:900,height:560,x:r.x+60+n,y:r.y+60+n,minWidth:380,minHeight:240,show:!1,backgroundColor:"#0d1117",title:"Terminal — aegiscode",icon:t,webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0,additionalArguments:g.usable?["--aegis-pty-gpu=1"]:[]}});return o.setMenuBarVisibility(!1),R.add(o),o.on("closed",()=>R.delete(o)),o.once("ready-to-show",()=>{o.isDestroyed()||o.show()}),o.loadFile(path.join(__dirname,"renderer","pty-window.html")),{ok:!0}}),i.handle("aegis:closePtyWindow",e=>{const t=e&&e.sender?a.fromWebContents(e.sender):null;return t&&R.has(t)&&!t.isDestroyed()&&t.close(),{ok:!0}}),registerTelemetryIpc(i,createTelemetryDispatch(createTelemetry({dir:S,enabled:telemetryEnabled(process.env,w),appVersion:(()=>{try{return"function"==typeof s.getVersion?s.getVersion():""}catch{return""}})()}))),registerCovenantIpc(i,createCovenantDispatch(covenantModule));const L=registerQueueIpc(i,{engine:createQueueEngine(y,w),aegis:y}),N=createAutoDrain({proceed:()=>L.proceed(),settings:w,queue:queueModule,env:process.env,log:e=>{e&&"skip"!==e.type&&(("auto-drain-armed"===e.type||"auto-drain-disarmed"===e.type)&&!process.env.ELECTRON_ENABLE_LOGGING||console.log("[auto-drain]",e.type,e.reason||e.error||""))}});let q=null;C=createAutoMint({mint:e=>(q||(q=createFingerprintService({dir:k,getVaultBackend:()=>w.vaultBackendConfig().backend})),q.mint(e||{})),settings:w}),registerAutoIpc(i,createAutoDispatch({autoDrain:N,autoMint:C})),N.start(),C.start();let U=null,F=null;function j(){return F&&!F.isDestroyed()||(F=new a({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(s.isPackaged,process.resourcesPath,__dirname),process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0}}),F.setMenuBarVisibility(!1),F.loadFile(path.join(__dirname,"renderer","quick.html")),F.webContents.on("before-input-event",(e,t)=>{"keyDown"!==t.type||"Escape"!==t.key||F.isDestroyed()||F.hide()}),F.on("blur",()=>{!F.isDestroyed()&&F.isVisible()&&F.hide()}),F.on("closed",()=>{F=null})),F}function O(){const e=j();e.isVisible()?e.hide():function(){const e=j(),t=p.getCursorScreenPoint(),n=p.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(U&&!U.isDestroyed())return U;const e=a.getFocusedWindow();return e&&!e.isDestroyed()&&e!==F?e:a.getAllWindows().find(e=>e!==F)||null};const B=createQuickLauncherDispatch(w,{isPackaged:s.isPackaged,applyConfig:function(e){if(f.unregisterAll(),!quickLauncherLib.shouldEnableGlobalShortcut({isPackaged:s.isPackaged,enabled:e.enabled}))return{active:!1,reason:null};try{if(!f.register(e.shortcut,O)){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 n=t&&t.sender&&a.fromWebContents(t.sender);n&&!n.isDestroyed()&&n.hide();const r=U&&!U.isDestroyed()?U:a.getAllWindows().find(e=>e!==n)||null;return r?(r.webContents.send("aegis:quickLauncherPush",e||{}),r.isMinimized()&&r.restore(),r.isVisible()||r.show(),r.focus(),{ok:!0}):{ok:!1,reason:"no main window is open"}}});registerQuickLauncherIpc(i,B);let $=null;s.on("will-quit",()=>{$&&"function"==typeof $.stop&&$.stop(),closeMemoryIndex(),f.unregisterAll(),G&&"function"==typeof G.stop&&G.stop(),V&&clearInterval(V),V=null});let H=!1;s.on("before-quit",e=>{!H&&b&&"function"==typeof b.unloadLocalModels&&(e.preventDefault(),Promise.resolve().then(()=>b.unloadLocalModels()).catch(()=>{}).finally(()=>{H=!0,s.quit()}))});const W=new Set;function K(e){for(const t of W)t.isDestroyed()||t.webContents.send(ACCOUNT_STATUS_CHANNEL,e);Q()}function Q(){u.setApplicationMenu(buildAppMenu({app:s,Menu:u,BrowserWindow:a,updateManager:G,loggedIn:Boolean(y.apiKey)}))}const G=createUpdateManager({isPackaged:s.isPackaged,onStatus:function(e){for(const t of W)t.isDestroyed()||t.webContents.send("aegis:updateStatus",e)}});let V=null;registerUpdateIpc(i,G),i.handle("aegis:accountStatus",()=>A.status()),i.handle("aegis:setNavState",(e,t)=>{const n=t&&"object"==typeof t?t:{},r=Boolean(n.back),o=Boolean(n.forward);return r===navState.back&&o===navState.forward||(navState.back=r,navState.forward=o,Q()),{ok:!0}}),i.handle("aegis:registerAccount",()=>A.registerAccount()),i.handle("aegis:driveSignIn",()=>_.signInWithGoogle()),i.handle("aegis:driveConnect",()=>_.connectDrive()),i.handle("aegis:driveStatus",()=>_.status()),i.handle("aegis:driveSyncMemory",()=>_.syncMemoryNow()),i.handle("aegis:driveBackupConversation",(e,t)=>_.backupConversation({sessionId:t&&t.sessionId})),i.handle("aegis:speechStatus",()=>{try{return speechHost.status({settings:readSpeechSettings(w)})}catch(e){return{enabled:!1,engine:"none",reason:e&&e.message||"dictation status failed"}}}),i.handle("aegis:speechSet",(e,t)=>{try{const e=t&&"object"==typeof t?t:{},n={...readSpeechSettings(w)};if("boolean"==typeof e.enabled&&(n.enabled=e.enabled),"string"==typeof e.engine&&(n.engine="local"===e.engine?"local":"none"),"string"==typeof e.model&&(n.model=e.model.trim()),"string"==typeof e.language&&(n.language=e.language.trim()||"auto"),null!=e.maxSeconds&&Number.isFinite(Number(e.maxSeconds))&&(n.maxSeconds=Math.min(600,Math.max(5,Math.round(Number(e.maxSeconds))))),!0===n.enabled){const e=speechHost.status({settings:{...n,enabled:!0}});if(!e.enabled)return{ok:!1,...e,settings:e.settings}}return w.setSharedPref("speech",n),{ok:!0,...speechHost.status({settings:n})}}catch(e){return{ok:!1,error:e&&e.message||"could not save dictation settings"}}}),i.handle("aegis:speechTranscribe",(e,t)=>{const n=t&&"object"==typeof t?t:{};return speechHost.transcribe(n.audio,{settings:readSpeechSettings(w),ext:n.ext}).catch(e=>({ok:!1,reason:e&&e.message||"transcription failed"}))}),i.handle("aegis:skillsList",()=>skillsHost.list()),i.handle("aegis:skillsRead",(e,t)=>skillsHost.read(t||{})),i.handle("aegis:skillsCreate",(e,t)=>skillsHost.create(t||{})),i.handle("aegis:skillsRemove",(e,t)=>skillsHost.remove(t||{})),i.handle("aegis:skillsImport",(e,t)=>skillsHost.importFromUrl(t||{})),registerExportIpc(i,sessionStore,v,e=>m.showSaveDialog(a.getFocusedWindow(),e),(e,t)=>fs.promises.writeFile(e,t,"utf8")),i.handle("aegis:credits",()=>{try{return creditsLib.creditsFromDisk({readText:e=>{const t=[path.join(__dirname,"..",e),path.join(__dirname,e),path.join(process.resourcesPath||"","app",e)];for(const e of t)try{return{path:e,text:fs.readFileSync(e,"utf8")}}catch{}return null}})}catch(e){return{program:{licence:creditsLib.LICENCE_ID,name:creditsLib.LICENCE_NAME,url:creditsLib.LICENCE_URL,source:creditsLib.SOURCE_URL,copyright:creditsLib.COPYRIGHT,notice:creditsLib.COPYRIGHT},documents:[],code:[],fonts:[],missing:["licensing","vendor","fonts"],error:String(e&&e.message||e)}}}),Q();const z=pathToFileURL(path.join(__dirname,"renderer","index.html")).href;function X(){const e=windowState.load(k),t=windowState.clampToDisplay(e,p.getAllDisplays(),{width:1080,height:720}),n=resolveIconsDir(s.isPackaged,process.resourcesPath,__dirname),r=new a({...t,minWidth:720,minHeight:480,show:!0,backgroundColor:"#0d1117",title:"aegis one",titleBarStyle:"hidden",titleBarOverlay:{color:"#111114",symbolColor:"#94a2b6",height:35},icon:iconForPlatform(n,process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0,spellcheck:!0,additionalArguments:g.usable?["--aegis-pty-gpu=1"]:[]}});e&&e.isMaximized&&r.maximize(),r.webContents.setWindowOpenHandler(({url:e})=>(isSafeExternalUrl(e)&&l.openExternal(e),{action:"deny"})),r.webContents.on("will-navigate",(e,t)=>{t!==z&&(e.preventDefault(),isSafeExternalUrl(t)&&l.openExternal(t))});let o=null;function i(){if(r.isDestroyed())return;const e=r.isMaximized(),t=e?r.getNormalBounds():r.getBounds();windowState.save(k,{...t,isMaximized:e})}function c(){o&&clearTimeout(o),o=setTimeout(i,500)}return r.on("resize",c),r.on("move",c),r.on("close",()=>{o&&clearTimeout(o),i()}),r.loadFile(path.join(__dirname,"renderer","index.html")),W.add(r),U=r,r.on("closed",()=>{W.delete(r),U===r&&(U=null)}),r}s.whenReady().then(async()=>{const e=e=>{if("string"!=typeof e||!e)return!1;try{const t=new URL(e);return"file:"===t.protocol||/^(localhost|127\.0\.0\.1)$/.test(t.hostname)}catch{return!1}},t=t=>{if(!t||"function"!=typeof t.getURL)return!1;const n=t.getURL();return!!e(n)&&!/quick\.html(?:[?#]|$)/.test(n)};try{const n=electron.session;n.defaultSession.setPermissionRequestHandler((n,r,o,s)=>{if("clipboard-sanitized-write"===r){const t=n&&"function"==typeof n.getURL?n.getURL():null;return o(e(t))}if("media"!==r)return o(!1);if(!t(n))return o(!1);const a=s&&s.mediaTypes||[];return Array.isArray(a)&&a.length&&!a.includes("audio")||Array.isArray(a)&&a.includes("video")?o(!1):o(!0)}),n.defaultSession.setPermissionCheckHandler((n,r,o)=>("clipboard-sanitized-write"===r||"media"===r&&!!t(n))&&e(o))}catch(e){console.warn(`aegis: could not install the microphone permission handler: ${e&&e.message}`)}if(!credentials.normalizeApiKey(process.env[credentials.KEY_ENV])){const e=await P,t=startupKeyOverride({mintedKey:D?"":e.key,hostKey:credentials.normalizeApiKey(w.aegisRawKey())});if(t)credentials.saveApiKey(t),y.setApiKey(t);else{const e=credentials.preferNewest(w.aegisRawKey(),w.aegisKeySavedAt());e.key&&(y.setApiKey(e.key),"shared"===e.source&&w.setAegisKey(e.key))}}try{$&&"function"==typeof $.stop&&$.stop(),$=sharedPresence.createPresence({apiKey:y.apiKey,app:"desktop",version:s.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)}}),$.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(w,envFile,{onWarn:t});n.mirrored.length&&console.warn(`aegis: shared ${n.mirrored.join(", ")} key(s) with the other hosts (${envFile.envFileFor()})`),b&&b.settings&&b.settings!==w&&e(b.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not backfill the shared env-file key mirror: ${e&&e.message}`)}B.setConfig(w.quickLauncherConfig());const n=X();G.start(),function(){if(V)return;const e=()=>{Promise.resolve(b.modelAutoSyncRun()).then(e=>{if(e&&e.ran){if(e.added>0&&"function"==typeof b.refreshByokModels)try{b.refreshByokModels()}catch{}for(const t of W)t.isDestroyed()||t.webContents.send("aegis:modelSyncReport",e)}}).catch(()=>{})},t=setTimeout(e,6e5);"function"==typeof t.unref&&t.unref(),V=setInterval(e,216e5),"function"==typeof V.unref&&V.unref()}(),h&&sendDeepLinkToWindow(n,h)}),s.on("window-all-closed",()=>{"darwin"!==process.platform&&s.quit()}),s.on("activate",()=>{const e=a.getAllWindows();if(0===e.length)return void X();const t=resolveTargetWindow()||e[0];t.isMinimized()&&t.restore(),t.isVisible()||t.show(),t.focus()}),s.on("second-instance",(e,t)=>{const n=resolveTargetWindow(),r=deepLink.parseDeepLinkArgv(t);if(!n){const e=X();return void(r&&sendDeepLinkToWindow(e,r))}n.isMinimized()&&n.restore(),n.isVisible()||n.show(),n.focus(),r&&sendDeepLinkToWindow(n,r)})}electron&&electron.app&&bootstrap(),module.exports={memoryIndex:memoryIndex,closeMemoryIndex:closeMemoryIndex,createIpcDispatch:createIpcDispatch,registerIpc:registerIpc,providerRouteConfigured:providerRouteConfigured,IPC_PREFIX:"aegis:",MODEL_PREFIX:"model:",SYNC_PREFIX:"sync:",watchTopupCredit:watchTopupCredit,bankAmount:bankAmount,TOPUP_POLL_MS:TOPUP_POLL_MS,TOPUP_POLL_TRIES:TOPUP_POLL_TRIES,CHAT_DELTA_CHANNEL:"aegis:chatDelta",PTY_EVENT_CHANNEL:"aegis:ptyEvent",createPtyIpc:createPtyIpc,MENU_NEW_CHAT_CHANNEL:"aegis:menuNewChat",MENU_SEARCH_CHANNEL:"aegis:menuSearch",MENU_SEARCH_MEMORY_CHANNEL:"aegis:menuSearchMemory",MENU_CREDITS_CHANNEL:"aegis:menuCredits",MENU_PALETTE_CHANNEL:"aegis:menuPalette",MENU_TOGGLE_SIDEBAR_CHANNEL:"aegis:menuToggleSidebar",MENU_EXPORT_MARKDOWN_CHANNEL:"aegis:menuExportMarkdown",MENU_EXPORT_JSON_CHANNEL:"aegis:menuExportJson",MENU_FINGERPRINT_CHANNEL:"aegis:menuFingerprint",MENU_GOOGLE_DRIVE_CHANNEL:"aegis:menuGoogleDrive",DEEP_LINK_CHANNEL:"aegis:deepLink",UPDATE_STATUS_CHANNEL:"aegis:updateStatus",UPDATE_CHECK_INTERVAL_MS:144e5,taggedChunk:taggedChunk,maskKey:maskKey,createModelDispatch:createModelDispatch,DESKTOP_CLASSES:DESKTOP_CLASSES,readTextFileForPreview:readTextFileForPreview,PREVIEW_READ_MAX_BYTES:524288,ingestAttachment:ingestAttachment,nativeImageResizer:nativeImageResizer,createSyncDispatch:createSyncDispatch,registerModelIpc:registerModelIpc,createHeartbeatRetry:createHeartbeatRetry,describeSyncError:describeSyncError,HEARTBEAT_RETRY_BASE_MS:5e3,HEARTBEAT_RETRY_MAX_MS:3e4,createEngine:createEngine,resolveUserDataDir:resolveUserDataDir,importForeignMemory:importForeignMemory,importForeignSessions:importForeignSessions,isSafeExternalUrl:isSafeExternalUrl,createUpdateManager:createUpdateManager,createNpmUpdateManager:createNpmUpdateManager,installFailureText:installFailureText,resolveUpdateOwner:resolveUpdateOwner,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:",QUICK_LAUNCHER_PUSH_CHANNEL:"aegis:quickLauncherPush",createQuickLauncherDispatch:createQuickLauncherDispatch,registerQuickLauncherIpc:registerQuickLauncherIpc,createConfirmModeDispatch:createConfirmModeDispatch,createDevModeDispatch:createDevModeDispatch,createModelAutoSyncDispatch:createModelAutoSyncDispatch,createVaultBackendDispatch:createVaultBackendDispatch,createPermRulesDispatch:createPermRulesDispatch,createSandboxPolicyDispatch:createSandboxPolicyDispatch,withAutoRoundsSwitch:withAutoRoundsSwitch,createTelemetryDispatch:createTelemetryDispatch,registerTelemetryIpc:registerTelemetryIpc,createCovenantDispatch:createCovenantDispatch,registerCovenantIpc:registerCovenantIpc,registerConfirmModeIpc:registerConfirmModeIpc,QUEUE_PREFIX:"queue:",QUEUE_PROGRESS_CHANNEL:"queue:progress",QUEUE_CHANGED_CHANNEL:"queue:changed",QUEUE_MAX_TASK_CHARS:8e3,QUEUE_MAX_ROUNDS:200,createQueueEngine:createQueueEngine,queueEngineWithDeniedApprovals:queueEngineWithDeniedApprovals,createQueueDispatch:createQueueDispatch,registerQueueIpc:registerQueueIpc,AUTO_PREFIX:"auto:",createAutoDispatch:createAutoDispatch,registerAutoIpc:registerAutoIpc};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),STORE_FILE="sessions.json",STORE_VERSION=2,MAX_MESSAGES_PER_SESSION=2e3;function storeDir(e){return e||aegisHome()}function storeFile(e){return path.join(storeDir(e),STORE_FILE)}function nextSeq(e){const t=("number"==typeof e.__seq?e.__seq:0)+1;return e.__seq=t,t}function toEpochMs(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.trim()){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function load(e){try{const t=JSON.parse(fs.readFileSync(storeFile(e),"utf8"));if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}return{}}function atomicWrite(e,t){fs.mkdirSync(path.dirname(e),{recursive:!0});const n=`${e}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),fs.renameSync(n,e);try{fs.chmodSync(e,384)}catch{}}const LOCK_STALE_MS=3e4,LOCK_WAIT_MS=(()=>{const e=Number(process.env.AEGIS_STORE_LOCK_WAIT_MS);return Number.isFinite(e)&&e>0?e:15e3})(),SLEEP_CELL=new Int32Array(new SharedArrayBuffer(4));function lockFile(e){return`${storeFile(e)}.lock`}function acquireLock(e){const t=lockFile(e);try{fs.mkdirSync(path.dirname(t),{recursive:!0})}catch{return!1}const n=Date.now()+LOCK_WAIT_MS,s=Math.max(200,Math.ceil(LOCK_WAIT_MS/5)+200);for(let e=0;e<s;e++)try{const e=fs.openSync(t,"wx");return fs.writeSync(e,String(process.pid)),fs.closeSync(e),!0}catch{let e=null;try{e=Date.now()-fs.statSync(t).mtimeMs}catch{continue}if(lockAbandoned(t,e)){try{fs.unlinkSync(t)}catch{}continue}if(Date.now()>=n)return!1;Atomics.wait(SLEEP_CELL,0,0,5)}return!1}function pidAlive(e){try{return process.kill(e,0),!0}catch(e){return e&&"EPERM"===e.code}}function lockAbandoned(e,t){let n=0;try{n=Number(String(fs.readFileSync(e,"utf8")).trim())}catch{n=0}return Number.isInteger(n)&&n>0?!pidAlive(n):t>3e4}function releaseLock(e){try{fs.unlinkSync(lockFile(e))}catch{}}function mutate(e,t){if(!acquireLock(e))throw new Error(`session store is locked by another writer: ${lockFile(e)} (waited ${LOCK_WAIT_MS}ms — refusing to write unlocked and overwrite it)`);try{const n=load(e),s=t(n);return save(e,n),s}finally{releaseLock(e)}}function save(e,t){atomicWrite(storeFile(e),t)}function trimMessages(e){return Array.isArray(e)?e.length<=2e3?e:e.slice(e.length-2e3):[]}function upsertSession(e,t){const n=t&&t.id;if(!n)throw new Error("session.id is required");return mutate(e,e=>{const s=e[n]||{messages:[]};e[n]={...s,...t,id:n,version:2};const r=t&&!0===t.seed,i="string"==typeof s.title&&s.title;return!0===s.named&&i?(e[n].title=s.title,e[n].named=!0):r&&i&&s.title&&(e[n].title=s.title),delete e[n].seed,!1!==t.pending&&(e[n].pending=!0),e[n].updatedAt||(e[n].updatedAt=Date.now()),e[n].seq=nextSeq(e),e[n]})}function appendMessage(e,t,n){if(!t)throw new Error("sessionId is required");return mutate(e,e=>{const s=e[t]||{id:t,messages:[]},r=Array.isArray(s.messages)?s.messages:[];return s.messages=trimMessages(r.concat(n)),s.updatedAt=Date.now(),s.pending=!0,s.seq=nextSeq(e),e[t]=s,s})}function recordExchange(e,t){const n=t||{};if(!n.sessionId)return null;const s=n.sessionId;return mutate(e,e=>{const t=e[s]||{id:s,messages:[]},r=Array.isArray(t.messages)?t.messages:[],i=n.ts||(new Date).toISOString(),o={role:"user",content:null==n.prompt?"":String(n.prompt),ts:i},a={role:"assistant",content:null==n.reply?"":String(n.reply),ts:i};return n.tokens&&(a.tokens=n.tokens),"number"==typeof n.costUsd&&(a.costUsd=n.costUsd),n.status&&(a.status=n.status),n.model&&(a.model=n.model),n.provider&&(a.provider=n.provider),n.origin&&(o.origin=n.origin,a.origin=n.origin),t.messages=trimMessages(r.concat([o,a])),t.title=t.title||String(n.prompt||"").slice(0,60),n.cwd&&(t.cwd=n.cwd),t.origin=n.origin||t.origin||"unknown",t.updatedAt=Date.now(),t.pending=!0===n.pending,t.seq=nextSeq(e),e[s]=t,t})}function setTitle(e,t,n,s){const r=String(null==n?"":n).trim().slice(0,200);if(!t||!r)return null;const i=s&&!0===s.named;return mutate(e,e=>{const n=e[t];return n?(n.title=r,i&&(n.named=!0),n.updatedAt=Date.now(),n.seq=nextSeq(e),n):null})}function listSessions(e){const t=load(e);return Object.values(t).filter(e=>e&&e.id).sort((e,t)=>(t.updatedAt||0)-(e.updatedAt||0)||(t.seq||0)-(e.seq||0))}function getSession(e,t){return load(e)[t]||null}function deleteSession(e,t){return mutate(e,e=>(delete e[t],{ok:!0}))}function markSynced(e,t,n){return mutate(e,e=>{const s=e[t];return s?(s.pending=!1,s.lastSyncedAt=Date.now(),n&&n.remoteId&&(s.remoteId=n.remoteId),s.seq=nextSeq(e),s):null})}function markPending(e,t){return mutate(e,e=>{const n=e[t];return n?(n.pending=!0,n.seq=nextSeq(e),n):null})}function listPending(e){return listSessions(e).filter(e=>!1!==e.pending)}function mergeRemoteSessions(e,t){const n=Array.isArray(t)?t:[];return n.length?mutate(e,e=>{let t=0;for(const s of n){const n=s&&(s.session_id||s.id);if(!n)continue;const r=e[n],i=toEpochMs(s.updated_at??s.updatedAt);r&&(r.pending||(r.updatedAt||0)>=i)||(e[n]={id:n,title:s.title||r&&r.title||"",messages:Array.isArray(s.messages)?s.messages:[],updatedAt:i||Date.now(),pending:!1,lastSyncedAt:Date.now(),remoteId:s.session_id||s.id,origin:s.source||r&&r.origin||"cloud",version:2},e[n].seq=nextSeq(e),t+=1)}return t}):0}function listSummaries(e,t=8){return listSessions(e).slice(0,t).map(e=>{const t=Array.isArray(e.messages)?e.messages:[],n=t.find(e=>e&&"user"===e.role);return{id:e.id,cwd:(e.cwd||"").split(/[\\/]/).filter(Boolean).pop()||"~",summary:String(e.title||n&&n.content||"").slice(0,60),time:new Date(e.updatedAt||Date.now()).toISOString(),own:!0,origin:e.origin||"unknown",messages:t.length,pending:!0===e.pending,dir:String(e.cwd||"")}})}function readTranscript(e,t){const n=getSession(e,t);return n?(Array.isArray(n.messages)?n.messages:[]).filter(e=>e&&("user"===e.role||"assistant"===e.role)).map(e=>({role:e.role,text:null==e.content?"":String(e.content)})):[]}function adopt(e,t){const n=storeFile(t);if(!(()=>{try{return fs.existsSync(n)}catch{return!1}})())return{adopted:!1,sessions:0,from:n,reason:"no legacy store"};const s=(()=>{try{const e=JSON.parse(fs.readFileSync(n,"utf8"));return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}})(),r=Object.values(s).filter(e=>e&&e.id);if(!r.length)return{adopted:!1,sessions:0,from:n,reason:"legacy store empty"};let i=0;return mutate(e,e=>{for(const t of r)e[t.id]||(e[t.id]={...t,adoptedFrom:n,version:2},e[t.id].seq=nextSeq(e),i+=1);return e.__seq=Math.max(e.__seq||0,s.__seq||0),e.version=2,null}),i?{adopted:!0,sessions:i,from:n}:{adopted:!1,sessions:0,from:n,reason:"already adopted"}}function toMarkdown(e){const t=e&&(e.title||e.id)||"session",n=e&&Array.isArray(e.messages)?e.messages:[],s=[`# ${t}`,""];for(const e of n){const t=e&&e.role||"unknown",n=t.charAt(0).toUpperCase()+t.slice(1),r=e&&(e.content||e.text)||"";s.push(`## ${n}`,"",r,"")}return s.join("\n")}function toJson(e){return JSON.stringify(e,null,2)}module.exports={STORE_FILE:STORE_FILE,STORE_VERSION:2,MAX_MESSAGES_PER_SESSION:2e3,storeDir:storeDir,storeFile:storeFile,lockFile:lockFile,LOCK_STALE_MS:3e4,LOCK_WAIT_MS:LOCK_WAIT_MS,toEpochMs:toEpochMs,load:load,save:save,upsertSession:upsertSession,appendMessage:appendMessage,recordExchange:recordExchange,setTitle:setTitle,listSessions:listSessions,getSession:getSession,deleteSession:deleteSession,markSynced:markSynced,markPending:markPending,listPending:listPending,mergeRemoteSessions:mergeRemoteSessions,listSummaries:listSummaries,readTranscript:readTranscript,adopt:adopt,toMarkdown:toMarkdown,toJson:toJson};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),STORE_FILE="sessions.json",STORE_VERSION=2,MAX_MESSAGES_PER_SESSION=2e3;function storeDir(e){return e||aegisHome()}function storeFile(e){return path.join(storeDir(e),STORE_FILE)}function nextSeq(e){const t=("number"==typeof e.__seq?e.__seq:0)+1;return e.__seq=t,t}function toEpochMs(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.trim()){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function load(e){try{const t=JSON.parse(fs.readFileSync(storeFile(e),"utf8"));if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}return{}}function atomicWrite(e,t){fs.mkdirSync(path.dirname(e),{recursive:!0});const n=`${e}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),fs.renameSync(n,e);try{fs.chmodSync(e,384)}catch{}}const LOCK_STALE_MS=3e4,LOCK_WAIT_MS=(()=>{const e=Number(process.env.AEGIS_STORE_LOCK_WAIT_MS);return Number.isFinite(e)&&e>0?e:15e3})(),SLEEP_CELL=new Int32Array(new SharedArrayBuffer(4));function lockFile(e){return`${storeFile(e)}.lock`}function acquireLock(e){const t=lockFile(e);try{fs.mkdirSync(path.dirname(t),{recursive:!0})}catch{return!1}const n=Date.now()+LOCK_WAIT_MS,s=Math.max(200,Math.ceil(LOCK_WAIT_MS/5)+200);for(let e=0;e<s;e++)try{const e=fs.openSync(t,"wx");return fs.writeSync(e,String(process.pid)),fs.closeSync(e),!0}catch{let e=null;try{e=Date.now()-fs.statSync(t).mtimeMs}catch{continue}if(lockAbandoned(t,e)){try{fs.unlinkSync(t)}catch{}continue}if(Date.now()>=n)return!1;Atomics.wait(SLEEP_CELL,0,0,5)}return!1}function pidAlive(e){try{return process.kill(e,0),!0}catch(e){return e&&"EPERM"===e.code}}function lockAbandoned(e,t){let n=0;try{n=Number(String(fs.readFileSync(e,"utf8")).trim())}catch{n=0}return Number.isInteger(n)&&n>0?!pidAlive(n):t>3e4}function releaseLock(e){try{fs.unlinkSync(lockFile(e))}catch{}}function mutate(e,t){if(!acquireLock(e))throw new Error(`session store is locked by another writer: ${lockFile(e)} (waited ${LOCK_WAIT_MS}ms — refusing to write unlocked and overwrite it)`);try{const n=load(e),s=t(n);return save(e,n),s}finally{releaseLock(e)}}function save(e,t){atomicWrite(storeFile(e),t)}function trimMessages(e){return Array.isArray(e)?e.length<=2e3?e:e.slice(e.length-2e3):[]}function upsertSession(e,t){const n=t&&t.id;if(!n)throw new Error("session.id is required");return mutate(e,e=>{const s=e[n]||{messages:[]};e[n]={...s,...t,id:n,version:2};const r=t&&!0===t.seed,i="string"==typeof s.title&&s.title;return!0===s.named&&i?(e[n].title=s.title,e[n].named=!0):r&&i&&s.title&&(e[n].title=s.title),delete e[n].seed,!1!==t.pending&&(e[n].pending=!0),e[n].updatedAt||(e[n].updatedAt=Date.now()),e[n].seq=nextSeq(e),e[n]})}function appendMessage(e,t,n){if(!t)throw new Error("sessionId is required");return mutate(e,e=>{const s=e[t]||{id:t,messages:[]},r=Array.isArray(s.messages)?s.messages:[];return s.messages=trimMessages(r.concat(n)),s.updatedAt=Date.now(),s.pending=!0,s.seq=nextSeq(e),e[t]=s,s})}function recordExchange(e,t){const n=t||{};if(!n.sessionId)return null;const s=n.sessionId,r=null==n.reply?"":String(n.reply),i=""!==r.trim()&&"(no response)"!==r.trim();return mutate(e,e=>{if(!i&&!e[s])return null;const t=e[s]||{id:s,messages:[]},r=Array.isArray(t.messages)?t.messages:[],o=n.ts||(new Date).toISOString(),a={role:"user",content:null==n.prompt?"":String(n.prompt),ts:o},c={role:"assistant",content:null==n.reply?"":String(n.reply),ts:o};return n.tokens&&(c.tokens=n.tokens),"number"==typeof n.costUsd&&(c.costUsd=n.costUsd),n.status&&(c.status=n.status),n.model&&(c.model=n.model),n.provider&&(c.provider=n.provider),n.origin&&(a.origin=n.origin,c.origin=n.origin),t.messages=trimMessages(r.concat([a,c])),t.title=t.title||String(n.prompt||"").slice(0,60),n.cwd&&(t.cwd=n.cwd),t.origin=n.origin||t.origin||"unknown",t.updatedAt=Date.now(),t.pending=!0===n.pending,t.seq=nextSeq(e),e[s]=t,t})}function setTitle(e,t,n,s){const r=String(null==n?"":n).trim().slice(0,200);if(!t||!r)return null;const i=s&&!0===s.named;return mutate(e,e=>{const n=e[t];return n?(n.title=r,i&&(n.named=!0),n.updatedAt=Date.now(),n.seq=nextSeq(e),n):null})}function listSessions(e){const t=load(e);return Object.values(t).filter(e=>e&&e.id&&"string"==typeof e.id).sort((e,t)=>(t.updatedAt||0)-(e.updatedAt||0)||(t.seq||0)-(e.seq||0))}function getSession(e,t){return t&&t!==DELETED_KEY&&load(e)[t]||null}function deleteSession(e,t){return t?mutate(e,e=>{const n=e[t];if(!n)return{ok:!1};const s=deletedMap(e);return s[t]={at:Date.now(),remoteId:n.remoteId||null},e[DELETED_KEY]=s,nextSeq(e),delete e[t],{ok:!0}}):{ok:!1}}function markSynced(e,t,n){return mutate(e,e=>{const s=e[t];return s?(s.pending=!1,s.lastSyncedAt=Date.now(),n&&n.remoteId&&(s.remoteId=n.remoteId),s.seq=nextSeq(e),s):null})}function markPending(e,t){return mutate(e,e=>{const n=e[t];return n?(n.pending=!0,n.seq=nextSeq(e),n):null})}function listPending(e){return listSessions(e).filter(e=>!1!==e.pending)}const DELETED_KEY="__deleted";function deletedMap(e){const t=e&&e[DELETED_KEY];return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}function isDeleted(e,t){return!!t&&Boolean(deletedMap(load(e))[t])}function mergeRemoteSessions(e,t){const n=Array.isArray(t)?t:[];return n.length?mutate(e,e=>{let t=0;const s=deletedMap(e);for(const r of n){const n=r&&(r.session_id||r.id);if(!n)continue;if(s[n]&&!e[n])continue;const i=e[n],o=toEpochMs(r.updated_at??r.updatedAt);i&&(i.pending||(i.updatedAt||0)>=o)||(e[n]={id:n,title:r.title||i&&i.title||"",messages:Array.isArray(r.messages)?r.messages:[],updatedAt:o||Date.now(),pending:!1,lastSyncedAt:Date.now(),remoteId:r.session_id||r.id,origin:r.source||i&&i.origin||"cloud",version:2},e[n].seq=nextSeq(e),t+=1)}return t}):0}function listSummaries(e,t=8){return listSessions(e).slice(0,t).map(e=>{const t=Array.isArray(e.messages)?e.messages:[],n=t.find(e=>e&&"user"===e.role);return{id:e.id,cwd:(e.cwd||"").split(/[\\/]/).filter(Boolean).pop()||"~",summary:String(e.title||n&&n.content||"").slice(0,60),time:new Date(e.updatedAt||Date.now()).toISOString(),own:!0,origin:e.origin||"unknown",messages:t.length,pending:!0===e.pending,dir:String(e.cwd||"")}})}function readTranscript(e,t){const n=getSession(e,t);return n?(Array.isArray(n.messages)?n.messages:[]).filter(e=>e&&("user"===e.role||"assistant"===e.role)).map(e=>({role:e.role,text:null==e.content?"":String(e.content)})):[]}function adopt(e,t){const n=storeFile(t);if(!(()=>{try{return fs.existsSync(n)}catch{return!1}})())return{adopted:!1,sessions:0,from:n,reason:"no legacy store"};const s=(()=>{try{const e=JSON.parse(fs.readFileSync(n,"utf8"));return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}})(),r=Object.values(s).filter(e=>e&&e.id);if(!r.length)return{adopted:!1,sessions:0,from:n,reason:"legacy store empty"};let i=0;return mutate(e,e=>{const t=deletedMap(e);for(const s of r)e[s.id]||t[s.id]||(e[s.id]={...s,adoptedFrom:n,version:2},e[s.id].seq=nextSeq(e),i+=1);return e.__seq=Math.max(e.__seq||0,s.__seq||0),e.version=2,null}),i?{adopted:!0,sessions:i,from:n}:{adopted:!1,sessions:0,from:n,reason:"already adopted"}}function toMarkdown(e){const t=e&&(e.title||e.id)||"session",n=e&&Array.isArray(e.messages)?e.messages:[],s=[`# ${t}`,""];for(const e of n){const t=e&&e.role||"unknown",n=t.charAt(0).toUpperCase()+t.slice(1),r=e&&(e.content||e.text)||"";s.push(`## ${n}`,"",r,"")}return s.join("\n")}function toJson(e){return JSON.stringify(e,null,2)}module.exports={STORE_FILE:STORE_FILE,STORE_VERSION:2,MAX_MESSAGES_PER_SESSION:2e3,storeDir:storeDir,storeFile:storeFile,lockFile:lockFile,LOCK_STALE_MS:3e4,LOCK_WAIT_MS:LOCK_WAIT_MS,toEpochMs:toEpochMs,load:load,save:save,upsertSession:upsertSession,appendMessage:appendMessage,recordExchange:recordExchange,setTitle:setTitle,listSessions:listSessions,getSession:getSession,deleteSession:deleteSession,DELETED_KEY:DELETED_KEY,isDeleted:isDeleted,markSynced:markSynced,markPending:markPending,listPending:listPending,mergeRemoteSessions:mergeRemoteSessions,listSummaries:listSummaries,readTranscript:readTranscript,adopt:adopt,toMarkdown:toMarkdown,toJson:toJson};