aegisone 1.0.48 → 1.0.50

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/src/doctor.js +1 -1
  4. package/vendor/cli/package.json +1 -1
  5. package/vendor/cli/src/commands.js +1 -1
  6. package/vendor/cli/src/screens.js +1 -1
  7. package/vendor/cli/src/update.js +1 -1
  8. package/vendor/cli/vendor/client/naming.js +1 -1
  9. package/vendor/cli/vendor/client/session-store.js +1 -1
  10. package/vendor/cli/vendor/client/update.js +1 -1
  11. package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
  12. package/vendor/cli/vendor/desktop/main.js +153 -2
  13. package/vendor/desktop/lib/local/integrity.js +1 -1
  14. package/vendor/desktop/main.js +153 -2
  15. package/vendor/desktop/package.json +1 -1
  16. package/vendor/desktop/renderer/app.js +3 -3
  17. package/vendor/desktop/renderer/index.html +22 -3
  18. package/vendor/desktop/renderer/library.js +1 -1
  19. package/vendor/desktop/renderer/style.css +48 -0
  20. package/vendor/desktop/vendor/faces/cli/package.json +1 -1
  21. package/vendor/desktop/vendor/faces/cli/src/commands.js +1 -1
  22. package/vendor/desktop/vendor/faces/cli/src/screens.js +1 -1
  23. package/vendor/desktop/vendor/faces/cli/src/update.js +1 -1
  24. package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +1 -1
  25. package/vendor/desktop/vendor/faces/cli/vendor/client/session-store.js +1 -1
  26. package/vendor/desktop/vendor/faces/cli/vendor/client/update.js +1 -1
  27. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
  28. package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +2 -2
  29. package/vendor/desktop/vendor/naming.js +1 -1
  30. package/vendor/desktop/vendor/session-store.js +1 -1
  31. package/vendor/desktop/vendor/update.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 path=require("node:path"),fs=require("node:fs"),{execFileSync:execFileSync}=require("node:child_process"),{resolveShared:resolveShared}=require("./deps.js"),shared=require(resolveShared("client/update.js")),VERSION=require("../package.json").version,PKG=shared.PKG||"aegiscode";let methodCache=null;function installMethod(){if(methodCache)return methodCache;const e=shared.detectInstallMethod;if("function"!=typeof e)return methodCache="npm",methodCache;try{methodCache=e({env:process.env,argv:process.argv,pkg:PKG,entry:path.resolve(__dirname,".."),fileExists:e=>fs.existsSync(path.resolve(__dirname,"..","..",e))})}catch{methodCache="npm"}return methodCache}function compareVersions(e,n){const t=String(e||"0").split("-")[0].split(".").map((e=>Number.parseInt(e,10)||0)),r=String(n||"0").split("-")[0].split(".").map((e=>Number.parseInt(e,10)||0));for(let e=0;e<Math.max(t.length,r.length);e++){const n=(t[e]||0)-(r[e]||0);if(n)return n>0?1:-1}return 0}function upgradeAdvice({current:e=VERSION,latest:n=null,packageName:t=PKG,method:r="npm"}={}){if(!n)return{upToDate:null,lines:[` Could not read the npm registry — local version is ${e}.`]};if(compareVersions(n,e)>0){const a="function"==typeof shared.updatePlan?shared.updatePlan({current:e,latest:n,behind:!0,channel:"npm",pkg:t,method:r}):null,s=[` Installed: ${e}`,` Published: ${n}`,` Channel: ${r}`,` Upgrade: ${a&&a.instruction||`npm i -g ${t}@latest`}`];return a&&a.apply&&s.push(" (or run `/upgrade apply` to do it here)"),{upToDate:!1,lines:s,plan:a}}return{upToDate:!0,lines:[` Installed ${e} is the published ${n} — nothing to upgrade.`]}}function applyUpgrade({current:e=VERSION,packageName:n=PKG,method:t="npm",latest:r=null}={}){const a="function"==typeof shared.updatePlan&&r?shared.updatePlan({current:e,latest:r,behind:!0,channel:"npm",pkg:n,method:t}):null,s=a&&a.apply?a.apply:null;if(!s)return{ok:!0,skipped:!0,channel:t,command:null,instruction:a&&a.instruction||("npm"===t?`npm i -g ${n}@latest`:"restart to pick up the new version")};try{const e=("function"==typeof shared.installSpawn?shared.installSpawn(s,{env:process.env}):{command:s.command,args:s.args,shell:!1})||{command:s.command,args:s.args,shell:!1},n=execFileSync(e.command,e.args,{encoding:"utf8",timeout:18e4,stdio:["ignore","pipe","pipe"],shell:!0===e.shell,windowsHide:!0});return{ok:!0,channel:t,command:`${s.command} ${s.args.join(" ")}`,output:String(n||"").trim()}}catch(e){return{ok:!1,channel:t,command:`${s.command} ${s.args.join(" ")}`,error:String(e&&(e.stderr||e.message)||e).trim()}}}function latestPublishedVersion({packageName:e=PKG,timeoutMs:n=5e3}={}){try{const t=execFileSync("npm",["view",e,"version"],{encoding:"utf8",timeout:n,stdio:["ignore","pipe","ignore"]}),r=String(t).trim();return/^\d+\.\d+\.\d+/.test(r)?r:null}catch{return null}}module.exports={...shared,VERSION:VERSION,compareVersions:compareVersions,upgradeAdvice:upgradeAdvice,applyUpgrade:applyUpgrade,installMethod:installMethod,latestPublishedVersion:latestPublishedVersion};
