aegiscode 7.0.38 → 7.0.40

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "7.0.38",
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
  }