aegisone 1.0.47 → 1.0.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # AEGISONE
2
2
 
3
- Product version: **1.0.47**
3
+ Product version: **1.0.48**
4
4
 
5
5
  One product, two faces: the terminal (`aegiscode`) and the window (`aegis-desktop`),
6
6
  reached through one command — `aegis` — and released as one version.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegisone",
3
3
  "productName": "AEGISONE",
4
- "version": "1.0.47",
4
+ "version": "1.0.48",
5
5
  "description": "AEGISONE — one product, two faces. `aegis` opens the window when there is nothing else to do and runs the terminal otherwise; `aegiscode` keeps behaving exactly as it always has.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "7.0.39",
4
+ "version": "7.0.40",
5
5
  "description": "aegiscode — the command-line version of AEGIS One. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
@@ -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));return r.length?listSessions(e).length?{adopted:!1,sessions:0,from:n,reason:"store already has sessions"}:(mutate(e,(e=>{for(const t of r)e[t.id]={...t,adoptedFrom:n,version:2},e[t.id].seq=nextSeq(e);return e.__seq=Math.max(e.__seq||0,s.__seq||0),e.version=2,null})),{adopted:!0,sessions:r.length,from:n}):{adopted:!1,sessions:0,from:n,reason:"legacy store empty"}}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=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};
@@ -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 = '018887de47c1831abc08b71f33ca8fd0563f08f7a15547b4c2130a4d6567fcd9';
137
+ const SEALED = '8ddbab7decbebe04faef45acc355a85c3dd93d87edfff43a8e2e96aa1152621a';
138
138
 
139
139
  /**
140
140
  * Ask the question. Never throws — a check that can break the program it is
@@ -5185,7 +5185,15 @@ function bootstrap() {
5185
5185
  // "AEGIS One" is the casing a short-lived build used. A user can arrive
5186
5186
  // from either, so both are candidates and neither is assumed to exist.
5187
5187
  const parentDir = path.dirname(userDataDir);
5188
- const LEGACY_NAMES = ['AEGIS Desktop', 'AEGIS One'];
5188
+ // FOUR prior names, not two. `aegis one` is the fifth name this app has
5189
+ // shipped under: "AEGIS Desktop" (the packaged identity in
5190
+ // electron-builder.yml, still frozen) is what the first installs wrote, and
5191
+ // "AEGIS One" is the casing a short-lived build used. "Electron" is what
5192
+ // an un-renamed dev/running-from-source launch wrote (`app.name` defaults
5193
+ // to Electron before the first setName), and "aegiscode-gui" is the
5194
+ // pre-rename name of the very first GUI. A user can arrive from any of
5195
+ // the four, so all are candidates and none is assumed to exist.
5196
+ const LEGACY_NAMES = ['AEGIS Desktop', 'AEGIS One', 'Electron', 'aegiscode-gui'];
5189
5197
  // Electron creates the userData directory eagerly, and a single launch of
5190
5198
  // this version before the guard was correct leaves a NON-empty root full of
5191
5199
  // Chromium profile junk (Cache/, GPUCache/, Local Storage/, Preferences,
@@ -5215,6 +5223,10 @@ function bootstrap() {
5215
5223
  };
5216
5224
  // settings.json only counts as state when it carries the account key; the
5217
5225
  // stub a pre-migration launch wrote holds nothing but __quickLauncher.
5226
+ // A key found in the CURRENT root is not state: adoption moves TOWARD the
5227
+ // current root, so a key there means the last launch already stored its
5228
+ // account (safeStorage entries are still being written there); treating it
5229
+ // as state would point the legacy scan at the wrong end.
5218
5230
  const hasAccountKey = (dir) => {
5219
5231
  try {
5220
5232
  return fs.readFileSync(path.join(dir, 'settings.json'), 'utf8').includes('"__aegis"');
@@ -5236,12 +5248,24 @@ function bootstrap() {
5236
5248
  if (['sessions.json', 'avatar', 'xp.json', 'queue.jsonl'].some((n) => names.includes(n))) return true;
5237
5249
  return hasAccountKey(dir);
5238
5250
  };
5251
+ const isCurrentRoot = (dir) =>
5252
+ (() => {
5253
+ try {
5254
+ return fs.realpathSync(dir) === fs.realpathSync(userDataDir);
5255
+ } catch {
5256
+ return false;
5257
+ }
5258
+ })();
5239
5259
  const isEmptyDir = (p) => isDir(p) && fs.readdirSync(p).length === 0;
5240
5260
 
5241
5261
  // Prefer whichever legacy root actually carries state; among two that do,
5242
- // take the larger sessions.json (the more recently used install).
5262
+ // take the larger sessions.json (the more recently used install). The
5263
+ // CURRENT root is never a candidate — a symlink (or a launch that already
5264
+ // adopted and then moved on) would otherwise make the app try to adopt
5265
+ // itself, and a root holding only the account key written by THIS build is
5266
+ // not "legacy" state to move.
5243
5267
  const legacyDir = LEGACY_NAMES.map((n) => path.join(parentDir, n))
5244
- .filter((d) => hasUserState(d))
5268
+ .filter((d) => hasUserState(d) && !isCurrentRoot(d))
5245
5269
  .sort((a, b) => sizeOf(path.join(b, 'sessions.json')) - sizeOf(path.join(a, 'sessions.json')))[0];
5246
5270
 
5247
5271
  if (legacyDir && !hasUserState(userDataDir)) {
@@ -5287,6 +5311,106 @@ function bootstrap() {
5287
5311
  app.setPath('userData', legacyDir);
5288
5312
  }
5289
5313
  }
5314
+
5315
+ // The pre-unification desktop chats live in ~/.aegiscode/native-chat-history/
5316
+ // (one JSON file per conversation, catalogued by native-chat-index.json) —
5317
+ // a store nothing ever imports. The shared session-store's adopt() merges
5318
+ // a whole legacy sessions.json, but these are individual transcripts with
5319
+ // no session ids, so they need one import of their own: any file not
5320
+ // already represented in the shared store becomes a session, id minted by
5321
+ // the transcript's own timestamp, once and idempotently. No other store
5322
+ // in the tree reads these files, so the import makes them visible rather
5323
+ // than duplicating them.
5324
+ try {
5325
+ const nativeHistoryDir = path.join(os.homedir(), '.aegiscode', 'native-chat-history');
5326
+ const isDir = (p) => {
5327
+ try {
5328
+ return fs.statSync(p).isDirectory();
5329
+ } catch {
5330
+ return false;
5331
+ }
5332
+ };
5333
+ if (isDir(nativeHistoryDir)) {
5334
+ const entries = fs
5335
+ .readdirSync(nativeHistoryDir)
5336
+ .filter((f) => f.endsWith('.json'))
5337
+ .sort();
5338
+ const existing = new Set(
5339
+ (sessionStore.listSessions(sessionStore.resolveStoreDir(null)) || [])
5340
+ .map((s) => s && s.id)
5341
+ .filter(Boolean)
5342
+ );
5343
+ let adopted = 0;
5344
+ for (const file of entries) {
5345
+ let parsed = null;
5346
+ try {
5347
+ parsed = JSON.parse(fs.readFileSync(path.join(nativeHistoryDir, file), 'utf8'));
5348
+ } catch {
5349
+ /* not JSON or not readable: not a conversation */
5350
+ }
5351
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) continue;
5352
+ const marker =
5353
+ (typeof parsed.createdAt === 'string' && parsed.createdAt) ||
5354
+ (typeof parsed.created_at === 'string' && parsed.created_at) ||
5355
+ String(parsed.timestamp || '');
5356
+ if (!marker) continue;
5357
+ // Mint the id from the transcript's own timestamp — stable across
5358
+ // launches, and one id per file (duplicate timestamps get a suffix).
5359
+ let sessionId = `native-${marker.replace(/[^0-9T:.Z+-]/g, '')}`.slice(0, 80);
5360
+ if (existing.has(sessionId)) sessionId = `${sessionId}-${file.replace(/\.json$/, '').slice(-24)}`;
5361
+ if (existing.has(sessionId)) continue;
5362
+ const messages = Array.isArray(parsed.messages)
5363
+ ? parsed.messages
5364
+ : parsed.history && Array.isArray(parsed.history.messages)
5365
+ ? parsed.history.messages
5366
+ : parsed.history && Array.isArray(parsed.history)
5367
+ ? parsed.history
5368
+ : parsed.entries && Array.isArray(parsed.entries)
5369
+ ? parsed.entries
5370
+ : [];
5371
+ const clean = messages
5372
+ .map((m) => {
5373
+ const text =
5374
+ (m && (m.content || m.text)) !== undefined
5375
+ ? m.content || m.text
5376
+ : m && typeof m.prompt === 'string'
5377
+ ? m.prompt
5378
+ : m && typeof m.reply === 'string'
5379
+ ? m.reply
5380
+ : null;
5381
+ if (text == null || text === '') return null;
5382
+ const role =
5383
+ m && (m.role === 'user' || m.role === 'assistant')
5384
+ ? m.role
5385
+ : m && typeof m.prompt === 'string'
5386
+ ? 'user'
5387
+ : m && typeof m.reply === 'string'
5388
+ ? 'assistant'
5389
+ : 'unknown';
5390
+ return { role, content: String(text) };
5391
+ })
5392
+ .filter(Boolean);
5393
+ if (!clean.length) continue;
5394
+ const title = String(parsed.title || (parsed.session && parsed.session.title) || '').trim();
5395
+ sessionStore.upsertSession(sessionStore.resolveStoreDir(null), {
5396
+ id: sessionId,
5397
+ title: title || String((clean.find((m) => m.role === 'user') || {}).content || '').slice(0, 60),
5398
+ messages: clean,
5399
+ cwd: typeof parsed.cwd === 'string' ? parsed.cwd : '',
5400
+ updatedAt:
5401
+ Date.parse(parsed.updatedAt || parsed.updated_at || parsed.createdAt || parsed.created_at || 0) ||
5402
+ Date.now(),
5403
+ origin: 'native-chat',
5404
+ pending: false,
5405
+ });
5406
+ existing.add(sessionId);
5407
+ adopted += 1;
5408
+ }
5409
+ if (adopted) console.warn(`aegis: imported ${adopted} conversation(s) from ${nativeHistoryDir}`);
5410
+ }
5411
+ } catch (nativeErr) {
5412
+ console.warn(`aegis: native-chat import skipped: ${nativeErr && nativeErr.message}`);
5413
+ }
5290
5414
  } catch (renameErr) {
5291
5415
  console.warn(`aegis: userData adoption skipped: ${renameErr && renameErr.message}`);
5292
5416
  }
@@ -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 = '018887de47c1831abc08b71f33ca8fd0563f08f7a15547b4c2130a4d6567fcd9';
137
+ const SEALED = '8ddbab7decbebe04faef45acc355a85c3dd93d87edfff43a8e2e96aa1152621a';
138
138
 