3
+ "use strict";const path=require("node:path"),fs=require("node:fs"),{execFileSync:execFileSync}=require("node:child_process"),{resolveShared:resolveShared}=require("./deps.js"),shared=require(resolveShared("client/update.js")),VERSION=require("../package.json").version,PKG=shared.PKG||"aegiscode",DECOMPOSED_VERSIONS=Object.freeze(["1.0.47"]);function decomposedVersion(e=VERSION){return DECOMPOSED_VERSIONS.includes(String(e||"").trim())}function decomposedUpdateLine(e=VERSION){return decomposedVersion(e)?`This version (${e}) is DECOMPOSED — update to the latest release.`:null}let methodCache=null;function installMethod(){if(methodCache)return methodCache;const e=shared.detectInstallMethod;if("function"!=typeof e)return methodCache="npm",methodCache;try{methodCache=e({env:process.env,argv:process.argv,pkg:PKG,entry:path.resolve(__dirname,".."),fileExists:e=>fs.existsSync(path.resolve(__dirname,"..","..",e))})}catch{methodCache="npm"}return methodCache}function compareVersions(e,n){const t=String(e||"0").split("-")[0].split(".").map((e=>Number.parseInt(e,10)||0)),r=String(n||"0").split("-")[0].split(".").map((e=>Number.parseInt(e,10)||0));for(let e=0;e<Math.max(t.length,r.length);e++){const n=(t[e]||0)-(r[e]||0);if(n)return n>0?1:-1}return 0}function upgradeAdvice({current:e=VERSION,latest:n=null,packageName:t=PKG,method:r="npm"}={}){if(!n)return{upToDate:null,lines:[` Could not read the npm registry — local version is ${e}.`]};if(compareVersions(n,e)>0){const s="function"==typeof shared.updatePlan?shared.updatePlan({current:e,latest:n,behind:!0,channel:"npm",pkg:t,method:r}):null,a=[` Installed: ${e}`,` Published: ${n}`,` Channel: ${r}`,` Upgrade: ${s&&s.instruction||`npm i -g ${t}@latest`}`];return s&&s.apply&&a.push(" (or run `/upgrade apply` to do it here)"),{upToDate:!1,lines:a,plan:s}}return{upToDate:!0,lines:[` Installed ${e} is the published ${n} — nothing to upgrade.`]}}function applyUpgrade({current:e=VERSION,packageName:n=PKG,method:t="npm",latest:r=null}={}){const s="function"==typeof shared.updatePlan&&r?shared.updatePlan({current:e,latest:r,behind:!0,channel:"npm",pkg:n,method:t}):null,a=s&&s.apply?s.apply:null;if(!a)return{ok:!0,skipped:!0,channel:t,command:null,instruction:s&&s.instruction||("npm"===t?`npm i -g ${n}@latest`:"restart to pick up the new version")};try{const e=("function"==typeof shared.installSpawn?shared.installSpawn(a,{env:process.env}):{command:a.command,args:a.args,shell:!1})||{command:a.command,args:a.args,shell:!1},n=execFileSync(e.command,e.args,{encoding:"utf8",timeout:18e4,stdio:["ignore","pipe","pipe"],shell:!0===e.shell,windowsHide:!0});return{ok:!0,channel:t,command:`${a.command} ${a.args.join(" ")}`,output:String(n||"").trim()}}catch(e){return{ok:!1,channel:t,command:`${a.command} ${a.args.join(" ")}`,error:String(e&&(e.stderr||e.message)||e).trim()}}}function latestPublishedVersion({packageName:e=PKG,timeoutMs:n=5e3}={}){try{const t=execFileSync("npm",["view",e,"version"],{encoding:"utf8",timeout:n,stdio:["ignore","pipe","ignore"]}),r=String(t).trim();return/^\d+\.\d+\.\d+/.test(r)?r:null}catch{return null}}module.exports={...shared,VERSION:VERSION,compareVersions:compareVersions,upgradeAdvice:upgradeAdvice,applyUpgrade:applyUpgrade,installMethod:installMethod,latestPublishedVersion:latestPublishedVersion,DECOMPOSED_VERSIONS:DECOMPOSED_VERSIONS,decomposedVersion:decomposedVersion,decomposedUpdateLine:decomposedUpdateLine};
@@ -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 GENERIC_TITLE="New conversation",TITLE_SYSTEM='You name conversations. Write a short descriptive title (2 to 6 words) that captures the topic of the conversation. Never repeat the user\'s words verbatim — if the message is just a greeting or has no clear topic, name it something like "New conversation". Sentence case, no quotes, no markdown, no trailing punctuation, no explanation.',isGenericTitle=e=>!e||String(e).trim().toLowerCase()===GENERIC_TITLE.toLowerCase(),GREETINGS=new Set(["hey","heey","heyy","heyyy","hi","hii","hello","hej","hejj","yo","sup","hola","howdy","hai","heyo","hiya","wassup","greetings","namaste","ahoy","hallo"]);function isTopicless(e){const t=String(e).trim().toLowerCase().replace(/[^a-z0-9\s]/g," ").replace(/\s+/g," ").trim();if(!t)return!0;const i=t.split(" ");return!!/^(good (morning|afternoon|evening)|whats up|wassup|hey there|hello there|hi there|how are you)\b/.test(t)||i.length<=2&&t.length<=12&&GREETINGS.has(i[0])}function looksLikeEcho(e,t){const i=e=>String(e).toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim(),n=i(e),o=i(t);if(!n||!o)return!1;if(n===o)return!0;if(o.length<=14&&(n.startsWith(o)||o.startsWith(n)))return!0;if(o.length<=24){const i=e=>new Set((String(e).toLowerCase().match(/[a-z0-9]+/g)||[]).filter((e=>!ECHO_STOP.has(e)))),n=i(e),o=i(t);if(n.size&&n.size===o.size&&[...n].every((e=>o.has(e))))return!0}return!1}const ECHO_STOP=new Set(["the","a","an","to","of","in","on","at","for","and","or","is","are","be","it","its","my","our","please","can","you","just","do","that","this"]);function cleanTitle(e){return String(null==e?"":e).replace(/\s+/g," ").trim().replace(/["'`“”‘’]/g,"").replace(/[*_#]/g,"").replace(/^\s*(?:title|name)\s*[:\-–]\s*/i,"").replace(/[.\s]+$/g,"").slice(0,60).trim()}const titlePromptOf=e=>`Write a short title for a conversation that begins with: "${String(e).slice(0,500)}"`,FILLER=/^(?:please|pls|plz|hey|hi|hello|ok(?:ay)?|so|now|just|also|and|then|maybe|well|um|uh|can you|could you|would you|will you|i want you to|i want to|i need you to|i need to|i'?d like you to|i would like you to|i'?d like to|help me|help|let'?s|lets|go ahead and)\b[\s,:;-]*/i,TRAILING_STOP=new Set(["the","a","an","in","on","at","to","for","of","and","or","with","is","are","my","our","this","that","please","can","you","could","would","i","we","just","do","it"]);function deriveTitle(e){let t=String(null==e?"":e).trim().replace(/\s+/g," ");if(!t)return GENERIC_TITLE;for(let e=0;e<6;e++){const e=t.replace(FILLER,"").trim();if(e===t)break;t=e}const i=t.split(" ").filter(Boolean);if(!i.length)return GENERIC_TITLE;const n=i.slice(0,6);for(;n.length>2&&TRAILING_STOP.has(n[n.length-1].toLowerCase().replace(/[^a-z0-9]/g,""));)n.pop();let o=n.join(" ").replace(/[.,!?;:]+$/,"").trim();return o?(o=o[0].toUpperCase()+o.slice(1),o.slice(0,60).trim()||GENERIC_TITLE):GENERIC_TITLE}async function nameConversation(e,{callModel:t,signal:i}={}){const n=null==e?"":String(e);if(!n.trim())return"";if(isTopicless(n))return GENERIC_TITLE;if(!("function"!=typeof t||i&&i.aborted)){let e=null;try{e=await t(titlePromptOf(n),{system:TITLE_SYSTEM,signal:i,naming:!0})}catch{e=null}const o=cleanTitle(e);if(o)return looksLikeEcho(o,n)?GENERIC_TITLE:o}return deriveTitle(n)}async function refineTitle(e,t,i={}){const n=i&&!0===i.named,o=i&&!0===i.seeded;if(n)return null;if(!o&&!isGenericTitle(e))return null;if(!String(t||"").trim()||isTopicless(t))return null;const r=cleanTitle(await nameConversation(t,i));return!r||isGenericTitle(r)?null:r}async function nameSession(e,t,i,n,o={}){if(!e||"function"!=typeof e.setTitle)return null;if(!i)return null;const r="function"==typeof e.getSession?e.getSession(t,i):null,s=r&&r.title,l=!(!r||r.named);if(l&&s&&!isGenericTitle(s)&&!looksLikeEcho(s,n)){try{e.setTitle(t,i,s,{named:!0})}catch{return null}return null}const a={...o,seeded:l},c=await refineTitle(s,n,a);if(c){try{e.setTitle(t,i,c,{named:!0})}catch{return null}return c}if(isTopicless(n)&&r&&!r.named&&!isGenericTitle(s)){try{e.setTitle(t,i,GENERIC_TITLE)}catch{return null}return GENERIC_TITLE}return null}module.exports={GENERIC_TITLE:GENERIC_TITLE,TITLE_SYSTEM:TITLE_SYSTEM,isGenericTitle:isGenericTitle,isTopicless:isTopicless,looksLikeEcho:looksLikeEcho,cleanTitle:cleanTitle,titlePromptOf:titlePromptOf,deriveTitle:deriveTitle,nameConversation:nameConversation,refineTitle:refineTitle,nameSession:nameSession};
3
+ "use strict";const GENERIC_TITLE="New conversation",TITLE_SYSTEM='You name conversations. Write a short descriptive title (2 to 6 words) that captures the topic of the conversation. Never repeat the user\'s words verbatim — if the message is just a greeting or has no clear topic, name it something like "New conversation". Sentence case, no quotes, no markdown, no trailing punctuation, no explanation.',isGenericTitle=e=>!e||String(e).trim().toLowerCase()===GENERIC_TITLE.toLowerCase(),GREETINGS=new Set(["hey","heey","heyy","heyyy","hi","hii","hello","hej","hejj","yo","sup","hola","howdy","hai","heyo","hiya","wassup","greetings","namaste","ahoy","hallo"]);function isTopicless(e){const t=String(e).trim().toLowerCase().replace(/[^a-z0-9\s]/g," ").replace(/\s+/g," ").trim();if(!t)return!0;const i=t.split(" ");return!!/^(good (morning|afternoon|evening)|whats up|wassup|hey there|hello there|hi there|how are you)\b/.test(t)||i.length<=2&&t.length<=12&&GREETINGS.has(i[0])}function looksLikeEcho(e,t){const i=e=>String(e).toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim(),n=i(e),r=i(t);if(!n||!r)return!1;if(n===r)return!0;if(r.length<=14&&(n.startsWith(r)||r.startsWith(n)))return!0;if(r.length<=24){const i=e=>new Set((String(e).toLowerCase().match(/[a-z0-9]+/g)||[]).filter((e=>!ECHO_STOP.has(e)))),n=i(e),r=i(t);if(n.size&&n.size===r.size&&[...n].every((e=>r.has(e))))return!0}return!1}const SEED_MAX=60;function isSeedTitle(e,t){const i=String(null==e?"":e).replace(/\s+/g," ").trim(),n=String(null==t?"":t).replace(/\s+/g," ").trim();if(!i||!n)return!1;const r=n.slice(0,SEED_MAX);return i===r||!!(r.length===SEED_MAX&&i.length>=SEED_MAX-8&&r.startsWith(i))}const ECHO_STOP=new Set(["the","a","an","to","of","in","on","at","for","and","or","is","are","be","it","its","my","our","please","can","you","just","do","that","this"]);function cleanTitle(e){return String(null==e?"":e).replace(/\s+/g," ").trim().replace(/["'`“”‘’]/g,"").replace(/[*_#]/g,"").replace(/^\s*(?:title|name)\s*[:\-–]\s*/i,"").replace(/[.\s]+$/g,"").slice(0,60).trim()}const titlePromptOf=e=>`Write a short title for a conversation that begins with: "${String(e).slice(0,500)}"`,FILLER=/^(?:please|pls|plz|hey|hi|hello|ok(?:ay)?|so|now|just|also|and|then|maybe|well|um|uh|can you|could you|would you|will you|i want you to|i want to|i need you to|i need to|i'?d like you to|i would like you to|i'?d like to|help me|help|let'?s|lets|go ahead and)\b[\s,:;-]*/i,TRAILING_STOP=new Set(["the","a","an","in","on","at","to","for","of","and","or","with","is","are","my","our","this","that","please","can","you","could","would","i","we","just","do","it"]);function deriveTitle(e){let t=String(null==e?"":e).trim().replace(/\s+/g," ");if(!t)return GENERIC_TITLE;for(let e=0;e<6;e++){const e=t.replace(FILLER,"").trim();if(e===t)break;t=e}const i=t.split(" ").filter(Boolean);if(!i.length)return GENERIC_TITLE;const n=i.slice(0,6);for(;n.length>2&&TRAILING_STOP.has(n[n.length-1].toLowerCase().replace(/[^a-z0-9]/g,""));)n.pop();let r=n.join(" ").replace(/[.,!?;:]+$/,"").trim();return r?(r=r[0].toUpperCase()+r.slice(1),r.slice(0,60).trim()||GENERIC_TITLE):GENERIC_TITLE}async function nameConversation(e,{callModel:t,signal:i}={}){const n=null==e?"":String(e);if(!n.trim())return"";if(isTopicless(n))return GENERIC_TITLE;if(!("function"!=typeof t||i&&i.aborted)){let e=null;try{e=await t(titlePromptOf(n),{system:TITLE_SYSTEM,signal:i,naming:!0})}catch{e=null}const r=cleanTitle(e);if(r)return looksLikeEcho(r,n)?GENERIC_TITLE:r}return deriveTitle(n)}async function refineTitle(e,t,i={}){const n=i&&!0===i.named,r=i&&!0===i.seeded,o=isSeedTitle(e,t);if(n&&!o)return null;if(!r&&!isGenericTitle(e)&&!o)return null;if(!String(t||"").trim()||isTopicless(t))return null;const s=cleanTitle(await nameConversation(t,i));return!s||isGenericTitle(s)?null:s}async function nameSession(e,t,i,n,r={}){if(!e||"function"!=typeof e.setTitle)return null;if(!i)return null;const o="function"==typeof e.getSession?e.getSession(t,i):null,s=o&&o.title,l=!(!o||o.named);if(l&&s&&!isGenericTitle(s)&&!isSeedTitle(s,n)&&!looksLikeEcho(s,n)){try{e.setTitle(t,i,s,{named:!0})}catch{return null}return null}const a={...r,seeded:l},c=await refineTitle(s,n,a);if(c){try{e.setTitle(t,i,c,{named:!0})}catch{return null}return c}if(isTopicless(n)&&o&&!o.named&&!isGenericTitle(s)){try{e.setTitle(t,i,GENERIC_TITLE)}catch{return null}return GENERIC_TITLE}return null}module.exports={GENERIC_TITLE:GENERIC_TITLE,TITLE_SYSTEM:TITLE_SYSTEM,isGenericTitle:isGenericTitle,isTopicless:isTopicless,isSeedTitle:isSeedTitle,looksLikeEcho:looksLikeEcho,cleanTitle:cleanTitle,titlePromptOf:titlePromptOf,deriveTitle:deriveTitle,nameConversation:nameConversation,refineTitle:refineTitle,nameSession:nameSession};
@@ -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=2e3,LOCK_WAIT_MS=500;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;for(let e=0;e<200;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(e>LOCK_STALE_MS){try{fs.unlinkSync(t)}catch{}continue}if(Date.now()>=n)return!1;const s=Date.now()+5;for(;Date.now()<s;);}return!1}function releaseLock(e){try{fs.unlinkSync(lockFile(e))}catch{}}function mutate(e,t){const n=acquireLock(e);try{const n=load(e),s=t(n);return save(e,n),s}finally{n&&releaseLock(e)}}function save(e,t){atomicWrite(storeFile(e),t)}function trimMessages(e){return Array.isArray(e)?e.length<=MAX_MESSAGES_PER_SESSION?e:e.slice(e.length-MAX_MESSAGES_PER_SESSION):[]}function upsertSession(e,t){const n=t&&t.id;if(!n)throw new Error("session.id is required");return mutate(e,(e=>{const s=e[n]||{messages:[]};return e[n]={...s,...t,id:n,version:2},!0===s.named&&"string"==typeof s.title&&s.title&&(e[n].title=s.title,e[n].named=!0),!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:[],o=n.ts||(new Date).toISOString(),i={role:"user",content:null==n.prompt?"":String(n.prompt),ts:o},a={role:"assistant",content:null==n.reply?"":String(n.reply),ts:o};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&&(i.origin=n.origin,a.origin=n.origin),t.messages=trimMessages(r.concat([i,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 o=s&&!0===s.named;return mutate(e,(e=>{const n=e[t];return n?(n.title=r,o&&(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],o=toEpochMs(s.updated_at??s.updatedAt);r&&(r.pending||(r.updatedAt||0)>=o)||(e[n]={id:n,title:s.title||r&&r.title||"",messages:Array.isArray(s.messages)?s.messages:[],updatedAt:o||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 o=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),o+=1);return e.__seq=Math.max(e.__seq||0,s.__seq||0),e.version=2,null})),o?{adopted:!0,sessions:o,from:n}:{adopted:!1,sessions:0,from:n,reason:"already adopted"}}function toMarkdown(e){const t=e&&(e.title||e.id)||"session",n=e&&Array.isArray(e.messages)?e.messages:[],s=[`# ${t}`,""];for(const e of n){const t=e&&e.role||"unknown",n=t.charAt(0).toUpperCase()+t.slice(1),r=e&&(e.content||e.text)||"";s.push(`## ${n}`,"",r,"")}return s.join("\n")}function toJson(e){return JSON.stringify(e,null,2)}module.exports={STORE_FILE:STORE_FILE,STORE_VERSION:2,MAX_MESSAGES_PER_SESSION:MAX_MESSAGES_PER_SESSION,storeDir:storeDir,storeFile:storeFile,lockFile:lockFile,LOCK_STALE_MS:LOCK_STALE_MS,LOCK_WAIT_MS:LOCK_WAIT_MS,toEpochMs:toEpochMs,load:load,save:save,upsertSession:upsertSession,appendMessage:appendMessage,recordExchange:recordExchange,setTitle:setTitle,listSessions:listSessions,getSession:getSession,deleteSession:deleteSession,markSynced:markSynced,markPending:markPending,listPending:listPending,mergeRemoteSessions:mergeRemoteSessions,listSummaries:listSummaries,readTranscript:readTranscript,adopt:adopt,toMarkdown:toMarkdown,toJson:toJson};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),STORE_FILE="sessions.json",STORE_VERSION=2,MAX_MESSAGES_PER_SESSION=2e3;function storeDir(e){return e||aegisHome()}function storeFile(e){return path.join(storeDir(e),STORE_FILE)}function nextSeq(e){const t=("number"==typeof e.__seq?e.__seq:0)+1;return e.__seq=t,t}function toEpochMs(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.trim()){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function load(e){try{const t=JSON.parse(fs.readFileSync(storeFile(e),"utf8"));if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}return{}}function atomicWrite(e,t){fs.mkdirSync(path.dirname(e),{recursive:!0});const n=`${e}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),fs.renameSync(n,e);try{fs.chmodSync(e,384)}catch{}}const LOCK_STALE_MS=3e4,LOCK_WAIT_MS=(()=>{const e=Number(process.env.AEGIS_STORE_LOCK_WAIT_MS);return Number.isFinite(e)&&e>0?e:15e3})(),SLEEP_CELL=new Int32Array(new SharedArrayBuffer(4));function lockFile(e){return`${storeFile(e)}.lock`}function acquireLock(e){const t=lockFile(e);try{fs.mkdirSync(path.dirname(t),{recursive:!0})}catch{return!1}const n=Date.now()+LOCK_WAIT_MS,s=Math.max(200,Math.ceil(LOCK_WAIT_MS/5)+200);for(let e=0;e<s;e++)try{const e=fs.openSync(t,"wx");return fs.writeSync(e,String(process.pid)),fs.closeSync(e),!0}catch{let e=null;try{e=Date.now()-fs.statSync(t).mtimeMs}catch{continue}if(lockAbandoned(t,e)){try{fs.unlinkSync(t)}catch{}continue}if(Date.now()>=n)return!1;Atomics.wait(SLEEP_CELL,0,0,5)}return!1}function pidAlive(e){try{return process.kill(e,0),!0}catch(e){return e&&"EPERM"===e.code}}function lockAbandoned(e,t){let n=0;try{n=Number(String(fs.readFileSync(e,"utf8")).trim())}catch{n=0}return Number.isInteger(n)&&n>0?!pidAlive(n):t>LOCK_STALE_MS}function releaseLock(e){try{fs.unlinkSync(lockFile(e))}catch{}}function mutate(e,t){if(!acquireLock(e))throw new Error(`session store is locked by another writer: ${lockFile(e)} (waited ${LOCK_WAIT_MS}ms — refusing to write unlocked and overwrite it)`);try{const n=load(e),s=t(n);return save(e,n),s}finally{releaseLock(e)}}function save(e,t){atomicWrite(storeFile(e),t)}function trimMessages(e){return Array.isArray(e)?e.length<=MAX_MESSAGES_PER_SESSION?e:e.slice(e.length-MAX_MESSAGES_PER_SESSION):[]}function upsertSession(e,t){const n=t&&t.id;if(!n)throw new Error("session.id is required");return mutate(e,(e=>{const s=e[n]||{messages:[]};return e[n]={...s,...t,id:n,version:2},!0===s.named&&"string"==typeof s.title&&s.title&&(e[n].title=s.title,e[n].named=!0),!1!==t.pending&&(e[n].pending=!0),e[n].updatedAt||(e[n].updatedAt=Date.now()),e[n].seq=nextSeq(e),e[n]}))}function appendMessage(e,t,n){if(!t)throw new Error("sessionId is required");return mutate(e,(e=>{const s=e[t]||{id:t,messages:[]},r=Array.isArray(s.messages)?s.messages:[];return s.messages=trimMessages(r.concat(n)),s.updatedAt=Date.now(),s.pending=!0,s.seq=nextSeq(e),e[t]=s,s}))}function recordExchange(e,t){const n=t||{};if(!n.sessionId)return null;const s=n.sessionId;return mutate(e,(e=>{const t=e[s]||{id:s,messages:[]},r=Array.isArray(t.messages)?t.messages:[],i=n.ts||(new Date).toISOString(),o={role:"user",content:null==n.prompt?"":String(n.prompt),ts:i},a={role:"assistant",content:null==n.reply?"":String(n.reply),ts:i};return n.tokens&&(a.tokens=n.tokens),"number"==typeof n.costUsd&&(a.costUsd=n.costUsd),n.status&&(a.status=n.status),n.model&&(a.model=n.model),n.provider&&(a.provider=n.provider),n.origin&&(o.origin=n.origin,a.origin=n.origin),t.messages=trimMessages(r.concat([o,a])),t.title=t.title||String(n.prompt||"").slice(0,60),n.cwd&&(t.cwd=n.cwd),t.origin=n.origin||t.origin||"unknown",t.updatedAt=Date.now(),t.pending=!0===n.pending,t.seq=nextSeq(e),e[s]=t,t}))}function setTitle(e,t,n,s){const r=String(null==n?"":n).trim().slice(0,200);if(!t||!r)return null;const i=s&&!0===s.named;return mutate(e,(e=>{const n=e[t];return n?(n.title=r,i&&(n.named=!0),n.updatedAt=Date.now(),n.seq=nextSeq(e),n):null}))}function listSessions(e){const t=load(e);return Object.values(t).filter((e=>e&&e.id)).sort(((e,t)=>(t.updatedAt||0)-(e.updatedAt||0)||(t.seq||0)-(e.seq||0)))}function getSession(e,t){return load(e)[t]||null}function deleteSession(e,t){return mutate(e,(e=>(delete e[t],{ok:!0})))}function markSynced(e,t,n){return mutate(e,(e=>{const s=e[t];return s?(s.pending=!1,s.lastSyncedAt=Date.now(),n&&n.remoteId&&(s.remoteId=n.remoteId),s.seq=nextSeq(e),s):null}))}function markPending(e,t){return mutate(e,(e=>{const n=e[t];return n?(n.pending=!0,n.seq=nextSeq(e),n):null}))}function listPending(e){return listSessions(e).filter((e=>!1!==e.pending))}function mergeRemoteSessions(e,t){const n=Array.isArray(t)?t:[];return n.length?mutate(e,(e=>{let t=0;for(const s of n){const n=s&&(s.session_id||s.id);if(!n)continue;const r=e[n],i=toEpochMs(s.updated_at??s.updatedAt);r&&(r.pending||(r.updatedAt||0)>=i)||(e[n]={id:n,title:s.title||r&&r.title||"",messages:Array.isArray(s.messages)?s.messages:[],updatedAt:i||Date.now(),pending:!1,lastSyncedAt:Date.now(),remoteId:s.session_id||s.id,origin:s.source||r&&r.origin||"cloud",version:2},e[n].seq=nextSeq(e),t+=1)}return t})):0}function listSummaries(e,t=8){return listSessions(e).slice(0,t).map((e=>{const t=Array.isArray(e.messages)?e.messages:[],n=t.find((e=>e&&"user"===e.role));return{id:e.id,cwd:(e.cwd||"").split(/[\\/]/).filter(Boolean).pop()||"~",summary:String(e.title||n&&n.content||"").slice(0,60),time:new Date(e.updatedAt||Date.now()).toISOString(),own:!0,origin:e.origin||"unknown",messages:t.length,pending:!0===e.pending,dir:String(e.cwd||"")}}))}function readTranscript(e,t){const n=getSession(e,t);return n?(Array.isArray(n.messages)?n.messages:[]).filter((e=>e&&("user"===e.role||"assistant"===e.role))).map((e=>({role:e.role,text:null==e.content?"":String(e.content)}))):[]}function adopt(e,t){const n=storeFile(t);if(!(()=>{try{return fs.existsSync(n)}catch{return!1}})())return{adopted:!1,sessions:0,from:n,reason:"no legacy store"};const s=(()=>{try{const e=JSON.parse(fs.readFileSync(n,"utf8"));return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}})(),r=Object.values(s).filter((e=>e&&e.id));if(!r.length)return{adopted:!1,sessions:0,from:n,reason:"legacy store empty"};let i=0;return mutate(e,(e=>{for(const t of r)e[t.id]||(e[t.id]={...t,adoptedFrom:n,version:2},e[t.id].seq=nextSeq(e),i+=1);return e.__seq=Math.max(e.__seq||0,s.__seq||0),e.version=2,null})),i?{adopted:!0,sessions:i,from:n}:{adopted:!1,sessions:0,from:n,reason:"already adopted"}}function toMarkdown(e){const t=e&&(e.title||e.id)||"session",n=e&&Array.isArray(e.messages)?e.messages:[],s=[`# ${t}`,""];for(const e of n){const t=e&&e.role||"unknown",n=t.charAt(0).toUpperCase()+t.slice(1),r=e&&(e.content||e.text)||"";s.push(`## ${n}`,"",r,"")}return s.join("\n")}function toJson(e){return JSON.stringify(e,null,2)}module.exports={STORE_FILE:STORE_FILE,STORE_VERSION:2,MAX_MESSAGES_PER_SESSION:MAX_MESSAGES_PER_SESSION,storeDir:storeDir,storeFile:storeFile,lockFile:lockFile,LOCK_STALE_MS:LOCK_STALE_MS,LOCK_WAIT_MS:LOCK_WAIT_MS,toEpochMs:toEpochMs,load:load,save:save,upsertSession:upsertSession,appendMessage:appendMessage,recordExchange:recordExchange,setTitle:setTitle,listSessions:listSessions,getSession:getSession,deleteSession:deleteSession,markSynced:markSynced,markPending:markPending,listPending:listPending,mergeRemoteSessions:mergeRemoteSessions,listSummaries:listSummaries,readTranscript:readTranscript,adopt:adopt,toMarkdown:toMarkdown,toJson:toJson};
@@ -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
- const https=require("node:https"),fs=require("node:fs");let platformHelpers=null;try{platformHelpers=require("./platform.js")}catch{platformHelpers=null}const REGISTRY="https://registry.npmjs.org",PKG="aegiscode",CHECK_INTERVAL_MS=864e5,TIMEOUT_MS=2500;function isNewer(e,t){const n=e=>String(e||"").trim().replace(/^v/,"").split("-")[0].split(".").map((e=>Number.parseInt(e,10)||0)),r=n(e),s=n(t);for(let e=0;e<Math.max(r.length,s.length);e++){const t=r[e]||0,n=s[e]||0;if(t!==n)return t>n}return!1}const REASONS=Object.freeze({TIMEOUT:"timeout",NETWORK:"network",NOT_FOUND:"not-found",FORBIDDEN:"forbidden",HTTP:"http",MALFORMED:"malformed",TOO_LARGE:"too-large"});function isTransientReason(e,t=null){return e===REASONS.TIMEOUT||e===REASONS.NETWORK||e===REASONS.HTTP&&(!t||t>=500||429===t)}function fetchLatestDetailed({pkg:e=PKG,timeoutMs:t=TIMEOUT_MS}={}){return new Promise((n=>{let r=!1;const s=e=>{r||(r=!0,n(e))},l=(e,t=null)=>s({ok:!1,latest:null,reason:e,status:t});try{const n=https.get(`${REGISTRY}/${e}`,{headers:{accept:"application/vnd.npm.install-v1+json"},timeout:t},(e=>{const t=e.statusCode;if(200!==t)return e.resume(),l(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);let r="";e.setEncoding("utf8"),e.on("data",(e=>{r+=e,r.length>2e6&&(n.destroy(),l(REASONS.TOO_LARGE,t))})),e.on("end",(()=>{try{const e=JSON.parse(r)["dist-tags"],n=e&&e.latest||null;if(!n)return l(REASONS.MALFORMED,t);(e=>{s({ok:!0,latest:e,reason:null,status:200})})(n)}catch{l(REASONS.MALFORMED,t)}}))}));n.on("timeout",(()=>{n.destroy(),l(REASONS.TIMEOUT)})),n.on("error",(()=>l(REASONS.NETWORK)))}catch{l(REASONS.NETWORK)}}))}function fetchLatest(e={}){return fetchLatestDetailed(e).then((e=>e.ok?e.latest:null))}const DEFAULT_API_BASE="https://aegiscloud.org",VERSION_BODY_CAP=65536;function fetchServerVersionDetailed({base:e=DEFAULT_API_BASE,clientVersion:t=null,timeoutMs:n=TIMEOUT_MS,getImpl:r=null}={}){return new Promise((s=>{let l=!1;const o=e=>{l||(l=!0,s(e))},a=(e,t=null)=>o({ok:!1,minClient:null,latestCli:null,latestDesktop:null,upgradeRequired:null,downloadUrl:"",reason:e,status:t}),i=(e,n)=>{const r=e&&"string"==typeof e.min_client?e.min_client:null;if(!r)return a(REASONS.MALFORMED,n);o({ok:!0,minClient:r,latestCli:"string"==typeof e.latest_cli?e.latest_cli:"",latestDesktop:"string"==typeof e.latest_desktop?e.latest_desktop:"",upgradeRequired:t&&"boolean"==typeof e.upgrade_required?e.upgrade_required:null,downloadUrl:"string"==typeof e.download_url?e.download_url:"",reason:null,status:n})};try{const s=`${String(e||DEFAULT_API_BASE).replace(/\/+$/,"")}/api/v1/version`,o={accept:"application/json"};t&&(o["X-AEGIS-Version"]=String(t));const c=e=>{const t=e.statusCode;if(200!==t)return e.resume(),a(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);let n="";e.setEncoding("utf8"),e.on("data",(r=>{n+=r,n.length>VERSION_BODY_CAP&&(e.destroy(),a(REASONS.TOO_LARGE,t))})),e.on("end",(()=>{if(!l)try{i(JSON.parse(n),t)}catch{a(REASONS.MALFORMED,t)}}))};if("function"==typeof r)return void Promise.resolve(r({url:s,headers:o,timeoutMs:n})).then((e=>{const t=e&&null!=e.status?e.status:0;if(!t)return a(REASONS.NETWORK);if(200!==t)return a(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);const n=e&&"string"==typeof e.text?e.text:"";if(n.length>VERSION_BODY_CAP)return a(REASONS.TOO_LARGE,t);try{i(JSON.parse(n),t)}catch{a(REASONS.MALFORMED,t)}})).catch((()=>a(REASONS.NETWORK)));const u=require(/^http:\/\//i.test(s)?"node:http":"node:https").get(s,{headers:o,timeout:n},c);u.on("timeout",(()=>{u.destroy(),a(REASONS.TIMEOUT)})),u.on("error",(()=>a(REASONS.NETWORK)))}catch{a(REASONS.NETWORK)}}))}function fetchServerVersion(e={}){return fetchServerVersionDetailed(e).then((e=>e.ok?e.minClient:null))}async function serverUpdateVerdict({current:e,base:t=DEFAULT_API_BASE,timeoutMs:n=TIMEOUT_MS,getImpl:r=null}={}){const s=await fetchServerVersionDetailed({base:t,clientVersion:e,timeoutMs:n,getImpl:r});if(!s.ok)return{ok:!1,behind:!1,latest:null,required:null,downloadUrl:"",reason:s.reason,status:s.status};const l=s.minClient||null,o=!0===s.upgradeRequired||!1!==s.upgradeRequired&&!!l&&isNewer(l,e);return{ok:!0,behind:o,latest:o&&(s.latestCli||s.latestDesktop)||l,latestCli:s.latestCli,latestDesktop:s.latestDesktop,required:l,downloadUrl:s.downloadUrl,reason:null,status:s.status}}function updateNotice({current:e,cache:t,save:n,now:r=Date.now(),fetchImpl:s=fetchLatest,intervalMs:l=864e5}={}){const o=t||{};"number"==typeof o.checkedAt&&r-o.checkedAt<l||Promise.resolve(s()).then((e=>{e&&"function"==typeof n&&n({checkedAt:r,latest:e})})).catch((()=>{}));const a=o.latest||null;return{latest:a,behind:!(!a||!isNewer(a,e))}}function installSpawn(e,t={}){if(!e||"string"!=typeof e.command||!e.command)return null;const n=t&&"object"==typeof t?t:{},r="string"==typeof n.platform&&n.platform?n.platform:process.platform,s=n.env&&"object"==typeof n.env?n.env:process.env,l=void 0===n.helpers?platformHelpers:n.helpers,o=Array.isArray(e.args)?e.args.map(String):[],a=[e.command,...o].join(" ");if("win32"===r){const e=l&&"function"==typeof l.shellSpec?l.shellSpec({platform:r,env:s}):{cmd:"cmd.exe",arg:"/d /s /c"};return{command:e.cmd,args:[...String(e.arg).split(" "),a],shell:!1,script:a}}let i=e.command;if(l&&"function"==typeof l.resolveExecutable)try{const t=l.resolveExecutable(e.command,{platform:r,env:s,..."function"==typeof n.exists?{exists:n.exists}:{}});t&&(i=t)}catch{}return{command:i,args:o.slice(),shell:!1,script:a}}function updatePlan({current:e,latest:t,behind:n,channel:r="npm",pkg:s=PKG,method:l="npm"}={}){const o=String(null==e?"":e),a=t?String(t):null;if(!Boolean(n)||!Boolean(a))return{channel:r,method:l,current:o,latest:a,behind:!1,action:"none",applier:"none",instruction:null,apply:null};const i=APPLIERS[l]||APPLIERS.npm;return{channel:r,method:l,current:o,latest:a,behind:!0,action:i.action,applier:i.name,instruction:i.instruction(s),apply:i.apply?i.apply(s):null}}const APPLIERS=Object.freeze({npm:Object.freeze({name:"npm",action:"npm-update",instruction:e=>`npm i -g ${e}@latest`,apply:e=>({command:"npm",args:["i","-g",`${e}@latest`]})}),pip:Object.freeze({name:"pip",action:"pip-update",instruction:e=>`pip install -U ${e}`,apply:e=>({command:"win32"===process.platform?"python":"python3",args:["-m","pip","install","-U",e]})}),npx:Object.freeze({name:"none",action:"npx-update",instruction:()=>"already fetched fresh on every run — restart to pick up the new version",apply:null}),source:Object.freeze({name:"git",action:"source-update",instruction:()=>"git pull && npm ci (this copy is a source checkout)",apply:null})});function detectInstallMethod({env:e={},argv:t=[],pkg:n=PKG,fileExists:r=(()=>!1),entry:s=""}={}){const l=String(e&&e.AEGIS_INSTALL_METHOD||"").trim().toLowerCase();if(l&&Object.prototype.hasOwnProperty.call(APPLIERS,l))return l;const o=t.map((e=>String(e))).join(" ");return/\bnpx\b/.test(o)||/_npx[\\/]/.test(o)||/_npx[\\/]/.test(s)?"npx":/[\\/]pipx[\\/]venvs[\\/]/.test(s)||/[\\/]site-packages[\\/]/.test(s)?"pip":/[\\/]node_modules[\\/]/.test(s)?"npm":r(".git")&&r("client/update.js")?"source":"npm"}async function checkPublished({current:e,cache:t,save:n,now:r=Date.now(),fetchImpl:s=fetchLatestDetailed,intervalMs:l=864e5,timeoutMs:o=TIMEOUT_MS,pkg:a=PKG}={}){const i=t||null;if(Boolean(i)&&"number"==typeof i.checkedAt&&r-i.checkedAt<l){const t=i.latest||null;return{ok:Boolean(t),latest:t,behind:!(!t||!isNewer(t,e)),reason:t?null:i.reason||null,status:t?200:null==i.status?null:i.status,cached:!0,checkedAt:i.checkedAt}}let c;try{c=await s({pkg:a,timeoutMs:o})}catch(e){c={ok:!1,latest:null,reason:REASONS.NETWORK,status:null,error:String(e&&e.message||e)}}const u={checkedAt:r,latest:c&&c.latest?c.latest:null,reason:c&&c.reason||null,status:c&&null!=c.status?c.status:null};if("function"==typeof n)try{n(u)}catch{}return{ok:Boolean(c&&c.ok&&c.latest),latest:u.latest,behind:!(!u.latest||!isNewer(u.latest,e)),reason:u.reason,status:u.status,cached:!1,checkedAt:r}}function updateLine({current:e,latest:t,behind:n,pkg:r=PKG,method:s="npm"}){const l=updatePlan({current:e,latest:t,behind:n,channel:"npm",pkg:r,method:s});if(!l.behind)return null;const o=`Update available: ${l.current} → ${l.latest}`;return l.apply?`${o} run: ${l.instruction}`:`${o} ${l.instruction}`}function serverNotice({current:e,cache:t,save:n,now:r=Date.now(),verdictImpl:s=serverUpdateVerdict,intervalMs:l=864e5}={}){const o=t||{};return"number"==typeof o.checkedAt&&r-o.checkedAt<l||Promise.resolve().then((()=>s({current:e}))).then((e=>{e&&"function"==typeof n&&n({checkedAt:r,behind:Boolean(e.behind),required:e.required||null,latest:e.latest||null,downloadUrl:e.downloadUrl||"",reason:e.reason||null})})).catch((()=>{})),{behind:Boolean(o.behind),latest:o.latest||null,required:o.required||null,downloadUrl:o.downloadUrl||""}}function serverUpdateLine({behind:e,latest:t,required:n,downloadUrl:r}={}){if(!e)return null;const s=t||n||"";return`${s?`This build is no longer served — update to v${s}.`:"This build is no longer served — update to the latest release."}${r?` ${r}`:""}`}module.exports={isNewer:isNewer,fetchLatest:fetchLatest,fetchLatestDetailed:fetchLatestDetailed,fetchServerVersion:fetchServerVersion,fetchServerVersionDetailed:fetchServerVersionDetailed,serverUpdateVerdict:serverUpdateVerdict,serverNotice:serverNotice,serverUpdateLine:serverUpdateLine,isTransientReason:isTransientReason,updateNotice:updateNotice,checkPublished:checkPublished,updatePlan:updatePlan,installSpawn:installSpawn,updateLine:updateLine,detectInstallMethod:detectInstallMethod,APPLIERS:APPLIERS,PKG:PKG,CHECK_INTERVAL_MS:864e5,REASONS:REASONS,DEFAULT_API_BASE:DEFAULT_API_BASE};
3
+ const https=require("node:https"),fs=require("node:fs");let platformHelpers=null;try{platformHelpers=require("./platform.js")}catch{platformHelpers=null}const REGISTRY="https://registry.npmjs.org",PKG="aegiscode",CHECK_INTERVAL_MS=864e5,TIMEOUT_MS=2500;function isNewer(e,t){const n=e=>String(e||"").trim().replace(/^v/,"").split("-")[0].split(".").map((e=>Number.parseInt(e,10)||0)),s=n(e),r=n(t);for(let e=0;e<Math.max(s.length,r.length);e++){const t=s[e]||0,n=r[e]||0;if(t!==n)return t>n}return!1}const REASONS=Object.freeze({TIMEOUT:"timeout",NETWORK:"network",NOT_FOUND:"not-found",FORBIDDEN:"forbidden",HTTP:"http",MALFORMED:"malformed",TOO_LARGE:"too-large"});function isTransientReason(e,t=null){return e===REASONS.TIMEOUT||e===REASONS.NETWORK||e===REASONS.HTTP&&(!t||t>=500||429===t)}function fetchLatestDetailed({pkg:e=PKG,timeoutMs:t=TIMEOUT_MS}={}){return new Promise((n=>{let s=!1;const r=e=>{s||(s=!0,n(e))},o=(e,t=null)=>r({ok:!1,latest:null,reason:e,status:t});try{const n=https.get(`${REGISTRY}/${e}`,{headers:{accept:"application/vnd.npm.install-v1+json"},timeout:t},(e=>{const t=e.statusCode;if(200!==t)return e.resume(),o(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);let s="";e.setEncoding("utf8"),e.on("data",(e=>{s+=e,s.length>2e6&&(n.destroy(),o(REASONS.TOO_LARGE,t))})),e.on("end",(()=>{try{const e=JSON.parse(s)["dist-tags"],n=e&&e.latest||null;if(!n)return o(REASONS.MALFORMED,t);(e=>{r({ok:!0,latest:e,reason:null,status:200})})(n)}catch{o(REASONS.MALFORMED,t)}}))}));n.on("timeout",(()=>{n.destroy(),o(REASONS.TIMEOUT)})),n.on("error",(()=>o(REASONS.NETWORK)))}catch{o(REASONS.NETWORK)}}))}function fetchLatest(e={}){return fetchLatestDetailed(e).then((e=>e.ok?e.latest:null))}const DEFAULT_API_BASE="https://aegiscloud.org",VERSION_BODY_CAP=65536;function fetchServerVersionDetailed({base:e=DEFAULT_API_BASE,clientVersion:t=null,timeoutMs:n=TIMEOUT_MS,getImpl:s=null}={}){return new Promise((r=>{let o=!1;const l=e=>{o||(o=!0,r(e))},a=(e,t=null)=>l({ok:!1,minClient:null,latestCli:null,latestDesktop:null,upgradeRequired:null,decomposed:null,downloadUrl:"",reason:e,status:t}),i=(e,n)=>{const s=e&&"string"==typeof e.min_client?e.min_client:null;if(!s)return a(REASONS.MALFORMED,n);l({ok:!0,minClient:s,latestCli:"string"==typeof e.latest_cli?e.latest_cli:"",latestDesktop:"string"==typeof e.latest_desktop?e.latest_desktop:"",upgradeRequired:t&&"boolean"==typeof e.upgrade_required?e.upgrade_required:null,decomposed:t&&"boolean"==typeof e.decomposed?e.decomposed:null,downloadUrl:"string"==typeof e.download_url?e.download_url:"",reason:null,status:n})};try{const r=`${String(e||DEFAULT_API_BASE).replace(/\/+$/,"")}/api/v1/version`,l={accept:"application/json"};t&&(l["X-AEGIS-Version"]=String(t));const c=e=>{const t=e.statusCode;if(200!==t)return e.resume(),a(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);let n="";e.setEncoding("utf8"),e.on("data",(s=>{n+=s,n.length>VERSION_BODY_CAP&&(e.destroy(),a(REASONS.TOO_LARGE,t))})),e.on("end",(()=>{if(!o)try{i(JSON.parse(n),t)}catch{a(REASONS.MALFORMED,t)}}))};if("function"==typeof s)return void Promise.resolve(s({url:r,headers:l,timeoutMs:n})).then((e=>{const t=e&&null!=e.status?e.status:0;if(!t)return a(REASONS.NETWORK);if(200!==t)return a(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);const n=e&&"string"==typeof e.text?e.text:"";if(n.length>VERSION_BODY_CAP)return a(REASONS.TOO_LARGE,t);try{i(JSON.parse(n),t)}catch{a(REASONS.MALFORMED,t)}})).catch((()=>a(REASONS.NETWORK)));const u=require(/^http:\/\//i.test(r)?"node:http":"node:https").get(r,{headers:l,timeout:n},c);u.on("timeout",(()=>{u.destroy(),a(REASONS.TIMEOUT)})),u.on("error",(()=>a(REASONS.NETWORK)))}catch{a(REASONS.NETWORK)}}))}function fetchServerVersion(e={}){return fetchServerVersionDetailed(e).then((e=>e.ok?e.minClient:null))}async function serverUpdateVerdict({current:e,base:t=DEFAULT_API_BASE,timeoutMs:n=TIMEOUT_MS,getImpl:s=null}={}){const r=await fetchServerVersionDetailed({base:t,clientVersion:e,timeoutMs:n,getImpl:s});if(!r.ok)return{ok:!1,behind:!1,latest:null,required:null,decomposed:null,downloadUrl:"",reason:r.reason,status:r.status};const o=r.minClient||null,l=!0===r.upgradeRequired||!1!==r.upgradeRequired&&!!o&&isNewer(o,e);return{ok:!0,behind:l,latest:l&&(r.latestCli||r.latestDesktop)||o,latestCli:r.latestCli,latestDesktop:r.latestDesktop,required:o,decomposed:r.decomposed,downloadUrl:r.downloadUrl,reason:null,status:r.status}}function updateNotice({current:e,cache:t,save:n,now:s=Date.now(),fetchImpl:r=fetchLatest,intervalMs:o=864e5}={}){const l=t||{};"number"==typeof l.checkedAt&&s-l.checkedAt<o||Promise.resolve(r()).then((e=>{e&&"function"==typeof n&&n({checkedAt:s,latest:e})})).catch((()=>{}));const a=l.latest||null,i=!0===l.decomposed;return{latest:a,behind:!(!a||!isNewer(a,e)),decomposed:i}}function installSpawn(e,t={}){if(!e||"string"!=typeof e.command||!e.command)return null;const n=t&&"object"==typeof t?t:{},s="string"==typeof n.platform&&n.platform?n.platform:process.platform,r=n.env&&"object"==typeof n.env?n.env:process.env,o=void 0===n.helpers?platformHelpers:n.helpers,l=Array.isArray(e.args)?e.args.map(String):[],a=[e.command,...l].join(" ");if("win32"===s){const e=o&&"function"==typeof o.shellSpec?o.shellSpec({platform:s,env:r}):{cmd:"cmd.exe",arg:"/d /s /c"};return{command:e.cmd,args:[...String(e.arg).split(" "),a],shell:!1,script:a}}let i=e.command;if(o&&"function"==typeof o.resolveExecutable)try{const t=o.resolveExecutable(e.command,{platform:s,env:r,..."function"==typeof n.exists?{exists:n.exists}:{}});t&&(i=t)}catch{}return{command:i,args:l.slice(),shell:!1,script:a}}function updatePlan({current:e,latest:t,behind:n,channel:s="npm",pkg:r=PKG,method:o="npm"}={}){const l=String(null==e?"":e),a=t?String(t):null;if(!Boolean(n)||!Boolean(a))return{channel:s,method:o,current:l,latest:a,behind:!1,action:"none",applier:"none",instruction:null,apply:null};const i=APPLIERS[o]||APPLIERS.npm;return{channel:s,method:o,current:l,latest:a,behind:!0,action:i.action,applier:i.name,instruction:i.instruction(r),apply:i.apply?i.apply(r):null}}const APPLIERS=Object.freeze({npm:Object.freeze({name:"npm",action:"npm-update",instruction:e=>`npm i -g ${e}@latest`,apply:e=>({command:"npm",args:["i","-g",`${e}@latest`]})}),pip:Object.freeze({name:"pip",action:"pip-update",instruction:e=>`pip install -U ${e}`,apply:e=>({command:"win32"===process.platform?"python":"python3",args:["-m","pip","install","-U",e]})}),npx:Object.freeze({name:"none",action:"npx-update",instruction:()=>"already fetched fresh on every run — restart to pick up the new version",apply:null}),source:Object.freeze({name:"git",action:"source-update",instruction:()=>"git pull && npm ci (this copy is a source checkout)",apply:null})});function detectInstallMethod({env:e={},argv:t=[],pkg:n=PKG,fileExists:s=(()=>!1),entry:r=""}={}){const o=String(e&&e.AEGIS_INSTALL_METHOD||"").trim().toLowerCase();if(o&&Object.prototype.hasOwnProperty.call(APPLIERS,o))return o;const l=t.map((e=>String(e))).join(" ");return/\bnpx\b/.test(l)||/_npx[\\/]/.test(l)||/_npx[\\/]/.test(r)?"npx":/[\\/]pipx[\\/]venvs[\\/]/.test(r)||/[\\/]site-packages[\\/]/.test(r)?"pip":/[\\/]node_modules[\\/]/.test(r)?"npm":s(".git")&&s("client/update.js")?"source":"npm"}async function checkPublished({current:e,cache:t,save:n,now:s=Date.now(),fetchImpl:r=fetchLatestDetailed,intervalMs:o=864e5,timeoutMs:l=TIMEOUT_MS,pkg:a=PKG}={}){const i=t||null;if(Boolean(i)&&"number"==typeof i.checkedAt&&s-i.checkedAt<o){const t=i.latest||null;return{ok:Boolean(t),latest:t,behind:!(!t||!isNewer(t,e)),reason:t?null:i.reason||null,status:t?200:null==i.status?null:i.status,cached:!0,checkedAt:i.checkedAt}}let c;try{c=await r({pkg:a,timeoutMs:l})}catch(e){c={ok:!1,latest:null,reason:REASONS.NETWORK,status:null,error:String(e&&e.message||e)}}const u={checkedAt:s,latest:c&&c.latest?c.latest:null,reason:c&&c.reason||null,status:c&&null!=c.status?c.status:null};if("function"==typeof n)try{n(u)}catch{}return{ok:Boolean(c&&c.ok&&c.latest),latest:u.latest,behind:!(!u.latest||!isNewer(u.latest,e)),reason:u.reason,status:u.status,cached:!1,checkedAt:s}}function updateLine({current:e,latest:t,behind:n,pkg:s=PKG,method:r="npm"}){const o=updatePlan({current:e,latest:t,behind:n,channel:"npm",pkg:s,method:r});if(!o.behind)return null;const l=`Update available: ${o.current} → ${o.latest}`;return o.apply?`${l} run: ${o.instruction}`:`${l} ${o.instruction}`}function serverNotice({current:e,cache:t,save:n,now:s=Date.now(),verdictImpl:r=serverUpdateVerdict,intervalMs:o=864e5}={}){const l=t||{};return"number"==typeof l.checkedAt&&s-l.checkedAt<o||Promise.resolve().then((()=>r({current:e}))).then((e=>{e&&"function"==typeof n&&n({checkedAt:s,behind:Boolean(e.behind),decomposed:!0===e.decomposed,required:e.required||null,latest:e.latest||null,downloadUrl:e.downloadUrl||"",reason:e.reason||null})})).catch((()=>{})),{behind:Boolean(l.behind),decomposed:!0===l.decomposed,latest:l.latest||null,required:l.required||null,downloadUrl:l.downloadUrl||""}}function serverUpdateLine({behind:e,latest:t,required:n,decomposed:s,downloadUrl:r}={}){if(s)return`${t||n?`This version is DECOMPOSED — update to v${t||n}.`:"This version is DECOMPOSED — update to the latest release."}${r?` ${r}`:""}`;if(!e)return null;const o=t||n||"";return`${o?`This build is no longer served — update to v${o}.`:"This build is no longer served — update to the latest release."}${r?` ${r}`:""}`}module.exports={isNewer:isNewer,fetchLatest:fetchLatest,fetchLatestDetailed:fetchLatestDetailed,fetchServerVersion:fetchServerVersion,fetchServerVersionDetailed:fetchServerVersionDetailed,serverUpdateVerdict:serverUpdateVerdict,serverNotice:serverNotice,serverUpdateLine:serverUpdateLine,isTransientReason:isTransientReason,updateNotice:updateNotice,checkPublished:checkPublished,updatePlan:updatePlan,installSpawn:installSpawn,updateLine:updateLine,detectInstallMethod:detectInstallMethod,APPLIERS:APPLIERS,PKG:PKG,CHECK_INTERVAL_MS:864e5,REASONS:REASONS,DEFAULT_API_BASE:DEFAULT_API_BASE};
@@ -134,7 +134,7 @@ const UNITS = Object.freeze([
134
134
  * (`tools/desktop-seal.mjs` in the source tree, `tools/obfuscate-faces.mjs`
135
135
  * after obfuscation), never by hand.
136
136
  */
137
- const SEALED = '8ddbab7decbebe04faef45acc355a85c3dd93d87edfff43a8e2e96aa1152621a';
137
+ const SEALED = '748b1a00ed6c17df08b27b27d4f90eda70b75ab0fc56ab6f50f643952748c580';
138
138
 
139
139
  /**
140
140
  * Ask the question. Never throws — a check that can break the program it is
@@ -3034,10 +3034,47 @@ function createSyncDispatch(sessions, dir, aegis, settingsDir, modelDispatch) {
3034
3034
  // never pass `settingsDir` and use one directory for everything.
3035
3035
  const autoPush = persistGate.createAutoPush({ push, dir: settingsDir || dir });
3036
3036
 
3037
+ // The sidebar needs to PAINT a list, not read transcripts. `listSessions()`
3038
+ // hands back whole session records — every message of every conversation —
3039
+ // so this account's store (1219 sessions, 11,180 messages) serialized 10.5 MB
3040
+ // across IPC on EVERY pane refresh, per row of which the pane draws a title,
3041
+ // a message count and a timestamp. `messages` was 98% of that payload. The
3042
+ // transcript is fetched per conversation by `sync.open`, which is the only
3043
+ // caller that needs bodies, so shipping them here was pure waste on the
3044
+ // window's own thread — and the cost grew with the account's history, which
3045
+ // is why the app got slower the longer it was used.
3046
+ //
3047
+ // Two fields keep the renderer honest without the bodies:
3048
+ // * `messages` becomes a COUNT — `library.js#messageCount` and
3049
+ // `sessionResultRow` already accept a number instead of an array;
3050
+ // * `firstPrompt` carries the opening user message, which is what the
3051
+ // unnamed-title fallback, the rename-seed check and the filter haystack
3052
+ // read out of `messages[0]`.
3053
+ const SIDEBAR_FIELDS = [
3054
+ 'id', 'title', 'updatedAt', 'pending', 'named', 'seq', 'cwd', 'dir',
3055
+ 'origin', 'remoteId', 'lastSyncedAt',
3056
+ ];
3057
+ function sessionListing(all) {
3058
+ const list = Array.isArray(all) ? all : [];
3059
+ return list
3060
+ .filter((s) => s && s.id)
3061
+ .map((s) => {
3062
+ const row = {};
3063
+ for (const field of SIDEBAR_FIELDS) {
3064
+ if (s[field] !== undefined) row[field] = s[field];
3065
+ }
3066
+ const messages = Array.isArray(s.messages) ? s.messages : [];
3067
+ row.messages = messages.length;
3068
+ const first = messages.find((m) => m && m.role === 'user' && m.content);
3069
+ row.firstPrompt = first ? String(first.content) : '';
3070
+ return row;
3071
+ });
3072
+ }
3073
+
3037
3074
  return {
3038
3075
  auto: () => autoPush.auto(),
3039
3076
  memoryPersistState: () => autoPush.gate(),
3040
- listSessions: () => ({ sessions: sessions.listSessions(dir) }),
3077
+ listSessions: () => ({ sessions: sessionListing(sessions.listSessions(dir)) }),
3041
3078
  // The ONE search the menu's "Search" (Cmd/Ctrl+K) runs — sessions AND
3042
3079
  // memory under a single query box.
3043
3080
  //
@@ -4264,6 +4301,10 @@ function createNpmUpdateManager({
4264
4301
  plan: null,
4265
4302
  method: null,
4266
4303
  canDownload: false,
4304
+ // A release the server has declared retired (`decomposed: true` from
4305
+ // /api/v1/version) is not a suggestion — the banner must say it even
4306
+ // when no newer version resolves and no download can be offered.
4307
+ decomposed: false,
4267
4308
  };
4268
4309
  const set = (patch) => {
4269
4310
  state = { ...state, ...patch };
@@ -4376,6 +4417,22 @@ function createNpmUpdateManager({
4376
4417
  return reason === 'unknown'; // unclassified: assume retryable, stay quiet
4377
4418
  };
4378
4419
 
4420
+ // The server is asked at most once per process for this: a retired release
4421
+ // does not un-retire, and re-asking on every 4h check is the nagging the
4422
+ // checker's once-a-day rule exists to avoid.
4423
+ let decomposedCache = null; // null = no answer yet (failures are not cached)
4424
+ async function decomposedVerdict() {
4425
+ if (decomposedCache !== null) return decomposedCache;
4426
+ if (!updater || typeof updater.serverUpdateVerdict !== 'function') return null;
4427
+ try {
4428
+ const v = await updater.serverUpdateVerdict({ current });
4429
+ if (v && v.ok) decomposedCache = Boolean(v.decomposed);
4430
+ return decomposedCache;
4431
+ } catch {
4432
+ return null;
4433
+ }
4434
+ }
4435
+
4379
4436
  /**
4380
4437
  * `announce: false` (the default) is the background check: a network failure
4381
4438
  * is swallowed and re-tried on the backoff ladder. `announce: true` is a
@@ -4407,6 +4464,16 @@ function createNpmUpdateManager({
4407
4464
  attempts = 0;
4408
4465
  retryAt = 0;
4409
4466
  clearRetry();
4467
+ // A retired release is reported whether or not the registry found a
4468
+ // newer one — DECOMPOSED is the strongest thing the banner can say,
4469
+ // and it must not be swallowed by an 'up-to-date' registry answer.
4470
+ const decomposed = await decomposedVerdict();
4471
+ if (decomposed) {
4472
+ return set({
4473
+ status: 'decomposed', version: res.latest, error: null, reason: null,
4474
+ transient: false, attempts: 0, retryInMs: 0, decomposed: true,
4475
+ });
4476
+ }
4410
4477
  if (!updater.isNewer(res.latest, current)) {
4411
4478
  return set({
4412
4479
  status: 'up-to-date', version: res.latest, error: null, reason: null,
@@ -4972,6 +5039,66 @@ function buildAppMenu({ app, Menu, BrowserWindow, updateManager, loggedIn }) {
4972
5039
  // ---------------------------------------------------------------------------
4973
5040
 
4974
5041
  function bootstrap() {
5042
+ // ── crash forensics ──────────────────────────────────────────────────────
5043
+ // Before this block there was NO `uncaughtException`/`unhandledRejection`
5044
+ // handler anywhere in this process, so a main-process throw exited silently:
5045
+ // the window vanished, no stack reached stderr (a GUI launch discards it) and
5046
+ // nothing was written to disk. "It crashed after some time" was undiagnosable
5047
+ // by construction. These record the fatal reason to a file next to the other
5048
+ // userData state, and a renderer that dies no longer leaves a blank window.
5049
+ //
5050
+ // Deliberately best-effort and never rethrowing: a crash handler that itself
5051
+ // throws loses the very stack it was installed to keep.
5052
+ let crashLog = null;
5053
+ const electronApp = electron && electron.app;
5054
+ const BrowserWindowRef = electron && electron.BrowserWindow;
5055
+ const writeCrash = (kind, err) => {
5056
+ const detail =
5057
+ (err && (err.stack || err.message)) || (err && String(err)) || String(err);
5058
+ const line = `[${new Date().toISOString()}] ${kind}: ${detail}\n`;
5059
+ try {
5060
+ process.stderr.write(`aegis-desktop: ${line}`);
5061
+ } catch {
5062
+ /* stderr may be gone; the file is what matters */
5063
+ }
5064
+ try {
5065
+ crashLog = crashLog || path.join(electronApp.getPath('userData'), 'crash.log');
5066
+ fs.appendFileSync(crashLog, line, { mode: 0o600 });
5067
+ } catch {
5068
+ /* an unwritable profile must not turn a crash into a second crash */
5069
+ }
5070
+ return detail;
5071
+ };
5072
+ process.on('uncaughtException', (err) => {
5073
+ writeCrash('uncaughtException', err);
5074
+ // An uncaught throw in a GUI app is exactly the "it just closed" the user
5075
+ // cannot report usefully, so it still exits — but now it leaves a reason.
5076
+ process.exitCode = 1;
5077
+ if (electronApp) electronApp.exit(1);
5078
+ else process.exit(1);
5079
+ });
5080
+ process.on('unhandledRejection', (reason) => {
5081
+ // A rejected promise is survivable in this process (most of them are the
5082
+ // network paths). Recorded, not fatal — otherwise one failed fetch would
5083
+ // tear the window down.
5084
+ writeCrash('unhandledRejection', reason);
5085
+ });
5086
+ // Only meaningful under Electron; `bootstrap()` is Electron-only, but a CI
5087
+ // smoke run that reaches here with a stub `electron` must not throw on `.on`.
5088
+ if (electronApp && typeof electronApp.on === 'function') electronApp.on('render-process-gone', (_event, _contents, details) => {
5089
+ writeCrash('render-process-gone', new Error(JSON.stringify(details)));
5090
+ if (details && details.reason !== 'clean-exit') {
5091
+ try {
5092
+ const win =
5093
+ (BrowserWindowRef.getFocusedWindow && BrowserWindowRef.getFocusedWindow()) ||
5094
+ (BrowserWindowRef.getAllWindows ? BrowserWindowRef.getAllWindows()[0] : null);
5095
+ if (win && !win.isDestroyed()) win.reload();
5096
+ } catch {
5097
+ /* no window to rescue */
5098
+ }
5099
+ }
5100
+ });
5101
+
4975
5102
  // ── interlock (see lib/local/integrity.js) ───────────────────────────────
4976
5103
  // Asked first, before a window, an IPC channel or a spawn site exists. A
4977
5104
  // build whose own privileged bytes have been rewritten is not the build that
@@ -5087,6 +5214,20 @@ function bootstrap() {
5087
5214
  app.commandLine.appendSwitch('disable-gpu');
5088
5215
  app.commandLine.appendSwitch('disable-software-rasterizer');
5089
5216
  app.commandLine.appendSwitch('disable-gpu-compositing');
5217
+ // The three switches above stop the GPU process being created, but they do
5218
+ // NOT stop the persistent shader cache from being opened and written: on a
5219
+ // launch with no GPU present the cache writer starts, misses, and reports
5220
+ // through the GPU service's error path —
5221
+ //
5222
+ // ERROR:gpu/command_buffer/service/gpu_persistent_cache.cc:137]
5223
+ // Persistent cache error: 1
5224
+ //
5225
+ // — which lands on the terminal on every start. The line is emitted before
5226
+ // the `log-level=3` below is honoured, so silencing logging does not cover
5227
+ // it; the cache itself has to be turned off. This is the switch that does
5228
+ // that (`log-level` tells Chromium what to SAY, this tells it what to BUILD),
5229
+ // and with no GPU process to own the cache nothing is lost by disabling it.
5230
+ app.commandLine.appendSwitch('disable-gpu-program-cache');
5090
5231
 
5091
5232
  // Chromium asks xdg-desktop-portal for the desktop accent colour on Linux so
5092
5233
  // form controls can match the system palette. On this Cinnamon session the
@@ -5820,7 +5961,17 @@ function bootstrap() {
5820
5961
  log: (entry) => {
5821
5962
  // Visible in the main-process log, and nowhere else. An automation that
5822
5963
  // fails silently is indistinguishable from one that is switched off.
5823
- if (entry && entry.type !== 'skip') console.log('[auto-drain]', entry.type, entry.reason || entry.error || '');
5964
+ if (!entry || entry.type === 'skip') return;
5965
+ // The arm/disarm pair is lifecycle bookkeeping, not an outcome: `start()`
5966
+ // is called on every boot, so `auto-drain-armed` printed at every launch
5967
+ // as the second line of a terminal that had not asked to see anything.
5968
+ // Those two stay silent unless verbose output was requested — the same
5969
+ // condition the GPU/log-level block above uses — while `error`, `drain`,
5970
+ // `turn` and `seal` still print unconditionally, because a drain that
5971
+ // failed or a seal that landed is exactly what must not be swallowed.
5972
+ const lifecycle = entry.type === 'auto-drain-armed' || entry.type === 'auto-drain-disarmed';
5973
+ if (lifecycle && !process.env.ELECTRON_ENABLE_LOGGING) return;
5974
+ console.log('[auto-drain]', entry.type, entry.reason || entry.error || '');
5824
5975
  },
5825
5976
  });
5826
5977
 
@@ -134,7 +134,7 @@ const UNITS = Object.freeze([
134
134
  * (`tools/desktop-seal.mjs` in the source tree, `tools/obfuscate-faces.mjs`
135
135
  * after obfuscation), never by hand.
136
136
  */
137
- const SEALED = '8ddbab7decbebe04faef45acc355a85c3dd93d87edfff43a8e2e96aa1152621a';
137
+ const SEALED = '748b1a00ed6c17df08b27b27d4f90eda70b75ab0fc56ab6f50f643952748c580';
138
138
 
139
139
  /**
140
140
  * Ask the question. Never throws — a check that can break the program it is
@@ -3034,10 +3034,47 @@ function createSyncDispatch(sessions, dir, aegis, settingsDir, modelDispatch) {
3034
3034
  // never pass `settingsDir` and use one directory for everything.
3035
3035
  const autoPush = persistGate.createAutoPush({ push, dir: settingsDir || dir });
3036
3036
 
3037
+ // The sidebar needs to PAINT a list, not read transcripts. `listSessions()`
3038
+ // hands back whole session records — every message of every conversation —
3039
+ // so this account's store (1219 sessions, 11,180 messages) serialized 10.5 MB
3040
+ // across IPC on EVERY pane refresh, per row of which the pane draws a title,
3041
+ // a message count and a timestamp. `messages` was 98% of that payload. The
3042
+ // transcript is fetched per conversation by `sync.open`, which is the only
3043
+ // caller that needs bodies, so shipping them here was pure waste on the
3044
+ // window's own thread — and the cost grew with the account's history, which
3045
+ // is why the app got slower the longer it was used.
3046
+ //
3047
+ // Two fields keep the renderer honest without the bodies:
3048
+ // * `messages` becomes a COUNT — `library.js#messageCount` and
3049
+ // `sessionResultRow` already accept a number instead of an array;
3050
+ // * `firstPrompt` carries the opening user message, which is what the
3051
+ // unnamed-title fallback, the rename-seed check and the filter haystack
3052
+ // read out of `messages[0]`.
3053
+ const SIDEBAR_FIELDS = [
3054
+ 'id', 'title', 'updatedAt', 'pending', 'named', 'seq', 'cwd', 'dir',
3055
+ 'origin', 'remoteId', 'lastSyncedAt',
3056
+ ];
3057
+ function sessionListing(all) {
3058
+ const list = Array.isArray(all) ? all : [];
3059
+ return list
3060
+ .filter((s) => s && s.id)
3061
+ .map((s) => {
3062
+ const row = {};
3063
+ for (const field of SIDEBAR_FIELDS) {
3064
+ if (s[field] !== undefined) row[field] = s[field];
3065
+ }
3066
+ const messages = Array.isArray(s.messages) ? s.messages : [];
3067
+ row.messages = messages.length;
3068
+ const first = messages.find((m) => m && m.role === 'user' && m.content);
3069
+ row.firstPrompt = first ? String(first.content) : '';
3070
+ return row;
3071
+ });
3072
+ }
3073
+
3037
3074
  return {
3038
3075
  auto: () => autoPush.auto(),
3039
3076
  memoryPersistState: () => autoPush.gate(),
3040
- listSessions: () => ({ sessions: sessions.listSessions(dir) }),
3077
+ listSessions: () => ({ sessions: sessionListing(sessions.listSessions(dir)) }),
3041
3078
  // The ONE search the menu's "Search" (Cmd/Ctrl+K) runs — sessions AND
3042
3079
  // memory under a single query box.
3043
3080
  //
@@ -4264,6 +4301,10 @@ function createNpmUpdateManager({
4264
4301
  plan: null,
4265
4302
  method: null,
4266
4303
  canDownload: false,
4304
+ // A release the server has declared retired (`decomposed: true` from
4305
+ // /api/v1/version) is not a suggestion — the banner must say it even
4306
+ // when no newer version resolves and no download can be offered.
4307
+ decomposed: false,
4267
4308
  };
4268
4309
  const set = (patch) => {
4269
4310
  state = { ...state, ...patch };
@@ -4376,6 +4417,22 @@ function createNpmUpdateManager({
4376
4417
  return reason === 'unknown'; // unclassified: assume retryable, stay quiet
4377
4418
  };
4378
4419
 
4420
+ // The server is asked at most once per process for this: a retired release
4421
+ // does not un-retire, and re-asking on every 4h check is the nagging the
4422
+ // checker's once-a-day rule exists to avoid.
4423
+ let decomposedCache = null; // null = no answer yet (failures are not cached)
4424
+ async function decomposedVerdict() {
4425
+ if (decomposedCache !== null) return decomposedCache;
4426
+ if (!updater || typeof updater.serverUpdateVerdict !== 'function') return null;
4427
+ try {
4428
+ const v = await updater.serverUpdateVerdict({ current });
4429
+ if (v && v.ok) decomposedCache = Boolean(v.decomposed);
4430
+ return decomposedCache;
4431
+ } catch {
4432
+ return null;
4433
+ }
4434
+ }
4435
+
4379
4436
  /**
4380
4437
  * `announce: false` (the default) is the background check: a network failure
4381
4438
  * is swallowed and re-tried on the backoff ladder. `announce: true` is a
@@ -4407,6 +4464,16 @@ function createNpmUpdateManager({
4407
4464
  attempts = 0;
4408
4465
  retryAt = 0;
4409
4466
  clearRetry();
4467
+ // A retired release is reported whether or not the registry found a
4468
+ // newer one — DECOMPOSED is the strongest thing the banner can say,
4469
+ // and it must not be swallowed by an 'up-to-date' registry answer.
4470
+ const decomposed = await decomposedVerdict();
4471
+ if (decomposed) {
4472
+ return set({
4473
+ status: 'decomposed', version: res.latest, error: null, reason: null,
4474
+ transient: false, attempts: 0, retryInMs: 0, decomposed: true,
4475
+ });
4476
+ }
4410
4477
  if (!updater.isNewer(res.latest, current)) {
4411
4478
  return set({
4412
4479
  status: 'up-to-date', version: res.latest, error: null, reason: null,
@@ -4972,6 +5039,66 @@ function buildAppMenu({ app, Menu, BrowserWindow, updateManager, loggedIn }) {
4972
5039
  // ---------------------------------------------------------------------------
4973
5040
 
4974
5041
  function bootstrap() {
5042
+ // ── crash forensics ──────────────────────────────────────────────────────
5043
+ // Before this block there was NO `uncaughtException`/`unhandledRejection`
5044
+ // handler anywhere in this process, so a main-process throw exited silently:
5045
+ // the window vanished, no stack reached stderr (a GUI launch discards it) and
5046
+ // nothing was written to disk. "It crashed after some time" was undiagnosable
5047
+ // by construction. These record the fatal reason to a file next to the other
5048
+ // userData state, and a renderer that dies no longer leaves a blank window.
5049
+ //
5050
+ // Deliberately best-effort and never rethrowing: a crash handler that itself
5051
+ // throws loses the very stack it was installed to keep.
5052
+ let crashLog = null;
5053
+ const electronApp = electron && electron.app;
5054
+ const BrowserWindowRef = electron && electron.BrowserWindow;
5055
+ const writeCrash = (kind, err) => {
5056
+ const detail =
5057
+ (err && (err.stack || err.message)) || (err && String(err)) || String(err);
5058
+ const line = `[${new Date().toISOString()}] ${kind}: ${detail}\n`;
5059
+ try {
5060
+ process.stderr.write(`aegis-desktop: ${line}`);
5061
+ } catch {
5062
+ /* stderr may be gone; the file is what matters */
5063
+ }
5064
+ try {
5065
+ crashLog = crashLog || path.join(electronApp.getPath('userData'), 'crash.log');
5066
+ fs.appendFileSync(crashLog, line, { mode: 0o600 });
5067
+ } catch {
5068
+ /* an unwritable profile must not turn a crash into a second crash */
5069
+ }
5070
+ return detail;
5071
+ };
5072
+ process.on('uncaughtException', (err) => {
5073
+ writeCrash('uncaughtException', err);
5074
+ // An uncaught throw in a GUI app is exactly the "it just closed" the user
5075
+ // cannot report usefully, so it still exits — but now it leaves a reason.
5076
+ process.exitCode = 1;
5077
+ if (electronApp) electronApp.exit(1);
5078
+ else process.exit(1);
5079
+ });
5080
+ process.on('unhandledRejection', (reason) => {
5081
+ // A rejected promise is survivable in this process (most of them are the
5082
+ // network paths). Recorded, not fatal — otherwise one failed fetch would
5083
+ // tear the window down.
5084
+ writeCrash('unhandledRejection', reason);
5085
+ });
5086
+ // Only meaningful under Electron; `bootstrap()` is Electron-only, but a CI
5087
+ // smoke run that reaches here with a stub `electron` must not throw on `.on`.
5088
+ if (electronApp && typeof electronApp.on === 'function') electronApp.on('render-process-gone', (_event, _contents, details) => {
5089
+ writeCrash('render-process-gone', new Error(JSON.stringify(details)));
5090
+ if (details && details.reason !== 'clean-exit') {
5091
+ try {
5092
+ const win =
5093
+ (BrowserWindowRef.getFocusedWindow && BrowserWindowRef.getFocusedWindow()) ||
5094
+ (BrowserWindowRef.getAllWindows ? BrowserWindowRef.getAllWindows()[0] : null);
5095
+ if (win && !win.isDestroyed()) win.reload();
5096
+ } catch {
5097
+ /* no window to rescue */
5098
+ }
5099
+ }
5100
+ });
5101
+
4975
5102
  // ── interlock (see lib/local/integrity.js) ───────────────────────────────
4976
5103
  // Asked first, before a window, an IPC channel or a spawn site exists. A
4977
5104
  // build whose own privileged bytes have been rewritten is not the build that
@@ -5087,6 +5214,20 @@ function bootstrap() {
5087
5214
  app.commandLine.appendSwitch('disable-gpu');
5088
5215
  app.commandLine.appendSwitch('disable-software-rasterizer');
5089
5216
  app.commandLine.appendSwitch('disable-gpu-compositing');
5217
+ // The three switches above stop the GPU process being created, but they do
5218
+ // NOT stop the persistent shader cache from being opened and written: on a
5219
+ // launch with no GPU present the cache writer starts, misses, and reports
5220
+ // through the GPU service's error path —
5221
+ //
5222
+ // ERROR:gpu/command_buffer/service/gpu_persistent_cache.cc:137]
5223
+ // Persistent cache error: 1
5224
+ //
5225
+ // — which lands on the terminal on every start. The line is emitted before
5226
+ // the `log-level=3` below is honoured, so silencing logging does not cover
5227
+ // it; the cache itself has to be turned off. This is the switch that does
5228
+ // that (`log-level` tells Chromium what to SAY, this tells it what to BUILD),
5229
+ // and with no GPU process to own the cache nothing is lost by disabling it.
5230
+ app.commandLine.appendSwitch('disable-gpu-program-cache');
5090
5231
 
5091
5232
  // Chromium asks xdg-desktop-portal for the desktop accent colour on Linux so
5092
5233
  // form controls can match the system palette. On this Cinnamon session the
@@ -5820,7 +5961,17 @@ function bootstrap() {
5820
5961
  log: (entry) => {
5821
5962
  // Visible in the main-process log, and nowhere else. An automation that
5822
5963
  // fails silently is indistinguishable from one that is switched off.
5823
- if (entry && entry.type !== 'skip') console.log('[auto-drain]', entry.type, entry.reason || entry.error || '');
5964
+ if (!entry || entry.type === 'skip') return;
5965
+ // The arm/disarm pair is lifecycle bookkeeping, not an outcome: `start()`
5966
+ // is called on every boot, so `auto-drain-armed` printed at every launch
5967
+ // as the second line of a terminal that had not asked to see anything.
5968
+ // Those two stay silent unless verbose output was requested — the same
5969
+ // condition the GPU/log-level block above uses — while `error`, `drain`,
5970
+ // `turn` and `seal` still print unconditionally, because a drain that
5971
+ // failed or a seal that landed is exactly what must not be swallowed.
5972
+ const lifecycle = entry.type === 'auto-drain-armed' || entry.type === 'auto-drain-disarmed';
5973
+ if (lifecycle && !process.env.ELECTRON_ENABLE_LOGGING) return;
5974
+ console.log('[auto-drain]', entry.type, entry.reason || entry.error || '');
5824
5975
  },
5825
5976
  });
5826
5977
 
@@ -2,7 +2,7 @@
2
2
  "name": "aegis-desktop",
3
3
  "productName": "aegis one",
4
4
  "desktopName": "aegis-desktop",
5
- "version": "1.0.40",
5
+ "version": "1.0.42",
6
6
  "description": "Thin Electron host for AEGIS — a local chat UI over the shared client/aegis.js transport. Ships transport + UI only; engine logic stays server-side.",
7
7
  "author": {
8
8
  "name": "AEGIS Code",