139
139
  /**
140
140
  * Ask the question. Never throws — a check that can break the program it is
@@ -5185,7 +5185,15 @@ function bootstrap() {
5185
5185
  // "AEGIS One" is the casing a short-lived build used. A user can arrive
5186
5186
  // from either, so both are candidates and neither is assumed to exist.
5187
5187
  const parentDir = path.dirname(userDataDir);
5188
- const LEGACY_NAMES = ['AEGIS Desktop', 'AEGIS One'];
5188
+ // FOUR prior names, not two. `aegis one` is the fifth name this app has
5189
+ // shipped under: "AEGIS Desktop" (the packaged identity in
5190
+ // electron-builder.yml, still frozen) is what the first installs wrote, and
5191
+ // "AEGIS One" is the casing a short-lived build used. "Electron" is what
5192
+ // an un-renamed dev/running-from-source launch wrote (`app.name` defaults
5193
+ // to Electron before the first setName), and "aegiscode-gui" is the
5194
+ // pre-rename name of the very first GUI. A user can arrive from any of
5195
+ // the four, so all are candidates and none is assumed to exist.
5196
+ const LEGACY_NAMES = ['AEGIS Desktop', 'AEGIS One', 'Electron', 'aegiscode-gui'];
5189
5197
  // Electron creates the userData directory eagerly, and a single launch of
5190
5198
  // this version before the guard was correct leaves a NON-empty root full of
5191
5199
  // Chromium profile junk (Cache/, GPUCache/, Local Storage/, Preferences,
@@ -5215,6 +5223,10 @@ function bootstrap() {
5215
5223
  };
5216
5224
  // settings.json only counts as state when it carries the account key; the
5217
5225
  // stub a pre-migration launch wrote holds nothing but __quickLauncher.
5226
+ // A key found in the CURRENT root is not state: adoption moves TOWARD the
5227
+ // current root, so a key there means the last launch already stored its
5228
+ // account (safeStorage entries are still being written there); treating it
5229
+ // as state would point the legacy scan at the wrong end.
5218
5230
  const hasAccountKey = (dir) => {
5219
5231
  try {
5220
5232
  return fs.readFileSync(path.join(dir, 'settings.json'), 'utf8').includes('"__aegis"');
@@ -5236,12 +5248,24 @@ function bootstrap() {
5236
5248
  if (['sessions.json', 'avatar', 'xp.json', 'queue.jsonl'].some((n) => names.includes(n))) return true;
5237
5249
  return hasAccountKey(dir);
5238
5250
  };
5251
+ const isCurrentRoot = (dir) =>
5252
+ (() => {
5253
+ try {
5254
+ return fs.realpathSync(dir) === fs.realpathSync(userDataDir);
5255
+ } catch {
5256
+ return false;
5257
+ }
5258
+ })();
5239
5259
  const isEmptyDir = (p) => isDir(p) && fs.readdirSync(p).length === 0;
5240
5260
 
5241
5261
  // Prefer whichever legacy root actually carries state; among two that do,
5242
- // take the larger sessions.json (the more recently used install).
5262
+ // take the larger sessions.json (the more recently used install). The
5263
+ // CURRENT root is never a candidate — a symlink (or a launch that already
5264
+ // adopted and then moved on) would otherwise make the app try to adopt
5265
+ // itself, and a root holding only the account key written by THIS build is
5266
+ // not "legacy" state to move.
5243
5267
  const legacyDir = LEGACY_NAMES.map((n) => path.join(parentDir, n))
5244
- .filter((d) => hasUserState(d))
5268
+ .filter((d) => hasUserState(d) && !isCurrentRoot(d))
5245
5269
  .sort((a, b) => sizeOf(path.join(b, 'sessions.json')) - sizeOf(path.join(a, 'sessions.json')))[0];
5246
5270
 
5247
5271
  if (legacyDir && !hasUserState(userDataDir)) {
@@ -5287,6 +5311,106 @@ function bootstrap() {
5287
5311
  app.setPath('userData', legacyDir);
5288
5312
  }
5289
5313
  }
5314
+
5315
+ // The pre-unification desktop chats live in ~/.aegiscode/native-chat-history/
5316
+ // (one JSON file per conversation, catalogued by native-chat-index.json) —
5317
+ // a store nothing ever imports. The shared session-store's adopt() merges
5318
+ // a whole legacy sessions.json, but these are individual transcripts with
5319
+ // no session ids, so they need one import of their own: any file not
5320
+ // already represented in the shared store becomes a session, id minted by
5321
+ // the transcript's own timestamp, once and idempotently. No other store
5322
+ // in the tree reads these files, so the import makes them visible rather
5323
+ // than duplicating them.
5324
+ try {
5325
+ const nativeHistoryDir = path.join(os.homedir(), '.aegiscode', 'native-chat-history');
5326
+ const isDir = (p) => {
5327
+ try {
5328
+ return fs.statSync(p).isDirectory();
5329
+ } catch {
5330
+ return false;
5331
+ }
5332
+ };
5333
+ if (isDir(nativeHistoryDir)) {
5334
+ const entries = fs
5335
+ .readdirSync(nativeHistoryDir)
5336
+ .filter((f) => f.endsWith('.json'))
5337
+ .sort();
5338
+ const existing = new Set(
5339
+ (sessionStore.listSessions(sessionStore.resolveStoreDir(null)) || [])
5340
+ .map((s) => s && s.id)
5341
+ .filter(Boolean)
5342
+ );
5343
+ let adopted = 0;
5344
+ for (const file of entries) {
5345
+ let parsed = null;
5346
+ try {
5347
+ parsed = JSON.parse(fs.readFileSync(path.join(nativeHistoryDir, file), 'utf8'));
5348
+ } catch {
5349
+ /* not JSON or not readable: not a conversation */
5350
+ }
5351
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) continue;
5352
+ const marker =
5353
+ (typeof parsed.createdAt === 'string' && parsed.createdAt) ||
5354
+ (typeof parsed.created_at === 'string' && parsed.created_at) ||
5355
+ String(parsed.timestamp || '');
5356
+ if (!marker) continue;
5357
+ // Mint the id from the transcript's own timestamp — stable across
5358
+ // launches, and one id per file (duplicate timestamps get a suffix).
5359
+ let sessionId = `native-${marker.replace(/[^0-9T:.Z+-]/g, '')}`.slice(0, 80);
5360
+ if (existing.has(sessionId)) sessionId = `${sessionId}-${file.replace(/\.json$/, '').slice(-24)}`;
5361
+ if (existing.has(sessionId)) continue;
5362
+ const messages = Array.isArray(parsed.messages)
5363
+ ? parsed.messages
5364
+ : parsed.history && Array.isArray(parsed.history.messages)
5365
+ ? parsed.history.messages
5366
+ : parsed.history && Array.isArray(parsed.history)
5367
+ ? parsed.history
5368
+ : parsed.entries && Array.isArray(parsed.entries)
5369
+ ? parsed.entries
5370
+ : [];
5371
+ const clean = messages
5372
+ .map((m) => {
5373
+ const text =
5374
+ (m && (m.content || m.text)) !== undefined
5375
+ ? m.content || m.text
5376
+ : m && typeof m.prompt === 'string'
5377
+ ? m.prompt
5378
+ : m && typeof m.reply === 'string'
5379
+ ? m.reply
5380
+ : null;
5381
+ if (text == null || text === '') return null;
5382
+ const role =
5383
+ m && (m.role === 'user' || m.role === 'assistant')
5384
+ ? m.role
5385
+ : m && typeof m.prompt === 'string'
5386
+ ? 'user'
5387
+ : m && typeof m.reply === 'string'
5388
+ ? 'assistant'
5389
+ : 'unknown';
5390
+ return { role, content: String(text) };
5391
+ })
5392
+ .filter(Boolean);
5393
+ if (!clean.length) continue;
5394
+ const title = String(parsed.title || (parsed.session && parsed.session.title) || '').trim();
5395
+ sessionStore.upsertSession(sessionStore.resolveStoreDir(null), {
5396
+ id: sessionId,
5397
+ title: title || String((clean.find((m) => m.role === 'user') || {}).content || '').slice(0, 60),
5398
+ messages: clean,
5399
+ cwd: typeof parsed.cwd === 'string' ? parsed.cwd : '',
5400
+ updatedAt:
5401
+ Date.parse(parsed.updatedAt || parsed.updated_at || parsed.createdAt || parsed.created_at || 0) ||
5402
+ Date.now(),
5403
+ origin: 'native-chat',
5404
+ pending: false,
5405
+ });
5406
+ existing.add(sessionId);
5407
+ adopted += 1;
5408
+ }
5409
+ if (adopted) console.warn(`aegis: imported ${adopted} conversation(s) from ${nativeHistoryDir}`);
5410
+ }
5411
+ } catch (nativeErr) {
5412
+ console.warn(`aegis: native-chat import skipped: ${nativeErr && nativeErr.message}`);
5413
+ }
5290
5414
  } catch (renameErr) {
5291
5415
  console.warn(`aegis: userData adoption skipped: ${renameErr && renameErr.message}`);
5292
5416
  }
@@ -2,7 +2,7 @@
2
2
  "name": "aegis-desktop",
3
3
  "productName": "aegis one",
4
4
  "desktopName": "aegis-desktop",
5
- "version": "1.0.39",
5
+ "version": "1.0.40",
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",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "7.0.39",
4
+ "version": "7.0.40",
5
5
  "description": "aegiscode — the command-line version of AEGIS One. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
@@ -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));return r.length?listSessions(e).length?{adopted:!1,sessions:0,from:n,reason:"store already has sessions"}:(mutate(e,(e=>{for(const t of r)e[t.id]={...t,adoptedFrom:n,version:2},e[t.id].seq=nextSeq(e);return e.__seq=Math.max(e.__seq||0,s.__seq||0),e.version=2,null})),{adopted:!0,sessions:r.length,from:n}):{adopted:!1,sessions:0,from:n,reason:"legacy store empty"}}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=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};
@@ -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="e0e28d90398c6ed83a8f98884f8cbff6d297e95081f4db047ba9382e914b64f9";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="string"==typeof SEALED?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="7e4cdff5b713b3a68ab50253f524a28c50df7f053ba6774e0875ef460c7cd4d0";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="string"==typeof SEALED?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:r=>{const n=s&&"function"==typeof s.capabilities?s.capabilities():null,o=r&&r.limit,a=Number.isFinite(o)?o:n&&Number.isFinite(n.recallEntries)?n.recallEntries:void 0;return normalizeMemoryReadWithFallback(e.memorySearch(r&&r.query,a),memoryIndex(t),r&&r.query,a)},memorySave:r=>saveMemoryWithQueue(e,t,r&&r.entry,s,memoryIndex(t)),memoryList:r=>normalizeMemoryReadWithFallback(e.memoryList(r&&r.limit),memoryIndex(t),"",r&&r.limit),verifyToken:t=>e.verifyToken(t&&t.token),memoryActivate:t=>e.memoryActivate(t&&t.token),memoryPull:r=>indexPulledMemory(e.memoryPull(r&&r.since),memoryIndex(t)),memorySaveBatch:t=>e.memorySaveBatch(t&&t.entries),memoryImport:r=>importForeignMemory(e,t,r,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,r){return r?e.then((e=>(r(t,e),e))):e}function registerIpc(e,t,r,n,o,s,a,i,c){const l=createIpcDispatch(t,r,n,o,a,c,i);for(const[t,r]of Object.entries(l))"chatCompletion"!==t?e.handle(`${IPC_PREFIX}${t}`,((e,t)=>r(t))):e.handle(`${IPC_PREFIX}${t}`,((e,t)=>{const n={...t||{}};if(!n.stream)return withReplyNotify(r(n),e,s);const o=e&&e.sender;return withReplyNotify(r({...n,stream:!0,onStream:e=>{o&&"function"==typeof o.send&&!o.isDestroyed()&&o.send(CHAT_DELTA_CHANNEL,taggedChunk(e,n.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 r=t&&t.name;return"string"!=typeof r?{name:e.getAccent()}:{name:e.setAccent(r)}}}}function createFontScaleDispatch(e){if(!e)throw new Error("createFontScaleDispatch requires a settings store");return{getFontScale:()=>({scale:e.getFontScale()}),setFontScale:t=>{const r=t&&t.scale;return"number"!=typeof r?{scale:e.getFontScale()}:{scale:e.setFontScale(r)}}}}function createConfirmModeDispatch(e){if(!e)throw new Error("createConfirmModeDispatch requires a settings store");return{getConfirmMode:()=>({enabled:e.getConfirmMode()}),setConfirmMode:t=>{const r=t&&t.enabled;return"boolean"!=typeof r?{enabled:e.getConfirmMode()}:{enabled:e.setConfirmMode(r)}}}}function createPermissionModeDispatch(e){if(!e)throw new Error("createPermissionModeDispatch requires a settings store");return{getPermissionMode:()=>({mode:e.getPermissionMode()}),setPermissionMode:t=>{const r=t&&t.mode;return"plan"!==r&&null!=r?{mode:e.getPermissionMode()}:{mode:e.setPermissionMode("plan"===r?"plan":null)}}}}function withAutoRoundsSwitch(e,t){const r=e.setConfirmMode;return{...e,setConfirmMode:e=>{const n=r(e);return e&&"boolean"==typeof e.enabled&&t&&"function"==typeof t.setAutoRounds&&t.setAutoRounds(!1===e.enabled),n}}}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:r=>{const n=r&&r.list,o=r&&r.rule;return"string"!=typeof n||"string"!=typeof o?t((()=>e.listRules()),{reason:"a rule needs a list and a pattern"}):t((()=>e.addRule(n,o)),{})},permRulesRemove:r=>{const n=r&&r.list,o=r&&r.rule;return"string"!=typeof n||"string"!=typeof o?t((()=>e.listRules()),{reason:"a rule needs a list and a pattern"}):t((()=>e.removeRule(n,o)),{})}}}function createCliFaceDispatch(e){const t=e||{},r=t.face||require("./lib/local/cli-face.js"),n=t.platform||require("./vendor/platform.js"),o=t.spawn||require("node:child_process").spawn,s=e=>{try{return Boolean(n.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 n=t.appInfo||{};let i;try{i=r.plan({packaged:n.packaged,resourcesPath:n.resourcesPath,appDir:n.appDir,execPath:n.execPath,nodePath:n.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:r.CLI_BIN}}if(!i||!i.ok)return{ok:!1,reason:i&&i.reason||"could not open a terminal",command:i&&i.command||r.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 createSandboxPolicyDispatch(e,t,r){if(!e)throw new Error("createSandboxPolicyDispatch requires a settings store");const n=t||{},o=(Array.isArray(n.MODES)?n.MODES:["off","read-only","workspace-write","managed"]).filter((e=>"managed"!==e)),s=r&&r.appDir,a=()=>{const t=e.getSandboxPolicy(),r=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=n.detectCached||n.detect;if("function"!=typeof t||"function"!=typeof n.describe)return null;try{const r=t({appDir:s}),o=n.describe(r,e);return{mechanism:r&&(r.mechanism||(r.path?"bwrap":null))||null,enforced:Boolean(r&&r.available)&&"off"!==e.mode,sentence:"string"==typeof o?o:null}}catch{return{mechanism:null,enforced:null,sentence:null}}})("function"==typeof n.normalize?n.normalize(t,void 0):{mode:r,network:a});e&&({sentence:i,enforced:c,mechanism:l}=e)}catch{}return{ok:!0,mode:r,network:a,modes:o,stored:!!t,sentence:i,enforced:c,mechanism:l}};return{getSandboxPolicy:()=>a(),setSandboxPolicy:t=>{const r=t&&t.mode,i=t&&t.network;if("string"!=typeof r||!o.includes(r))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:r,fileSystem:l,network:u})}catch{return a()}if("function"==typeof n.invalidateProbe)try{n.invalidateProbe(s)}catch{}return a()}}}function registerConfirmModeIpc(e,t){for(const[r,n]of Object.entries(t))e.handle(`${IPC_PREFIX}${r}`,((e,t)=>n(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 r=e&&"object"==typeof e?e:{};return t.record(r.event,{campaign:r.campaign,surface:r.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[r,n]of Object.entries(t))e.handle(`${IPC_PREFIX}${r}`,((e,t)=>n(t)));return t}function registerTelemetryIpc(e,t){for(const[r,n]of Object.entries(t))e.handle(`${IPC_PREFIX}${r}`,((e,t)=>n(t)));return t}function safeExportBasename(e){return(e&&(e.title||e.id)||"session").replace(/[^\w.-]+/g,"_").slice(0,80)||"session"}function createExportDispatch(e,t,r,n){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 r({defaultPath:`${safeExportBasename(i)}.${l}`,filters:u});if(!d||d.canceled||!d.filePath)return{ok:!1,canceled:!0};try{await n(d.filePath,c)}catch(e){return{ok:!1,reason:errorText(e)}}return{ok:!0,filePath:d.filePath}}}}function registerExportIpc(e,t,r,n,o){const s=createExportDispatch(t,r,n,o);for(const[t,r]of Object.entries(s))e.handle(`${IPC_PREFIX}${t}`,((e,t)=>r(t)));return s}function createQuickLauncherDispatch(e,t={}){const r=Boolean(t.isPackaged),n=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:r,...s}},setConfig:function(t){const o=e.setQuickLauncherConfig({enabled:t&&t.enabled,shortcut:t&&t.shortcut});return s=n(o)||{active:!1,reason:null},{...o,packaged:r,...s}},pushToMain:(e,t)=>o(e,t)}}function registerQuickLauncherIpc(e,t){for(const[r,n]of Object.entries(t))"pushToMain"!==r?e.handle(`${QUICK_PREFIX}${r}`,((e,t)=>n(t))):e.handle(`${QUICK_PREFIX}${r}`,((e,t)=>n(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:r,dir:n,sessionsDir:o}={}){const s=n||resolveUserDataDir(t),a=createSettingsStore({dir:s,safeStorage:r}),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:a.getSandboxPolicy(),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:"",r=e&&"string"==typeof e.cwd?e.cwd:"";if(!t||!r||!path.isAbsolute(r))return null;const n=fs.realpathSync(r),o=fs.realpathSync(path.resolve(n,t)),s=path.relative(n,o);if(""===s||s.startsWith("..")||path.isAbsolute(s))return null;const a=fs.statSync(o);if(!a.isFile())return null;if(a.size<=PREVIEW_READ_MAX_BYTES)return{text:fs.readFileSync(o,"utf8"),truncated:!1};const i=fs.openSync(o,"r");try{const e=Buffer.alloc(PREVIEW_READ_MAX_BYTES),t=fs.readSync(i,e,0,PREVIEW_READ_MAX_BYTES,0);let r=e.toString("utf8",0,t);const n=r.lastIndexOf("\n");return n>0&&(r=r.slice(0,n+1)),{text:r,truncated:!0}}finally{fs.closeSync(i)}}catch{return null}}const attachmentsModule=require("./lib/local/attachments.js");function nativeImageResizer(e,t){try{const{nativeImage:r}=require("electron");if(!r)return null;const n=r.createFromBuffer(e);if(!n||n.isEmpty())return null;const o=n.getSize(),s=Math.max(o.width,o.height),a=s>1568?n.resize({width:Math.round(1568*o.width/s)}):n,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 r=e&&"string"==typeof e.path?e.path.trim():"";if(!r)return{ok:!1,reason:"no path"};if(!path.isAbsolute(r))return{ok:!1,reason:"not an absolute path"};let n,o,s;try{n=fs.realpathSync(r),o=fs.statSync(n)}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(n)}catch{return{ok:!1,reason:"unreadable"}}const a=attachmentsModule.sniff(s),i={path:n,name:path.basename(n),size:o.size,mime:a.mime,kind:a.kind};if("image"===a.kind){let{mime:e}=a,r=s,n=!1;if(r.length>attachmentsModule.MAX_IMAGE_BYTES&&"function"==typeof t){const o=t(s,e);o&&o.buffer&&o.buffer.length<r.length&&(r=o.buffer,e=o.mime,n=!0)}const o=attachmentsModule.toDataUrl(r,e);return o?{ok:!0,attachment:{...i,kind:"image",mime:e,size:r.length,dataUrl:o,scaled:n,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:r}={}){const n=new Map;let o,s=autoRoundsDefault(t),a=!1;const i=()=>{const t=r||e&&e.settings||null,n=e=>"boolean"==typeof e?e:void 0;let i;try{if(t&&"function"==typeof t.confirmModeState){const e=t.confirmModeState();i=n(e&&e.enabled)}void 0===i&&t&&"function"==typeof t.getConfirmMode&&(i=n(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:r=>{const o=r&&r.onStream;if("function"!=typeof o)return e.chat(r,o);const s=r&&r.sessionId||"";return e.chat(r,(r=>{if(r&&r.rounds&&r.rounds.id&&i()){const a=autoContinuePlan({on:!0,used:n.get(s)||0,limit:autoContinueLimit(t)});if(n.set(s,a.used),a.auto){const t="function"==typeof e.respondRoundsAsk?e.respondRoundsAsk(r.rounds.id,!0):{ok:!1};if(t&&t.ok){const e=Number(r.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(r)}))},"settings.get":()=>e.settings.list().filter((e=>!(e&&isReservedNamespace(e.provider)))),"settings.set":t=>e.settings.set(t&&t.provider,{baseURL:t&&t.baseURL,key:t&&t.key}),"settings.remove":t=>e.settings.remove(t&&t.provider),"userModels.get":()=>e.userModels(),"userModels.add":t=>e.addUserModel(t&&t.provider,t&&t.model),"userModels.remove":t=>e.removeUserModel(t&&t.provider,t&&t.model),"userModels.discover":t=>e.discoverModels(t&&t.provider),"userModels.addAll":t=>e.addUserModels(t&&t.provider,t&&t.ids),"userModels.canDiscover":t=>Boolean(e.canDiscoverModels(t&&t.provider)),"userModels.discoverable":()=>e.discoverableProviders(),"memoryPersist.get":()=>e.settings.memoryPersistState(),"memoryPersist.set":t=>e.settings.setMemoryPersist(Boolean(t&&t.enabled)),cancel:t=>e.cancel(t&&t.sessionId),respondApproval:t=>e.respondApproval(t&&t.approvalId,t&&t.decision),respondRoundsAsk:t=>"function"==typeof e.respondRoundsAsk?e.respondRoundsAsk(t&&t.roundsAskId,t&&t.decision):{ok:!1},clearApprovals:t=>e.clearSessionApprovals(t&&t.sessionId),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,r,n,o){let s=null;function a(){return Boolean(r&&r.apiKey)}async function i(){const n=e.listPending(t);if(!a())return{ok:!1,queued:n.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 n=[];let o=0,s=null;for(let a=0;a<e.length;a+=1)try{await r.memorySave(e[a]),o+=1;const n=memoryIndex(t);if(n)try{n.upsert(e[a])}catch{}}catch(t){const r=upgradeInfo(t);if(r){s=r,n.push(...e.slice(a));break}n.push(e[a])}return memoryQueue.save(t,n),{flushed:o,remaining:n.length,upgrade:s}}();if(!n.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 n)try{const n=await r.conversationSyncPush({session_id:o.id,title:o.title,messages:o.messages}),s=n&&(n.session_id||n.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:n||t});return{auto:()=>c.auto(),memoryPersistState:()=>c.gate(),listSessions:()=>({sessions:e.listSessions(t)}),searchSessions:r=>{const n=r&&"string"==typeof r.query?r.query:"",o=Number.isInteger(r&&r.limit)?r.limit:50,s=Math.max(1,o),a=e.listSessions(t)||[],i=sessionSearch.rankSessions(n,a).slice(0,s);let c=[],l=0,u="ok";try{const e=memoryIndex(t);if(e){const t=e.search(n,{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:n,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(n,e)})))}},open:r=>e.getSession(t,r&&r.sessionId),save:r=>e.upsertSession(t,r||{}),append:r=>e.appendMessage(t,r&&r.sessionId,r&&r.message),delete:r=>e.deleteSession(t,r&&r.sessionId),rename:r=>e.renameSession(t,r&&r.sessionId,r&&r.title),nameSession:async r=>{const n=r&&r.sessionId,s=r&&r.prompt;if(!n||!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:r&&r.class||"model",model:r&&r.model,prompt:e,system:t.system,maxTokens:64,sessionId:`${n}: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,n,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 n=await r.conversationSyncPull(),o=e.mergeRemoteSessions(t,n&&n.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 r="function"==typeof t.now?t.now:()=>Date.now(),n=Number(t.baseMs)>0?Number(t.baseMs):HEARTBEAT_RETRY_BASE_MS,o=Number(t.maxMs)>0?Number(t.maxMs):HEARTBEAT_RETRY_MAX_MS;let s=0,a=0,i=null,c=!1;function l(e){s+=1;const t=Math.min(o,n*2**Math.max(0,s-1));return i=e||"push failed",a=r()+t,{attempted:!0,ok:!1,error:i,failures:s,retryInMs:t}}return{run:async function(){const t=r();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=r();return{failures:s,lastError:i,retryInMs:s>0&&a>e?a-e:0}},recordFailure:e=>l(errorText(e))}}function registerModelIpc(e,t,r,n,o,s,a){const i=createModelDispatch(t),c=createSyncDispatch(sessionStore,r,n,a,i),l=createHeartbeatRetry((()=>c.push()),s);function u(){const e=l.run();e&&"function"==typeof e.catch&&e.catch((e=>l.recordFailure(e)))}for(const[t,r]of Object.entries(i))"chat"!==t?"listModels"!==t?e.handle(`${MODEL_PREFIX}${t}`,((e,t)=>r(t))):e.handle(`${MODEL_PREFIX}${t}`,((e,t)=>(u(),r(t)))):e.handle(`${MODEL_PREFIX}${t}`,((e,t)=>{const n={...t||{}},s=!0===n.bestEffort;delete n.bestEffort;const a="low"===n.effort||"medium"===n.effort||"max"===n.effort?n.effort:"high";n.effort=a;const i=e&&e.sender,c=n.class||"model",l=r({...n,onStream:e=>{i&&"function"==typeof i.send&&!i.isDestroyed()&&i.send(CHAT_DELTA_CHANNEL,taggedChunk(e,n.sessionId))}});return s?l.then((t=>(o&&o(e,t),t)),(e=>{const t=e&&"number"==typeof e.status?e.status:0,r=e&&e.code||"";return backgroundLaneLogs()&&console.warn(`[model] background ${c} turn produced no answer: ${errorText(e)}${t?` (status ${t})`:""}${r?` [${r}]`:""}`),{bestEffortFailed:!0,status:t,code:r||void 0,message:errorText(e),choices:[{message:{content:""}}]}})):withReplyNotify(l,e,o).catch((e=>{if(!isAbortShapedError(e))throw e;return console.warn(`[model] ${c} turn stopped before it finished: ${errorText(e)} [ABORT_ERR]`),abortedTurnPayload(e)}))}));e.on(`${MODEL_PREFIX}readTextFile`,((e,t)=>{e.returnValue=readTextFileForPreview(t)})),e.handle(`${IPC_PREFIX}attachments:ingest`,(async(e,t)=>ingestAttachment(t)));for(const[t,r]of Object.entries(c))"status"!==t?e.handle(`${SYNC_PREFIX}${t}`,((e,t)=>r(t))):e.handle(`${SYNC_PREFIX}${t}`,((e,t)=>{u();const n=r(t);return n&&"object"==typeof n?{...n,retry:l.state()}:n}));return{modelDispatch:i,syncDispatch:c,heartbeat:l}}function createQueueEngine(e,t){return createLocalEngine({aegis:e,settings:t,getConfirmMode:()=>!1})}function queueEngineWithDeniedApprovals(e){return e&&"function"==typeof e.chat?{...e,chat:(t,r)=>e.chat(t,(t=>{(t=>{const r=t&&t.approval;if(r&&r.id&&"function"==typeof e.respondApproval)try{e.respondApproval(r.id,"deny")}catch{}})(t),(t=>{const r=t&&t.rounds;if(r&&r.id&&"function"==typeof e.respondRoundsAsk)try{e.respondRoundsAsk(r.id,!1)}catch{}})(t),"function"==typeof r&&r(t)}))}:e}function isExistingDir(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function clampInt(e,t,r){const n=Number(e);return!Number.isInteger(n)||n<t||n>r?null:n}function createQueueDispatch({engine:e,env:t=process.env,queue:r=queueModule,autonomous:n=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=n.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=r.loadQueue(t);return{ok:!0,items:e,pending:r.pendingCount(e),running:e.find((e=>e&&"running"===e.status))||null,draining:c,stopping:i,defaultCwd:process.cwd(),defaultModel:n.resolveModel({env:t}),queueFile:r.queuePath(t),runs:r.readRuns(t,{limit:20}),entitlement:o.current()}}const d=e=>(e||[]).map((e=>({id:e.id,ok:Boolean(e.ok),error:e.error||null})));return{enqueue:async e=>{await o.refresh();const s=o.gateFanout({workers:clampInt(e&&e.workers,1,QUEUE_MAX_WORKERS),fanout:Boolean(e&&!0===e.fanout)});if(!s.ok)return{...s,...u()};const{opts:a,error:i}=function(e){const t=e||{},r=String(null==t.task?"":t.task).trim();if(!r)return{error:"a queued task needs text"};if(r.length>QUEUE_MAX_TASK_CHARS)return{error:`task text is too long (${r.length} > ${QUEUE_MAX_TASK_CHARS} chars)`};const o=String(null==t.cwd?"":t.cwd).trim()||process.cwd();if(!path.isAbsolute(o))return{error:"the working directory must be an absolute path"};if(!isExistingDir(o))return{error:`not a directory: ${o}`};const s=n.normalizeClass(t.class),a=String(null==t.model?"":t.model).trim().slice(0,120)||null,i=n.modelRefusal(a,s);if(i)return{error:i};const c=String(null==t.effort?"":t.effort).trim().toLowerCase();return{opts:{task:r,cwd:o,class:s,model:a,effort:QUEUE_EFFORTS.has(c)?c:null,workers:clampInt(t.workers,1,QUEUE_MAX_WORKERS),maxRounds:clampInt(t.maxRounds,1,QUEUE_MAX_ROUNDS),singlePass:!(!0===t.fanout||!0===t.autonomous),commit:Boolean(t.commit),source:"desktop"}}}(e);return i?{ok:!1,reason:i,...u()}:{ok:!0,item:r.addTask(t,a),...u()}},list:()=>u(),entitlement:async e=>(await o.refresh({force:Boolean(e&&!0===e.force)}),{ok:!0,...u()}),clear:e=>({...r.clearQueue(t,{all:Boolean(e&&e.all)}),ok:!0,...u()}),retry:e=>{const n=e&&e.id,o=r.retryTask(t,n);return o?{ok:!0,item:o,...u()}:{ok:!1,reason:`no task #${n}`,...u()}},remove:e=>{const n=e&&e.id,o=r.loadQueue(t),s=r.findTask(o,n);return s?"running"===s.status?{ok:!1,reason:`task #${s.id} is running — stop the drain first`,...u()}:(r.saveQueue(t,o.filter((e=>Number(e&&e.id)!==Number(s.id)))),{ok:!0,removed:s.id,...u()}):{ok:!1,reason:`no task #${n}`,...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 r=await l.proceed({max:1});if(r.locked){t={ok:!1,locked:!0,holder:r.holder,ran:d(e)};break}if(!r.ran.length){t={ok:!0,stopped:i,ran:d(e)};break}if(e.push(...r.ran),i){t={ok:!0,stopped:!0,ran:d(e)};break}}}catch(r){t={ok:!1,reason:errorText(r),ran:d(e)}}return c=!1,a=null,{...t,...u()}}(),stop:e=>{i=!0;const t=e&&null!=e.id?e.id:a,r=null==t?null:l.cancel(t);return{ok:!0,wasDraining:c,cancelled:r,...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 r=t||{},n={};null!=r.enabled&&(n.enabled=Boolean(r.enabled)),null!=r.intervalMs&&(n.intervalMs=Number(r.intervalMs));try{return{ok:!0,drain:e.set(n)}}catch(e){return{ok:!1,error:errorText(e)}}},autoSetMint:e=>{const r=e||{},n={};null!=r.enabled&&(n.enabled=Boolean(r.enabled)),null!=r.publish&&(n.publish=Boolean(r.publish));try{return{ok:!0,mint:t.set(n)}}catch(e){return{ok:!1,error:errorText(e)}}},autoSealNow:async e=>{const r=e||{};null!=r.publish&&t.set({publish:Boolean(r.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:r,queue:n,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_CHANNEL,{at:Date.now()})}catch{}},d=createQueueDispatch({engine:t,env:r,queue:n,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_CHANNEL,e))}});for(const[t,r]of Object.entries(d))e.handle(`${QUEUE_PREFIX}${t}`,((e,n)=>{c=e&&e.sender||null;const o=r(n);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[r,n]of Object.entries(t))e.handle(`${AUTO_PREFIX}${r}`,((e,t)=>n(t)));return t}const UPDATE_STATUS_CHANNEL=`${IPC_PREFIX}updateStatus`,ACCOUNT_STATUS_CHANNEL=`${IPC_PREFIX}accountStatusChanged`,UPDATE_CHECK_INTERVAL_MS=144e5,UPDATE_RETRY_BACKOFF_MS=[6e4,3e5,9e5,36e5];function describeRegistryFailure(e,t,r){switch(e){case"not-found":return`${r} is not published on the npm registry (404)`;case"forbidden":return`the npm registry refused the request (${t||"auth"})`;case"malformed":return"the npm registry sent a response this app could not read";case"too-large":return"the npm registry response was too large to read";case"timeout":return"the npm registry did not respond in time";case"network":return"the npm registry could not be reached";default:return"the update check did not complete"}}function createNpmUpdateManager({onStatus:e,packaged:t=!1,now:r=(()=>Date.now()),fetchImpl:n,setTimeoutImpl:o=setTimeout,clearTimeoutImpl:s=clearTimeout,runUpgrade:a,relaunch:i}={}){const c="aegis-desktop";let l="unknown";try{l=require("./package.json").version}catch{}let u={status:"idle",version:null,error:null,channel:"npm",reason:null,transient:!1,attempts:0,retryInMs:0,command:null,plan:null,method:null,canDownload:!1};const d=t=>(u={...u,...t},e&&e(u),u);let p=null;try{p=require("../client/update.js")}catch{try{p=require("./vendor/update.js")}catch{p=null}}let m=0,f=0,h=null,g=null,y=null,E=null;function _(){h&&s(h),h=null}async function k({announce:e=!1}={}){if(!p)return d({status:"disabled",error:"update checker unavailable"});if(g)return g;g=(async()=>{const s=u.status,a=u.version;let i;d({status:"checking",error:null,reason:null,transient:!1});try{i=await async function(){if(n)return n({pkg:c});if(p&&"function"==typeof p.checkPublished){const e=await p.checkPublished({current:l,pkg:c,now:r(),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(m=0,f=0,_(),!p.isNewer(i.latest,l))return d({status:"up-to-date",version:i.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0});const e=function(){if(E)return E;const e=p&&p.detectInstallMethod;if("function"!=typeof e)return E="npm",E;try{E=e({env:process.env,argv:process.argv,pkg:c,entry:__dirname,fileExists:e=>fs.existsSync(path.resolve(__dirname,"..",e))})}catch{E="npm"}return E}(),r="function"==typeof p.updatePlan?p.updatePlan({current:l,latest:i.latest,behind:!0,channel:"npm",pkg:c,method:e}):null;return d({status:"available",version:i.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0,plan:r,method:e,command:t?`${i.latest} is published — reinstall aegis one from the installer to pick it up`:r&&r.instruction||`npm i -g ${c}@latest`,commandIsSentence:t||Boolean(r&&!r.apply),canDownload:Boolean(r&&r.apply)&&!t})}m+=1;const g=i.error||describeRegistryFailure(i.reason,i.status,c);return y=i.reason,A=i.status,("function"==typeof p.isTransientReason?p.isTransientReason(y,A):"unknown"===y)?(function(){_();const e=UPDATE_RETRY_BACKOFF_MS[Math.min(Math.max(m-1,0),UPDATE_RETRY_BACKOFF_MS.length-1)];f=r()+e,h=o((()=>{h=null,k().catch((()=>{}))}),e),h&&h.unref&&h.unref(),d({retryInMs:e})}(),d(e?{status:"error",error:g,reason:i.reason,transient:!0,attempts:m}:{status:"available"===s?"available":"unavailable",version:a,error:g,reason:i.reason,transient:!0,attempts:m})):(_(),f=0,d({status:"error",error:g,reason:i.reason,transient:!1,attempts:m,retryInMs:0}));var y,A})();try{return await g}finally{g=null}}return{status:()=>u,check:k,download:async()=>{const e=!t&&u.plan&&u.plan.apply;if(!e)return d({status:"available"===u.status?"available":u.status,command:u.plan&&u.plan.instruction||u.command,canDownload:!1});d({status:"downloading",error:null,progress:0});const r=await function(e){const t=a||((e,t)=>new Promise((r=>{execFile(e,t,{timeout:18e4,windowsHide:!0},((e,t,n)=>{if(e)return r({ok:!1,output:String(n||t||e.message||e)});r({ok:!0,output:String(t||"")})}))}))),r=!a&&p&&"function"==typeof p.installSpawn?p.installSpawn(e,{env:process.env}):null,n=r?r.command:e.command,o=r?r.args:e.args;return Promise.resolve(t(n,o)).then((e=>({ok:Boolean(e&&e.ok),output:String(e&&e.output||"")})),(e=>({ok:!1,output:errorText(e)})))}(e);return r.ok?d({status:"downloaded",version:u.version,error:null,progress:100,command:`npm i -g ${c}@latest`,canDownload:!1}):d({status:"error",transient:!1,error:r.output.trim().split("\n").slice(-3).join(" ").trim()||"the installer failed",command:`${e.command} ${e.args.join(" ")}`})},quitAndInstall:()=>{"downloaded"===u.status&&(i||(()=>{try{const{app:e}=require("electron");e.relaunch(),e.exit(0)}catch{}}))()},start:()=>{k().catch((()=>{})),y=setInterval((()=>k().catch((()=>{}))),UPDATE_CHECK_INTERVAL_MS),y.unref&&y.unref()},stop:()=>{_(),y&&clearInterval(y),y=null},retryState:()=>({attempts:m,retryAt:f,inFlight:!!g,hasTimer:!!h})}}function createUpdateManager({isPackaged:e,onStatus:t}){let r={status:"idle",version:null,error:null,canDownload:!1};return createNpmUpdateManager({onStatus:function(e){r={...r,...e},t&&t(r)},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 r=createUpdateDispatch(t);for(const[t,n]of Object.entries(r))e.handle(`${IPC_PREFIX}${t}`,((e,t)=>n(t)));return r}let resolveTargetWindow=null;function sendToAppWindow(e,t){const r="function"==typeof resolveTargetWindow?resolveTargetWindow():null,n=r&&!r.isDestroyed()?r:e.getFocusedWindow()||e.getAllWindows()[0];n&&!n.isDestroyed()&&n.webContents.send(t)}function sendDeepLinkToWindow(e,t){if(!e||e.isDestroyed()||!t)return;const r=()=>{e.isDestroyed()||e.webContents.send(DEEP_LINK_CHANNEL,t)};e.webContents.isLoadingMainFrame()?e.webContents.once("did-finish-load",r):r()}function buildAppMenu({app:e,Menu:t,BrowserWindow:r,updateManager:n,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:()=>n.check({announce:!0})},i={label:"New Chat",accelerator:"CmdOrCtrl+N",click:()=>sendToAppWindow(r,MENU_NEW_CHAT_CHANNEL)},c={label:"Search",accelerator:"CmdOrCtrl+K",click:()=>sendToAppWindow(r,MENU_SEARCH_CHANNEL)},l={label:"Command palette…",accelerator:"CmdOrCtrl+P",click:()=>sendToAppWindow(r,MENU_PALETTE_CHANNEL)},u={label:"Toggle sidebar",accelerator:"CmdOrCtrl+B",click:()=>sendToAppWindow(r,MENU_TOGGLE_SIDEBAR_CHANNEL)},d={label:"Find in conversation",accelerator:"CmdOrCtrl+F",click:()=>sendToAppWindow(r,MENU_FIND_CHANNEL)},p={label:"Go Back",accelerator:s?"Cmd+[":"Alt+Left",enabled:navState.back,click:()=>sendToAppWindow(r,MENU_GO_BACK_CHANNEL)},m={label:"Go Forward",accelerator:s?"Cmd+]":"Alt+Right",enabled:navState.forward,click:()=>sendToAppWindow(r,MENU_GO_FORWARD_CHANNEL)},f={label:"Search memory",accelerator:"CmdOrCtrl+Shift+K",visible:!1,click:()=>sendToAppWindow(r,MENU_SEARCH_MEMORY_CHANNEL)},h={label:"Credits & Licence…",click:()=>sendToAppWindow(r,MENU_CREDITS_CHANNEL)},g={label:"Source Code",click:()=>{try{require("electron").shell.openExternal(creditsLib.SOURCE_URL)}catch{}}},y={label:"Save as…",accelerator:"CmdOrCtrl+S",click:()=>sendToAppWindow(r,MENU_EXPORT_MARKDOWN_CHANNEL)},E={label:"Export Session…",click:()=>sendToAppWindow(r,MENU_EXPORT_JSON_CHANNEL)},_={label:"Authorship Panel…",click:()=>sendToAppWindow(r,MENU_FINGERPRINT_CHANNEL)},k={label:"Google Drive Backup…",enabled:Boolean(o),click:()=>sendToAppWindow(r,MENU_GOOGLE_DRIVE_CHANNEL)},A=[...s?[{label:e.getName(),submenu:[{role:"about"},a,{type:"separator"},h,g,{type:"separator"},{role:"services"},{type:"separator"},{role:"hide"},{role:"hideOthers"},{role:"unhide"},{type:"separator"},{role:"quit"}]}]:[],{label:"File",submenu:[i,{type:"separator"},y,E,{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"},_,k,{type:"separator"},{role:"reload",accelerator:"CmdOrCtrl+R"},{role:"forceReload"},{type:"separator"},{role:"toggleDevTools",accelerator:"CmdOrCtrl+Shift+I"}]},{label:"Help",submenu:[h,g,{type:"separator"},...s?[]:[{role:"about"}]]}];return t.buildFromTemplate(A)}function bootstrap(){let e=!1;try{e=require("./lib/local/integrity.js").armed()}catch{e=!0,process.env.AEGIS_REDUCED_MODE="1",process.stderr.write("aegis-desktop: reduced mode (d1) — this build is not the one that was published.\n")}if(e){try{const{app:e}=electron;e&&"function"==typeof e.quit&&e.quit()}catch{}return}const{app:t,BrowserWindow:r,ipcMain:n,safeStorage:o,shell:s,Menu:a,Notification:i,screen:c,dialog:l,globalShortcut:u}=electron;try{let e;try{e=require("./vendor/selfhost.js")}catch{e=require("../one/src/selfhost.js")}const r=e.plan({packaged:t.isPackaged,execPath:process.execPath,resourcesPath:process.resourcesPath,argv:process.argv.slice(1),invokedAs:path.basename(process.argv[1]||process.execPath)});if(r){const n=e.spawnOptions(r,process.env),o=require("node:child_process").spawnSync(n.exec,n.args,{stdio:"inherit",env:n.env}),s="number"==typeof o.status?o.status:1;return void t.exit(s)}}catch(e){t.isPackaged&&!/MODULE_NOT_FOUND/.test(String(e&&e.message))&&process.stderr.write(`aegis: terminal face hand-off failed: ${e&&e.message||e}\n`)}if(t.disableHardwareAcceleration(),t.commandLine.appendSwitch("disable-gpu"),t.commandLine.appendSwitch("disable-software-rasterizer"),t.commandLine.appendSwitch("disable-gpu-compositing"),t.commandLine.appendSwitch("disable-features","UsePortalAccentColor"),process.argv.some((e=>/^--(log-level|enable-logging)/.test(e)))||process.env.ELECTRON_ENABLE_LOGGING||t.commandLine.appendSwitch("log-level","3"),!t.requestSingleInstanceLock())return void t.quit();t.setName("aegis one");try{const e=t.getPath("userData"),r=path.dirname(e),n=["sessions.json","avatar","xp.json","queue.jsonl","memory.db","settings.json"],o=e=>{try{return fs.statSync(e).isDirectory()}catch{return!1}},s=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(!o(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=e=>o(e)&&0===fs.readdirSync(e).length,l=["AEGIS Desktop","AEGIS One"].map((e=>path.join(r,e))).filter((e=>i(e))).sort(((e,t)=>s(path.join(t,"sessions.json"))-s(path.join(e,"sessions.json"))))[0];if(l&&!i(e))try{if(!fs.existsSync(e)||c(e))fs.existsSync(e)&&fs.rmdirSync(e),fs.renameSync(l,e);else{const t=[];for(const r of n){const n=path.join(l,r),o=path.join(e,r);if(fs.existsSync(n)){if(fs.existsSync(o)){if(!("settings.json"===r&&a(l)&&!a(e)||"memory.db"===r&&s(n)>s(o)))continue;fs.rmSync(o,{recursive:!0,force:!0})}fs.renameSync(n,o),t.push(r)}}t.length&&console.warn(`aegis: adopted user state from ${l}: ${t.join(", ")}`)}}catch(r){console.warn(`aegis: could not move ${l} -> ${e} (${r&&r.message}); reading the old location instead`),t.setPath("userData",l)}}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}`)}t.setAsDefaultProtocolClient(deepLink.PROTOCOL);let d=deepLink.parseDeepLinkArgv(process.argv);t.on("open-url",((e,t)=>{e.preventDefault();const r=deepLink.parseDeepLinkUrl(t);if(!r)return;const n="function"==typeof resolveTargetWindow?resolveTargetWindow():null;n&&!n.isDestroyed()?sendDeepLinkToWindow(n,r):d=r}));const p=createClient(credentials.clientOptions()),m=resolveUserDataDir(t),{engine:f,sessionsDir:h,settingsDir:g,settings:y,avatar:E}=createEngine(p,{app:t,safeStorage:o,dir:m}),_=createAccountKey({aegis:p,credentials:credentials,persistKey:e=>y.setAegisKey(e),provision:(e,t)=>autoProvision.autoProvisionApiKey(e,t,{app:"desktop"}),describeFailure:autoProvision.provisionFailureText,onChange:e=>q(e)});let k=null;const A=createGoogleConnect({aegis:p,credentials:credentials,persistKey:e=>y.setAegisKey(e),openUrl:e=>!!isSafeExternalUrl(e)&&(s.openExternal(e),!0),googleSignIn:googleSignIn,driveConnect:driveConnectLib,driveUpload:driveUploadLib,conversationExport:conversationExportLib?{...conversationExportLib,toTranscript:e=>sessionStore.toMarkdown(e)}:null,getSession:e=>sessionStore.getSession(h,e),getAuthor:()=>{try{k||(k=createFingerprintService({dir:m,getVaultBackend:()=>y.vaultBackendConfig().backend}));const e=k.status();return e&&e.ok?e:null}catch{return null}},onAccountChange:()=>q(_.status())}),b=Boolean(p.apiKey),v=autoProvision.autoProvisionApiKey(p,credentials,{app:"desktop"}).then((e=>{if(_.recordStartup(e),!e.key&&!p.apiKey){const t=e.error&&(e.error.status||e.error.message||String(e.error))||"no key returned";console.warn(`auto-provision: no account key from register-device (${t})`)}return e}));try{const{wrapProviderKeyMirror:e}=require("./lib/provider-key-mirror.js"),t=e=>console.warn(`aegis: ${e}`);e(y,envFile,{onWarn:t}),f&&f.settings&&f.settings!==y&&e(f.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not wire the shared env-file key mirror: ${e&&e.message}`)}let S=null;const C=(e,t)=>{if(function(e){const t=e&&e.sender,n=t&&r.fromWebContents(t);if(!n||n.isDestroyed())return;if(n.isFocused()&&n.isVisible())return;if(!i||!i.isSupported())return;const o=new i({title:"aegis one",body:"Reply ready"});o.on("click",(()=>{n.isDestroyed()||(n.isMinimized()&&n.restore(),n.isVisible()||n.show(),n.focus())})),o.show()}(e),S&&"function"==typeof S.note){const e=t&&(t.model||t.modelId)||void 0;S.note({sessionId:t&&t.sessionId||null,model:e})}};registerIpc(n,p,m,(e=>{const t=y.setAegisKey(e);return e?credentials.saveApiKey(e):credentials.clearApiKey(),t}),(e=>s.openExternal(e)),C,(()=>providerRouteConfigured(f)),(()=>y.vaultBackendConfig().backend),E);const I=registerModelIpc(n,f,h,p,C,void 0,g);registerConfirmModeIpc(n,withAutoRoundsSwitch(createConfirmModeDispatch(y),I.modelDispatch)),registerConfirmModeIpc(n,createPermissionModeDispatch(y)),registerConfirmModeIpc(n,createFontScaleDispatch(y)),registerConfirmModeIpc(n,createAccentDispatch(y)),registerConfirmModeIpc(n,createVaultBackendDispatch(y)),registerConfirmModeIpc(n,createPermRulesDispatch(require("./lib/local/perm-store.js"))),registerConfirmModeIpc(n,createSandboxPolicyDispatch(y,require("./lib/local/sandbox.js"),{appDir:__dirname})),registerConfirmModeIpc(n,createCliFaceDispatch({appInfo:{packaged:t.isPackaged,resourcesPath:process.resourcesPath,appDir:__dirname,execPath:process.execPath,nodePath:process.execPath}})),registerTelemetryIpc(n,createTelemetryDispatch(createTelemetry({dir:g,enabled:telemetryEnabled(process.env,y),appVersion:(()=>{try{return"function"==typeof t.getVersion?t.getVersion():""}catch{return""}})()}))),registerCovenantIpc(n,createCovenantDispatch(covenantModule));const P=registerQueueIpc(n,{engine:createQueueEngine(p,y),aegis:p}),w=createAutoDrain({proceed:()=>P.proceed(),settings:y,queue:queueModule,env:process.env,log:e=>{e&&"skip"!==e.type&&console.log("[auto-drain]",e.type,e.reason||e.error||"")}});let R=null;S=createAutoMint({mint:e=>(R||(R=createFingerprintService({dir:m,getVaultBackend:()=>y.vaultBackendConfig().backend})),R.mint(e||{})),settings:y}),registerAutoIpc(n,createAutoDispatch({autoDrain:w,autoMint:S})),w.start(),S.start();let M=null,N=null;function T(){return N&&!N.isDestroyed()||(N=new r({width:560,height:320,show:!1,frame:!1,alwaysOnTop:!0,skipTaskbar:!0,resizable:!1,movable:!0,fullscreenable:!1,minimizable:!1,maximizable:!1,backgroundColor:"#0d1117",icon:iconForPlatform(resolveIconsDir(t.isPackaged,process.resourcesPath,__dirname),process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0}}),N.setMenuBarVisibility(!1),N.loadFile(path.join(__dirname,"renderer","quick.html")),N.webContents.on("before-input-event",((e,t)=>{"keyDown"!==t.type||"Escape"!==t.key||N.isDestroyed()||N.hide()})),N.on("blur",(()=>{!N.isDestroyed()&&N.isVisible()&&N.hide()})),N.on("closed",(()=>{N=null}))),N}function D(){const e=T();e.isVisible()?e.hide():function(){const e=T(),t=c.getCursorScreenPoint(),r=c.getAllDisplays(),n=e.getBounds(),o=quickLauncherLib.computeQuickLauncherBounds({cursor:t,displays:r,size:{width:n.width,height:n.height}});e.setBounds(o),e.show(),e.focus()}()}resolveTargetWindow=()=>{if(M&&!M.isDestroyed())return M;const e=r.getFocusedWindow();return e&&!e.isDestroyed()&&e!==N?e:r.getAllWindows().find((e=>e!==N))||null};const L=createQuickLauncherDispatch(y,{isPackaged:t.isPackaged,applyConfig:function(e){if(u.unregisterAll(),!quickLauncherLib.shouldEnableGlobalShortcut({isPackaged:t.isPackaged,enabled:e.enabled}))return{active:!1,reason:null};try{if(!u.register(e.shortcut,D)){const t=`"${e.shortcut}" could not be registered — it may already be in use by another application.`;return console.warn(`[quick-launcher] ${t}`),{active:!1,reason:t}}return{active:!0,reason:null}}catch(t){const r=errorText(t);return console.warn(`[quick-launcher] failed to register shortcut "${e.shortcut}": ${r}`),{active:!1,reason:r}}},pushToMain:function(e,t){const n=t&&t.sender&&r.fromWebContents(t.sender);n&&!n.isDestroyed()&&n.hide();const o=M&&!M.isDestroyed()?M:r.getAllWindows().find((e=>e!==n))||null;return o?(o.webContents.send(QUICK_LAUNCHER_PUSH_CHANNEL,e||{}),o.isMinimized()&&o.restore(),o.isVisible()||o.show(),o.focus(),{ok:!0}):{ok:!1,reason:"no main window is open"}}});registerQuickLauncherIpc(n,L);let U=null;t.on("will-quit",(()=>{U&&"function"==typeof U.stop&&U.stop(),closeMemoryIndex(),u.unregisterAll(),j&&"function"==typeof j.stop&&j.stop()}));let F=!1;t.on("before-quit",(e=>{!F&&f&&"function"==typeof f.unloadLocalModels&&(e.preventDefault(),Promise.resolve().then((()=>f.unloadLocalModels())).catch((()=>{})).finally((()=>{F=!0,t.quit()})))}));const x=new Set;function q(e){for(const t of x)t.isDestroyed()||t.webContents.send(ACCOUNT_STATUS_CHANNEL,e);O()}function O(){a.setApplicationMenu(buildAppMenu({app:t,Menu:a,BrowserWindow:r,updateManager:j,loggedIn:Boolean(p.apiKey)}))}const j=createUpdateManager({isPackaged:t.isPackaged,onStatus:function(e){for(const t of x)t.isDestroyed()||t.webContents.send(UPDATE_STATUS_CHANNEL,e)}});registerUpdateIpc(n,j),n.handle(`${IPC_PREFIX}accountStatus`,(()=>_.status())),n.handle(`${IPC_PREFIX}setNavState`,((e,t)=>{const r=t&&"object"==typeof t?t:{},n=Boolean(r.back),o=Boolean(r.forward);return n===navState.back&&o===navState.forward||(navState.back=n,navState.forward=o,O()),{ok:!0}})),n.handle(`${IPC_PREFIX}registerAccount`,(()=>_.registerAccount())),n.handle(`${IPC_PREFIX}driveSignIn`,(()=>A.signInWithGoogle())),n.handle(`${IPC_PREFIX}driveConnect`,(()=>A.connectDrive())),n.handle(`${IPC_PREFIX}driveStatus`,(()=>A.status())),n.handle(`${IPC_PREFIX}driveSyncMemory`,(()=>A.syncMemoryNow())),n.handle(`${IPC_PREFIX}driveBackupConversation`,((e,t)=>A.backupConversation({sessionId:t&&t.sessionId}))),registerExportIpc(n,sessionStore,h,(e=>l.showSaveDialog(r.getFocusedWindow(),e)),((e,t)=>fs.promises.writeFile(e,t,"utf8"))),n.handle(`${IPC_PREFIX}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)}}})),O();const H=pathToFileURL(path.join(__dirname,"renderer","index.html")).href;function B(){const e=windowState.load(m),n=windowState.clampToDisplay(e,c.getAllDisplays(),{width:1080,height:720}),o=resolveIconsDir(t.isPackaged,process.resourcesPath,__dirname),a=new r({...n,minWidth:720,minHeight:480,show:!0,backgroundColor:"#0d1117",title:"aegis one",titleBarStyle:"hidden",titleBarOverlay:{color:"#111114",symbolColor:"#94a2b6",height:35},icon:iconForPlatform(o,process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0,spellcheck:!0}});e&&e.isMaximized&&a.maximize(),a.webContents.setWindowOpenHandler((({url:e})=>(isSafeExternalUrl(e)&&s.openExternal(e),{action:"deny"}))),a.webContents.on("will-navigate",((e,t)=>{t!==H&&(e.preventDefault(),isSafeExternalUrl(t)&&s.openExternal(t))}));let i=null;function l(){if(a.isDestroyed())return;const e=a.isMaximized(),t=e?a.getNormalBounds():a.getBounds();windowState.save(m,{...t,isMaximized:e})}function u(){i&&clearTimeout(i),i=setTimeout(l,500)}return a.on("resize",u),a.on("move",u),a.on("close",(()=>{i&&clearTimeout(i),l()})),a.loadFile(path.join(__dirname,"renderer","index.html")),x.add(a),M=a,a.on("closed",(()=>{x.delete(a),M===a&&(M=null)})),a}t.whenReady().then((async()=>{if(!credentials.normalizeApiKey(process.env[credentials.KEY_ENV])){const e=await v,t=startupKeyOverride({mintedKey:b?"":e.key,hostKey:credentials.normalizeApiKey(y.aegisRawKey())});if(t)credentials.saveApiKey(t),p.setApiKey(t);else{const e=credentials.preferNewest(y.aegisRawKey(),y.aegisKeySavedAt());e.key&&(p.setApiKey(e.key),"shared"===e.source&&y.setAegisKey(e.key))}}try{U&&"function"==typeof U.stop&&U.stop(),U=sharedPresence.createPresence({apiKey:p.apiKey,app:"desktop",version:t.getVersion(),platform:process.platform,install:sharedFingerprint.machineFingerprint(),queueDepth:()=>{try{return queueModule.readQueue(queueModule.queuePath()).filter((e=>e&&"pending"===e.status)).length}catch{return 0}},autonomous:!1,log:(e,t)=>{"debug"!==e&&console.warn(t)}}),U.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}`),r=e(y,envFile,{onWarn:t});r.mirrored.length&&console.warn(`aegis: shared ${r.mirrored.join(", ")} key(s) with the other hosts (${envFile.envFileFor()})`),f&&f.settings&&f.settings!==y&&e(f.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not backfill the shared env-file key mirror: ${e&&e.message}`)}L.setConfig(y.quickLauncherConfig());const e=B();j.start(),d&&sendDeepLinkToWindow(e,d)})),t.on("window-all-closed",(()=>{"darwin"!==process.platform&&t.quit()})),t.on("activate",(()=>{const e=r.getAllWindows();if(0===e.length)return void B();const t=resolveTargetWindow()||e[0];t.isMinimized()&&t.restore(),t.isVisible()||t.show(),t.focus()})),t.on("second-instance",((e,t)=>{const r=resolveTargetWindow(),n=deepLink.parseDeepLinkArgv(t);if(r)r.isMinimized()&&r.restore(),r.isVisible()||r.show(),r.focus(),n&&sendDeepLinkToWindow(r,n);else{const e=B();n&&sendDeepLinkToWindow(e,n)}}))}electron&&electron.app&&bootstrap(),module.exports={memoryIndex:memoryIndex,closeMemoryIndex:closeMemoryIndex,createIpcDispatch:createIpcDispatch,registerIpc:registerIpc,providerRouteConfigured:providerRouteConfigured,IPC_PREFIX:IPC_PREFIX,MODEL_PREFIX:MODEL_PREFIX,SYNC_PREFIX:SYNC_PREFIX,watchTopupCredit:watchTopupCredit,bankAmount:bankAmount,TOPUP_POLL_MS:TOPUP_POLL_MS,TOPUP_POLL_TRIES:TOPUP_POLL_TRIES,CHAT_DELTA_CHANNEL:CHAT_DELTA_CHANNEL,MENU_NEW_CHAT_CHANNEL:MENU_NEW_CHAT_CHANNEL,MENU_SEARCH_CHANNEL:MENU_SEARCH_CHANNEL,MENU_SEARCH_MEMORY_CHANNEL:MENU_SEARCH_MEMORY_CHANNEL,MENU_CREDITS_CHANNEL:MENU_CREDITS_CHANNEL,MENU_PALETTE_CHANNEL:MENU_PALETTE_CHANNEL,MENU_TOGGLE_SIDEBAR_CHANNEL:MENU_TOGGLE_SIDEBAR_CHANNEL,MENU_EXPORT_MARKDOWN_CHANNEL:MENU_EXPORT_MARKDOWN_CHANNEL,MENU_EXPORT_JSON_CHANNEL:MENU_EXPORT_JSON_CHANNEL,MENU_FINGERPRINT_CHANNEL:MENU_FINGERPRINT_CHANNEL,MENU_GOOGLE_DRIVE_CHANNEL:MENU_GOOGLE_DRIVE_CHANNEL,DEEP_LINK_CHANNEL:DEEP_LINK_CHANNEL,UPDATE_STATUS_CHANNEL:UPDATE_STATUS_CHANNEL,UPDATE_CHECK_INTERVAL_MS:UPDATE_CHECK_INTERVAL_MS,taggedChunk:taggedChunk,maskKey:maskKey,createModelDispatch:createModelDispatch,DESKTOP_CLASSES:DESKTOP_CLASSES,readTextFileForPreview:readTextFileForPreview,PREVIEW_READ_MAX_BYTES:PREVIEW_READ_MAX_BYTES,ingestAttachment:ingestAttachment,nativeImageResizer:nativeImageResizer,createSyncDispatch:createSyncDispatch,registerModelIpc:registerModelIpc,createHeartbeatRetry:createHeartbeatRetry,describeSyncError:describeSyncError,HEARTBEAT_RETRY_BASE_MS:HEARTBEAT_RETRY_BASE_MS,HEARTBEAT_RETRY_MAX_MS:HEARTBEAT_RETRY_MAX_MS,createEngine:createEngine,resolveUserDataDir:resolveUserDataDir,importForeignMemory:importForeignMemory,importForeignSessions:importForeignSessions,isSafeExternalUrl:isSafeExternalUrl,createUpdateManager:createUpdateManager,createNpmUpdateManager:createNpmUpdateManager,createUpdateDispatch:createUpdateDispatch,describeRegistryFailure:describeRegistryFailure,UPDATE_RETRY_BACKOFF_MS:UPDATE_RETRY_BACKOFF_MS,registerUpdateIpc:registerUpdateIpc,buildAppMenu:buildAppMenu,createExportDispatch:createExportDispatch,registerExportIpc:registerExportIpc,safeExportBasename:safeExportBasename,sendDeepLinkToWindow:sendDeepLinkToWindow,QUICK_PREFIX:QUICK_PREFIX,QUICK_LAUNCHER_PUSH_CHANNEL:QUICK_LAUNCHER_PUSH_CHANNEL,createQuickLauncherDispatch:createQuickLauncherDispatch,registerQuickLauncherIpc:registerQuickLauncherIpc,createConfirmModeDispatch:createConfirmModeDispatch,createVaultBackendDispatch:createVaultBackendDispatch,createPermRulesDispatch:createPermRulesDispatch,createSandboxPolicyDispatch:createSandboxPolicyDispatch,withAutoRoundsSwitch:withAutoRoundsSwitch,createTelemetryDispatch:createTelemetryDispatch,registerTelemetryIpc:registerTelemetryIpc,createCovenantDispatch:createCovenantDispatch,registerCovenantIpc:registerCovenantIpc,registerConfirmModeIpc:registerConfirmModeIpc,QUEUE_PREFIX:QUEUE_PREFIX,QUEUE_PROGRESS_CHANNEL:QUEUE_PROGRESS_CHANNEL,QUEUE_CHANGED_CHANNEL:QUEUE_CHANGED_CHANNEL,QUEUE_MAX_TASK_CHARS:QUEUE_MAX_TASK_CHARS,QUEUE_MAX_ROUNDS:QUEUE_MAX_ROUNDS,createQueueEngine:createQueueEngine,queueEngineWithDeniedApprovals:queueEngineWithDeniedApprovals,createQueueDispatch:createQueueDispatch,registerQueueIpc:registerQueueIpc,AUTO_PREFIX:AUTO_PREFIX,createAutoDispatch:createAutoDispatch,registerAutoIpc:registerAutoIpc};
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:()=>n.check({announce:!0})},i={label:"New Chat",accelerator:"CmdOrCtrl+N",click:()=>sendToAppWindow(r,MENU_NEW_CHAT_CHANNEL)},c={label:"Search",accelerator:"CmdOrCtrl+K",click:()=>sendToAppWindow(r,MENU_SEARCH_CHANNEL)},l={label:"Command palette…",accelerator:"CmdOrCtrl+P",click:()=>sendToAppWindow(r,MENU_PALETTE_CHANNEL)},u={label:"Toggle sidebar",accelerator:"CmdOrCtrl+B",click:()=>sendToAppWindow(r,MENU_TOGGLE_SIDEBAR_CHANNEL)},d={label:"Find in conversation",accelerator:"CmdOrCtrl+F",click:()=>sendToAppWindow(r,MENU_FIND_CHANNEL)},p={label:"Go Back",accelerator:s?"Cmd+[":"Alt+Left",enabled:navState.back,click:()=>sendToAppWindow(r,MENU_GO_BACK_CHANNEL)},m={label:"Go Forward",accelerator:s?"Cmd+]":"Alt+Right",enabled:navState.forward,click:()=>sendToAppWindow(r,MENU_GO_FORWARD_CHANNEL)},f={label:"Search memory",accelerator:"CmdOrCtrl+Shift+K",visible:!1,click:()=>sendToAppWindow(r,MENU_SEARCH_MEMORY_CHANNEL)},h={label:"Credits & Licence…",click:()=>sendToAppWindow(r,MENU_CREDITS_CHANNEL)},g={label:"Source Code",click:()=>{try{require("electron").shell.openExternal(creditsLib.SOURCE_URL)}catch{}}},y={label:"Save as…",accelerator:"CmdOrCtrl+S",click:()=>sendToAppWindow(r,MENU_EXPORT_MARKDOWN_CHANNEL)},E={label:"Export Session…",click:()=>sendToAppWindow(r,MENU_EXPORT_JSON_CHANNEL)},_={label:"Authorship Panel…",click:()=>sendToAppWindow(r,MENU_FINGERPRINT_CHANNEL)},k={label:"Google Drive Backup…",enabled:Boolean(o),click:()=>sendToAppWindow(r,MENU_GOOGLE_DRIVE_CHANNEL)},A=[...s?[{label:e.getName(),submenu:[{role:"about"},a,{type:"separator"},h,g,{type:"separator"},{role:"services"},{type:"separator"},{role:"hide"},{role:"hideOthers"},{role:"unhide"},{type:"separator"},{role:"quit"}]}]:[],{label:"File",submenu:[i,{type:"separator"},y,E,{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"},_,k,{type:"separator"},{role:"reload",accelerator:"CmdOrCtrl+R"},{role:"forceReload"},{type:"separator"},{role:"toggleDevTools",accelerator:"CmdOrCtrl+Shift+I"}]},{label:"Help",submenu:[h,g,{type:"separator"},...s?[]:[{role:"about"}]]}];return t.buildFromTemplate(A)}function bootstrap(){let e=!1;try{e=require("./lib/local/integrity.js").armed()}catch{e=!0,process.env.AEGIS_REDUCED_MODE="1",process.stderr.write("aegis-desktop: reduced mode (d1) — this build is not the one that was published.\n")}if(e){try{const{app:e}=electron;e&&"function"==typeof e.quit&&e.quit()}catch{}return}const{app:t,BrowserWindow:r,ipcMain:n,safeStorage:o,shell:s,Menu:a,Notification:i,screen:c,dialog:l,globalShortcut:u}=electron;try{let e;try{e=require("./vendor/selfhost.js")}catch{e=require("../one/src/selfhost.js")}const r=e.plan({packaged:t.isPackaged,execPath:process.execPath,resourcesPath:process.resourcesPath,argv:process.argv.slice(1),invokedAs:path.basename(process.argv[1]||process.execPath)});if(r){const n=e.spawnOptions(r,process.env),o=require("node:child_process").spawnSync(n.exec,n.args,{stdio:"inherit",env:n.env}),s="number"==typeof o.status?o.status:1;return void t.exit(s)}}catch(e){t.isPackaged&&!/MODULE_NOT_FOUND/.test(String(e&&e.message))&&process.stderr.write(`aegis: terminal face hand-off failed: ${e&&e.message||e}\n`)}if(t.disableHardwareAcceleration(),t.commandLine.appendSwitch("disable-gpu"),t.commandLine.appendSwitch("disable-software-rasterizer"),t.commandLine.appendSwitch("disable-gpu-compositing"),t.commandLine.appendSwitch("disable-features","UsePortalAccentColor"),process.argv.some((e=>/^--(log-level|enable-logging)/.test(e)))||process.env.ELECTRON_ENABLE_LOGGING||t.commandLine.appendSwitch("log-level","3"),!t.requestSingleInstanceLock())return void t.quit();t.setName("aegis one");try{const e=t.getPath("userData"),r=path.dirname(e),n=["sessions.json","avatar","xp.json","queue.jsonl","memory.db","settings.json"],o=e=>{try{return fs.statSync(e).isDirectory()}catch{return!1}},s=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(!o(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=>o(e)&&0===fs.readdirSync(e).length,u=["AEGIS Desktop","AEGIS One","Electron","aegiscode-gui"].map((e=>path.join(r,e))).filter((e=>i(e)&&!c(e))).sort(((e,t)=>s(path.join(t,"sessions.json"))-s(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),o=path.join(e,r);if(fs.existsSync(n)){if(fs.existsSync(o)){if(!("settings.json"===r&&a(u)&&!a(e)||"memory.db"===r&&s(n)>s(o)))continue;fs.rmSync(o,{recursive:!0,force:!0})}fs.renameSync(n,o),t.push(r)}}t.length&&console.warn(`aegis: adopted user state from ${u}: ${t.join(", ")}`)}}catch(r){console.warn(`aegis: could not move ${u} -> ${e} (${r&&r.message}); reading the old location instead`),t.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(),r=new Set((sessionStore.listSessions(sessionStore.resolveStoreDir(null))||[]).map((e=>e&&e.id)).filter(Boolean));let n=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(r.has(a)&&(a=`${a}-${o.replace(/\.json$/,"").slice(-24)}`),r.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}),r.add(a),n+=1}n&&console.warn(`aegis: imported ${n} 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}`)}t.setAsDefaultProtocolClient(deepLink.PROTOCOL);let d=deepLink.parseDeepLinkArgv(process.argv);t.on("open-url",((e,t)=>{e.preventDefault();const r=deepLink.parseDeepLinkUrl(t);if(!r)return;const n="function"==typeof resolveTargetWindow?resolveTargetWindow():null;n&&!n.isDestroyed()?sendDeepLinkToWindow(n,r):d=r}));const p=createClient(credentials.clientOptions()),m=resolveUserDataDir(t),{engine:f,sessionsDir:h,settingsDir:g,settings:y,avatar:E}=createEngine(p,{app:t,safeStorage:o,dir:m}),_=createAccountKey({aegis:p,credentials:credentials,persistKey:e=>y.setAegisKey(e),provision:(e,t)=>autoProvision.autoProvisionApiKey(e,t,{app:"desktop"}),describeFailure:autoProvision.provisionFailureText,onChange:e=>q(e)});let k=null;const A=createGoogleConnect({aegis:p,credentials:credentials,persistKey:e=>y.setAegisKey(e),openUrl:e=>!!isSafeExternalUrl(e)&&(s.openExternal(e),!0),googleSignIn:googleSignIn,driveConnect:driveConnectLib,driveUpload:driveUploadLib,conversationExport:conversationExportLib?{...conversationExportLib,toTranscript:e=>sessionStore.toMarkdown(e)}:null,getSession:e=>sessionStore.getSession(h,e),getAuthor:()=>{try{k||(k=createFingerprintService({dir:m,getVaultBackend:()=>y.vaultBackendConfig().backend}));const e=k.status();return e&&e.ok?e:null}catch{return null}},onAccountChange:()=>q(_.status())}),S=Boolean(p.apiKey),b=autoProvision.autoProvisionApiKey(p,credentials,{app:"desktop"}).then((e=>{if(_.recordStartup(e),!e.key&&!p.apiKey){const t=e.error&&(e.error.status||e.error.message||String(e.error))||"no key returned";console.warn(`auto-provision: no account key from register-device (${t})`)}return e}));try{const{wrapProviderKeyMirror:e}=require("./lib/provider-key-mirror.js"),t=e=>console.warn(`aegis: ${e}`);e(y,envFile,{onWarn:t}),f&&f.settings&&f.settings!==y&&e(f.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not wire the shared env-file key mirror: ${e&&e.message}`)}let v=null;const C=(e,t)=>{if(function(e){const t=e&&e.sender,n=t&&r.fromWebContents(t);if(!n||n.isDestroyed())return;if(n.isFocused()&&n.isVisible())return;if(!i||!i.isSupported())return;const o=new i({title:"aegis one",body:"Reply ready"});o.on("click",(()=>{n.isDestroyed()||(n.isMinimized()&&n.restore(),n.isVisible()||n.show(),n.focus())})),o.show()}(e),v&&"function"==typeof v.note){const e=t&&(t.model||t.modelId)||void 0;v.note({sessionId:t&&t.sessionId||null,model:e})}};registerIpc(n,p,m,(e=>{const t=y.setAegisKey(e);return e?credentials.saveApiKey(e):credentials.clearApiKey(),t}),(e=>s.openExternal(e)),C,(()=>providerRouteConfigured(f)),(()=>y.vaultBackendConfig().backend),E);const I=registerModelIpc(n,f,h,p,C,void 0,g);registerConfirmModeIpc(n,withAutoRoundsSwitch(createConfirmModeDispatch(y),I.modelDispatch)),registerConfirmModeIpc(n,createPermissionModeDispatch(y)),registerConfirmModeIpc(n,createFontScaleDispatch(y)),registerConfirmModeIpc(n,createAccentDispatch(y)),registerConfirmModeIpc(n,createVaultBackendDispatch(y)),registerConfirmModeIpc(n,createPermRulesDispatch(require("./lib/local/perm-store.js"))),registerConfirmModeIpc(n,createSandboxPolicyDispatch(y,require("./lib/local/sandbox.js"),{appDir:__dirname})),registerConfirmModeIpc(n,createCliFaceDispatch({appInfo:{packaged:t.isPackaged,resourcesPath:process.resourcesPath,appDir:__dirname,execPath:process.execPath,nodePath:process.execPath}})),registerTelemetryIpc(n,createTelemetryDispatch(createTelemetry({dir:g,enabled:telemetryEnabled(process.env,y),appVersion:(()=>{try{return"function"==typeof t.getVersion?t.getVersion():""}catch{return""}})()}))),registerCovenantIpc(n,createCovenantDispatch(covenantModule));const w=registerQueueIpc(n,{engine:createQueueEngine(p,y),aegis:p}),P=createAutoDrain({proceed:()=>w.proceed(),settings:y,queue:queueModule,env:process.env,log:e=>{e&&"skip"!==e.type&&console.log("[auto-drain]",e.type,e.reason||e.error||"")}});let R=null;v=createAutoMint({mint:e=>(R||(R=createFingerprintService({dir:m,getVaultBackend:()=>y.vaultBackendConfig().backend})),R.mint(e||{})),settings:y}),registerAutoIpc(n,createAutoDispatch({autoDrain:P,autoMint:v})),P.start(),v.start();let M=null,N=null;function T(){return N&&!N.isDestroyed()||(N=new r({width:560,height:320,show:!1,frame:!1,alwaysOnTop:!0,skipTaskbar:!0,resizable:!1,movable:!0,fullscreenable:!1,minimizable:!1,maximizable:!1,backgroundColor:"#0d1117",icon:iconForPlatform(resolveIconsDir(t.isPackaged,process.resourcesPath,__dirname),process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0}}),N.setMenuBarVisibility(!1),N.loadFile(path.join(__dirname,"renderer","quick.html")),N.webContents.on("before-input-event",((e,t)=>{"keyDown"!==t.type||"Escape"!==t.key||N.isDestroyed()||N.hide()})),N.on("blur",(()=>{!N.isDestroyed()&&N.isVisible()&&N.hide()})),N.on("closed",(()=>{N=null}))),N}function D(){const e=T();e.isVisible()?e.hide():function(){const e=T(),t=c.getCursorScreenPoint(),r=c.getAllDisplays(),n=e.getBounds(),o=quickLauncherLib.computeQuickLauncherBounds({cursor:t,displays:r,size:{width:n.width,height:n.height}});e.setBounds(o),e.show(),e.focus()}()}resolveTargetWindow=()=>{if(M&&!M.isDestroyed())return M;const e=r.getFocusedWindow();return e&&!e.isDestroyed()&&e!==N?e:r.getAllWindows().find((e=>e!==N))||null};const L=createQuickLauncherDispatch(y,{isPackaged:t.isPackaged,applyConfig:function(e){if(u.unregisterAll(),!quickLauncherLib.shouldEnableGlobalShortcut({isPackaged:t.isPackaged,enabled:e.enabled}))return{active:!1,reason:null};try{if(!u.register(e.shortcut,D)){const t=`"${e.shortcut}" could not be registered — it may already be in use by another application.`;return console.warn(`[quick-launcher] ${t}`),{active:!1,reason:t}}return{active:!0,reason:null}}catch(t){const r=errorText(t);return console.warn(`[quick-launcher] failed to register shortcut "${e.shortcut}": ${r}`),{active:!1,reason:r}}},pushToMain:function(e,t){const n=t&&t.sender&&r.fromWebContents(t.sender);n&&!n.isDestroyed()&&n.hide();const o=M&&!M.isDestroyed()?M:r.getAllWindows().find((e=>e!==n))||null;return o?(o.webContents.send(QUICK_LAUNCHER_PUSH_CHANNEL,e||{}),o.isMinimized()&&o.restore(),o.isVisible()||o.show(),o.focus(),{ok:!0}):{ok:!1,reason:"no main window is open"}}});registerQuickLauncherIpc(n,L);let U=null;t.on("will-quit",(()=>{U&&"function"==typeof U.stop&&U.stop(),closeMemoryIndex(),u.unregisterAll(),j&&"function"==typeof j.stop&&j.stop()}));let F=!1;t.on("before-quit",(e=>{!F&&f&&"function"==typeof f.unloadLocalModels&&(e.preventDefault(),Promise.resolve().then((()=>f.unloadLocalModels())).catch((()=>{})).finally((()=>{F=!0,t.quit()})))}));const x=new Set;function q(e){for(const t of x)t.isDestroyed()||t.webContents.send(ACCOUNT_STATUS_CHANNEL,e);O()}function O(){a.setApplicationMenu(buildAppMenu({app:t,Menu:a,BrowserWindow:r,updateManager:j,loggedIn:Boolean(p.apiKey)}))}const j=createUpdateManager({isPackaged:t.isPackaged,onStatus:function(e){for(const t of x)t.isDestroyed()||t.webContents.send(UPDATE_STATUS_CHANNEL,e)}});registerUpdateIpc(n,j),n.handle(`${IPC_PREFIX}accountStatus`,(()=>_.status())),n.handle(`${IPC_PREFIX}setNavState`,((e,t)=>{const r=t&&"object"==typeof t?t:{},n=Boolean(r.back),o=Boolean(r.forward);return n===navState.back&&o===navState.forward||(navState.back=n,navState.forward=o,O()),{ok:!0}})),n.handle(`${IPC_PREFIX}registerAccount`,(()=>_.registerAccount())),n.handle(`${IPC_PREFIX}driveSignIn`,(()=>A.signInWithGoogle())),n.handle(`${IPC_PREFIX}driveConnect`,(()=>A.connectDrive())),n.handle(`${IPC_PREFIX}driveStatus`,(()=>A.status())),n.handle(`${IPC_PREFIX}driveSyncMemory`,(()=>A.syncMemoryNow())),n.handle(`${IPC_PREFIX}driveBackupConversation`,((e,t)=>A.backupConversation({sessionId:t&&t.sessionId}))),registerExportIpc(n,sessionStore,h,(e=>l.showSaveDialog(r.getFocusedWindow(),e)),((e,t)=>fs.promises.writeFile(e,t,"utf8"))),n.handle(`${IPC_PREFIX}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)}}})),O();const H=pathToFileURL(path.join(__dirname,"renderer","index.html")).href;function $(){const e=windowState.load(m),n=windowState.clampToDisplay(e,c.getAllDisplays(),{width:1080,height:720}),o=resolveIconsDir(t.isPackaged,process.resourcesPath,__dirname),a=new r({...n,minWidth:720,minHeight:480,show:!0,backgroundColor:"#0d1117",title:"aegis one",titleBarStyle:"hidden",titleBarOverlay:{color:"#111114",symbolColor:"#94a2b6",height:35},icon:iconForPlatform(o,process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0,spellcheck:!0}});e&&e.isMaximized&&a.maximize(),a.webContents.setWindowOpenHandler((({url:e})=>(isSafeExternalUrl(e)&&s.openExternal(e),{action:"deny"}))),a.webContents.on("will-navigate",((e,t)=>{t!==H&&(e.preventDefault(),isSafeExternalUrl(t)&&s.openExternal(t))}));let i=null;function l(){if(a.isDestroyed())return;const e=a.isMaximized(),t=e?a.getNormalBounds():a.getBounds();windowState.save(m,{...t,isMaximized:e})}function u(){i&&clearTimeout(i),i=setTimeout(l,500)}return a.on("resize",u),a.on("move",u),a.on("close",(()=>{i&&clearTimeout(i),l()})),a.loadFile(path.join(__dirname,"renderer","index.html")),x.add(a),M=a,a.on("closed",(()=>{x.delete(a),M===a&&(M=null)})),a}t.whenReady().then((async()=>{if(!credentials.normalizeApiKey(process.env[credentials.KEY_ENV])){const e=await b,t=startupKeyOverride({mintedKey:S?"":e.key,hostKey:credentials.normalizeApiKey(y.aegisRawKey())});if(t)credentials.saveApiKey(t),p.setApiKey(t);else{const e=credentials.preferNewest(y.aegisRawKey(),y.aegisKeySavedAt());e.key&&(p.setApiKey(e.key),"shared"===e.source&&y.setAegisKey(e.key))}}try{U&&"function"==typeof U.stop&&U.stop(),U=sharedPresence.createPresence({apiKey:p.apiKey,app:"desktop",version:t.getVersion(),platform:process.platform,install:sharedFingerprint.machineFingerprint(),queueDepth:()=>{try{return queueModule.readQueue(queueModule.queuePath()).filter((e=>e&&"pending"===e.status)).length}catch{return 0}},autonomous:!1,log:(e,t)=>{"debug"!==e&&console.warn(t)}}),U.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}`),r=e(y,envFile,{onWarn:t});r.mirrored.length&&console.warn(`aegis: shared ${r.mirrored.join(", ")} key(s) with the other hosts (${envFile.envFileFor()})`),f&&f.settings&&f.settings!==y&&e(f.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not backfill the shared env-file key mirror: ${e&&e.message}`)}L.setConfig(y.quickLauncherConfig());const e=$();j.start(),d&&sendDeepLinkToWindow(e,d)})),t.on("window-all-closed",(()=>{"darwin"!==process.platform&&t.quit()})),t.on("activate",(()=>{const e=r.getAllWindows();if(0===e.length)return void $();const t=resolveTargetWindow()||e[0];t.isMinimized()&&t.restore(),t.isVisible()||t.show(),t.focus()})),t.on("second-instance",((e,t)=>{const r=resolveTargetWindow(),n=deepLink.parseDeepLinkArgv(t);if(r)r.isMinimized()&&r.restore(),r.isVisible()||r.show(),r.focus(),n&&sendDeepLinkToWindow(r,n);else{const e=$();n&&sendDeepLinkToWindow(e,n)}}))}electron&&electron.app&&bootstrap(),module.exports={memoryIndex:memoryIndex,closeMemoryIndex:closeMemoryIndex,createIpcDispatch:createIpcDispatch,registerIpc:registerIpc,providerRouteConfigured:providerRouteConfigured,IPC_PREFIX:IPC_PREFIX,MODEL_PREFIX:MODEL_PREFIX,SYNC_PREFIX:SYNC_PREFIX,watchTopupCredit:watchTopupCredit,bankAmount:bankAmount,TOPUP_POLL_MS:TOPUP_POLL_MS,TOPUP_POLL_TRIES:TOPUP_POLL_TRIES,CHAT_DELTA_CHANNEL:CHAT_DELTA_CHANNEL,MENU_NEW_CHAT_CHANNEL:MENU_NEW_CHAT_CHANNEL,MENU_SEARCH_CHANNEL:MENU_SEARCH_CHANNEL,MENU_SEARCH_MEMORY_CHANNEL:MENU_SEARCH_MEMORY_CHANNEL,MENU_CREDITS_CHANNEL:MENU_CREDITS_CHANNEL,MENU_PALETTE_CHANNEL:MENU_PALETTE_CHANNEL,MENU_TOGGLE_SIDEBAR_CHANNEL:MENU_TOGGLE_SIDEBAR_CHANNEL,MENU_EXPORT_MARKDOWN_CHANNEL:MENU_EXPORT_MARKDOWN_CHANNEL,MENU_EXPORT_JSON_CHANNEL:MENU_EXPORT_JSON_CHANNEL,MENU_FINGERPRINT_CHANNEL:MENU_FINGERPRINT_CHANNEL,MENU_GOOGLE_DRIVE_CHANNEL:MENU_GOOGLE_DRIVE_CHANNEL,DEEP_LINK_CHANNEL:DEEP_LINK_CHANNEL,UPDATE_STATUS_CHANNEL:UPDATE_STATUS_CHANNEL,UPDATE_CHECK_INTERVAL_MS:UPDATE_CHECK_INTERVAL_MS,taggedChunk:taggedChunk,maskKey:maskKey,createModelDispatch:createModelDispatch,DESKTOP_CLASSES:DESKTOP_CLASSES,readTextFileForPreview:readTextFileForPreview,PREVIEW_READ_MAX_BYTES:PREVIEW_READ_MAX_BYTES,ingestAttachment:ingestAttachment,nativeImageResizer:nativeImageResizer,createSyncDispatch:createSyncDispatch,registerModelIpc:registerModelIpc,createHeartbeatRetry:createHeartbeatRetry,describeSyncError:describeSyncError,HEARTBEAT_RETRY_BASE_MS:HEARTBEAT_RETRY_BASE_MS,HEARTBEAT_RETRY_MAX_MS:HEARTBEAT_RETRY_MAX_MS,createEngine:createEngine,resolveUserDataDir:resolveUserDataDir,importForeignMemory:importForeignMemory,importForeignSessions:importForeignSessions,isSafeExternalUrl:isSafeExternalUrl,createUpdateManager:createUpdateManager,createNpmUpdateManager:createNpmUpdateManager,createUpdateDispatch:createUpdateDispatch,describeRegistryFailure:describeRegistryFailure,UPDATE_RETRY_BACKOFF_MS:UPDATE_RETRY_BACKOFF_MS,registerUpdateIpc:registerUpdateIpc,buildAppMenu:buildAppMenu,createExportDispatch:createExportDispatch,registerExportIpc:registerExportIpc,safeExportBasename:safeExportBasename,sendDeepLinkToWindow:sendDeepLinkToWindow,QUICK_PREFIX:QUICK_PREFIX,QUICK_LAUNCHER_PUSH_CHANNEL:QUICK_LAUNCHER_PUSH_CHANNEL,createQuickLauncherDispatch:createQuickLauncherDispatch,registerQuickLauncherIpc:registerQuickLauncherIpc,createConfirmModeDispatch:createConfirmModeDispatch,createVaultBackendDispatch:createVaultBackendDispatch,createPermRulesDispatch:createPermRulesDispatch,createSandboxPolicyDispatch:createSandboxPolicyDispatch,withAutoRoundsSwitch:withAutoRoundsSwitch,createTelemetryDispatch:createTelemetryDispatch,registerTelemetryIpc:registerTelemetryIpc,createCovenantDispatch:createCovenantDispatch,registerCovenantIpc:registerCovenantIpc,registerConfirmModeIpc:registerConfirmModeIpc,QUEUE_PREFIX:QUEUE_PREFIX,QUEUE_PROGRESS_CHANNEL:QUEUE_PROGRESS_CHANNEL,QUEUE_CHANGED_CHANNEL:QUEUE_CHANGED_CHANNEL,QUEUE_MAX_TASK_CHARS:QUEUE_MAX_TASK_CHARS,QUEUE_MAX_ROUNDS:QUEUE_MAX_ROUNDS,createQueueEngine:createQueueEngine,queueEngineWithDeniedApprovals:queueEngineWithDeniedApprovals,createQueueDispatch:createQueueDispatch,registerQueueIpc:registerQueueIpc,AUTO_PREFIX:AUTO_PREFIX,createAutoDispatch:createAutoDispatch,registerAutoIpc:registerAutoIpc};
@@ -1,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));return r.length?listSessions(e).length?{adopted:!1,sessions:0,from:n,reason:"store already has sessions"}:(mutate(e,(e=>{for(const t of r)e[t.id]={...t,adoptedFrom:n,version:2},e[t.id].seq=nextSeq(e);return e.__seq=Math.max(e.__seq||0,s.__seq||0),e.version=2,null})),{adopted:!0,sessions:r.length,from:n}):{adopted:!1,sessions:0,from:n,reason:"legacy store empty"}}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=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};