aegiscode 7.0.39 → 7.0.41
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.
|
|
4
|
+
"version": "7.0.41",
|
|
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",
|
package/src/screens.js
CHANGED
|
@@ -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{getSize:getSize,paint:paint,span:span,lineWidth:lineWidth,clip:clip,w:w}=require("./screen.js"),events=require("./events.js"),{nextKey:nextKey,KEY:KEY}=events,{C:C,BOLD:BOLD,BOLD_OFF:BOLD_OFF,GLYPH:GLYPH,THEME_TABLE:THEME_TABLE,themeOf:themeOf,themeIsLight:themeIsLight,terminalIsLight:terminalIsLight}=require("./theme.js"),{TAGLINE:TAGLINE,TAGLINE_SHORT:TAGLINE_SHORT,welcomeArtParts:welcomeArtParts}=require("./art.js"),{renderDiffPreview:renderDiffPreview}=require("./markdown.js"),render=require("./render.js"),{updateConfig:updateConfig,configExists:configExists,loadConfig:loadConfig}=require("./config.js"),{updateNotice:updateNotice,updateLine:updateLine,serverNotice:serverNotice,serverUpdateLine:serverUpdateLine}=require("./update.js"),credentials=require("./credentials.js"),{signupUrl:signupUrl,signupDisplayUrl:signupDisplayUrl}=require("./signup.js"),{createSettingsStore:createSettingsStore,isReservedNamespace:isReservedNamespace}=require("./deps.js"),VERSION=require("../package.json").version,PRODUCT="AEGIS Code",TIPS=[" Run /init to create an AEGIS.md"," Use ↑↓ to recall past prompts"," Press / for commands"," Press Tab to complete a command"," Press ? for shortcuts"],KEY_HELP=[" Add a model: /model add"," <id> <name> <model> <url>"," Set a provider key: /byok-key"," <provider> — openai, anthropic"," Set your account key: /key <key>"," Switch model: /model, or alt+p"," Reasoning effort: /effort"," All commands: press / for the list"],CONNECT_BYOK=["Your own provider key: /byok-key <provider> — works with your AEGIS key"],CONNECT_CLOUD=["AEGIS Cloud, one account key: /key — no provider signup"],CONNECT_BOTH=["Your key, your bill: /byok-key <provider> — or AEGIS Cloud, /key"],CONNECT_DESKTOP=[`AEGIS Desktop: same engine on your machine — ${signupDisplayUrl()}`];function connectRows(){const e=[],t=byokRouteNeeded(),n=cloudRouteNeeded();return t&&n?e.push(...CONNECT_BOTH):t?e.push(...CONNECT_BYOK):n&&e.push(...CONNECT_CLOUD),e.length&&e.push(...CONNECT_DESKTOP),e}function centered(e,t,n){const s=clip(String(e),Math.max(1,t)),r=Math.max(0,Math.floor((t-w(s))/2));return[span(""," ".repeat(r)),span(n,s)]}function wrapped(e,t,n,s=0){const r=String(e).split(" "),o=[];let a=[],i=0;for(const e of r)i+w(e)+1>t-4-s&&a.length?(o.push([span(""," ".repeat(s)),span(n,a.join(" "))]),a=[e],i=w(e)):(a.length&&i++,a.push(e),i+=w(e));return a.length&&o.push([span(""," ".repeat(s)),span(n,a.join(" "))]),o}function trustLines(e,t,n=0,s=process.cwd()){const r=[];r.push([span(C.gold,"─".repeat(Math.max(1,t)))]),r.push([span(C.white+BOLD,"Accessing workspace:")]),r.push([span(C.white+BOLD,clip(s,Math.max(1,t-1)))]),r.push([span("","")]);for(const e of wrapped("Quick safety check: Is this a project you created or one you trust? (Like your own code, a well-known open source project, or work from your team). If not, take a moment to review what's in this folder first.",t,C.white))r.push(e);r.push([span("","")]),r.push([span(C.white,`${PRODUCT} will be able to read, edit, and execute files here.`)]),r.push([span("","")]),r.push([span(C.white+BOLD,"Security guide")]),r.push([span("","")]);for(let e=0;e<2;e++){const t=n===e,s=t?span(C.lavender,GLYPH.cursor):span(""," "),o=span(C.gray,` ${e+1}.`),a=0===e?"Yes, I trust this folder":"No, exit";r.push([s,o,span(t?C.lavender:C.white,a)])}return r.push([span("","")]),r.push([span(C.gray,`Enter to confirm ${GLYPH.bullet} Esc to cancel`)]),r}async function showTrustCheck(e){const{cols:t}=getSize();let n=0;const s=()=>paint(trustLines(e,t,n));for(s();;){const e=await nextKey();if(e.name===KEY.UP||e.name===KEY.DOWN||e.name===KEY.TAB)n=1-n,s();else{if(e.name===KEY.ENTER)return 0===n;if(e.name===KEY.ESC||e.name===KEY.CTRL_C||e.name===KEY.CTRL_D)return!1;if("char"===e.name){const t=String(e.ch).trim();"1"===t&&(n=0,s()),"2"===t&&(n=1,s())}}}}function applyTheme(e,t){return THEME_TABLE[t]||THEME_TABLE[1],e.themeIndex=t,e.light=themeIsLight(t),t}function themePickerLines(e,t,n,s){const r=[];r.push([span(C.coral,`Welcome to ${PRODUCT} v${VERSION}`)]),r.push([span(C.white+BOLD,"Let's get started.")]),r.push([span(C.white,"Choose the text style that looks best with your terminal")]),r.push([span(C.gray,"To change this later, run /theme")]),r.push([span("","")]);for(let e=0;e<THEME_TABLE.length;e++){const t=THEME_TABLE[e],n=s===e,o=n?span(C.lavender,GLYPH.cursor):span(""," "),a=span(C.gray,`${e+1}.`),i=n?span(C.green," "+GLYPH.check):span("","");r.push([o,a,span(n?C.lavender:C.white,t.name),...t.note?[span(C.gray," "+t.note)]:[],i])}for(const n of renderDiffPreview(t,e))r.push(n);for(r.push([span(C.gray," Syntax theme: Monokai Extended (ctrl+t to disable)")]);r.length<n-1;)r.push([span("","")]);return r}async function showThemePicker(e,t=`Welcome to ${PRODUCT}`){const{cols:n,rows:s}=getSize();let r="number"==typeof e.themeIndex?e.themeIndex:terminalIsLight()?2:1;const o=()=>paint(themePickerLines(e,n,s,r));for(o();;){const t=await nextKey();if(t.name===KEY.UP)r=Math.max(0,r-1),o();else if(t.name===KEY.DOWN)r=Math.min(THEME_TABLE.length-1,r+1),o();else{if(t.name===KEY.ENTER||t.name===KEY.ESC||t.name===KEY.CTRL_C||t.name===KEY.CTRL_D)return applyTheme(e,r);if(t.name===KEY.CTRL_T)e.light=!e.light,o();else if("char"===t.name){const e=parseInt(t.ch,10);e>=1&&e<=THEME_TABLE.length&&(r=e-1,o())}}}}function welcomeLines(e,t,n,s=!0){const r=themeOf(e),o=[];o.push([span(r.gold,"━"+"─".repeat(Math.max(0,t-2))+"━")]),o.push([span("","")]);let a=null;try{const e=loadConfig(),t=updateNotice({current:VERSION,cache:e.updateCheck,save:e=>{try{updateConfig({updateCheck:e})}catch{}}});a=updateLine({current:VERSION,...t});const n=serverNotice({current:VERSION,cache:e.updateCheckServer,save:e=>{try{updateConfig({updateCheckServer:e})}catch{}}});a=serverUpdateLine(n)||a}catch{}const i=welcomeArtParts();if(t>=i.width+2){const n=Math.max(0,Math.floor((t-i.width)/2));for(const t of i.rows)o.push(wrapPlain(render.artRow(e,t,i,n)))}else o.push(centered(`${PRODUCT}`,t,r.gold+BOLD));a&&(o.push([span("","")]),o.push(centered(a,t,r.gold))),o.push([span("","")]);const c=s?`Welcome to ${PRODUCT}`:"Welcome back!";o.push(centered(c,t,r.coral+BOLD));const p=t>=w(TAGLINE)+4?TAGLINE:TAGLINE_SHORT;o.push(centered(p,t,r.gray)),o.push([span("","")]),o.push(...boxes(r,t,n-o.length-4)),o.push([span("","")]);for(const e of connectRows())o.push(...wrapped(e,t,r.white,1));for(o.push([span(r.gray,GLYPH.hint),span(r.white,' Try "write a test for <filepath>"')]);o.length<n-1;)o.push([span("","")]);return o}function boxLines(e,t,n,s){const r=Math.max(1,s-4),o=` ${clip(t,Math.max(0,s-4))} `,a=[[span(e.gray,"╭─"),span(e.gray+BOLD,o),span(e.gray,"─".repeat(Math.max(0,s-3-o.length))+"╮")]];for(const t of n){const n=clip(String(t),r);a.push([span(e.gray,"│ "),span(e.white,n+" ".repeat(Math.max(0,r-w(n)))),span(e.gray," │")])}return a.push([span(e.gray,"╰"+"─".repeat(r+2)+"╯")]),a}function boxes(e,t,n){const s=Math.floor((t-2)/2),r=TIPS.map((e=>`${GLYPH.pointer}${e}`)),o=KEY_HELP,a=`Models & keys · v${VERSION}`;if(s>=30){let t=boxLines(e,"Tips for getting started",r,s),n=boxLines(e,a,o,s);const i=Math.max(t.length,n.length),c=t=>{if(t.length>=i)return t;const n=t.slice(0,t.length-1),r=[span(e.gray,"│ "),span(""," ".repeat(Math.max(0,s-4))),span(e.gray," │")];for(;n.length<i-1;)n.push(r);return n.push(t[t.length-1]),n};t=c(t),n=c(n);const p=[];for(let e=0;e<i;e++)p.push([...t[e],span(""," ".repeat(2)),...n[e]]);return p}const i=Math.max(20,t-1);return[...boxLines(e,"Tips for getting started",r,i),...boxLines(e,a,o,i)]}function wrapPlain(e){const t=[],n=/\x1b\[[0-9;]*m/g;let s,r=0,o="";for(;null!==(s=n.exec(e));)s.index>r&&t.push(make(o,e.slice(r,s.index))),o=s[0],r=s.index+s[0].length;return r<e.length&&t.push(make(o,e.slice(r))),t}function make(e,t){const n=span(e,t);return e&&(n.s=e,n.w=w(t)),n}function providerRouteConfigured(){try{return createSettingsStore({dir:credentials.aegisHome()}).list().some((e=>{if(!e||!e.provider||isReservedNamespace(e.provider))return!1;const t="string"==typeof e.baseURL?e.baseURL.trim():"";return Boolean(e.configured||t)}))}catch{return!1}}function connectNeeded(){try{return byokRouteNeeded()||cloudRouteNeeded()}catch{return!0}}function byokRouteNeeded(){try{return!providerRouteConfigured()}catch{return!0}}function cloudRouteNeeded(){try{return!credentials.keyStatus().configured}catch{return!0}}async function showWelcome(e,t=!0){for((()=>{const{cols:n,rows:s}=getSize();paint(welcomeLines(e,n,s,t))})();;){const e=await nextKey();if(e.name===KEY.ENTER||e.name===KEY.ESC)return{exit:!1};if(e.name===KEY.CTRL_C||e.name===KEY.CTRL_D)return{exit:!0}}}const KEY_URL=signupUrl("key_screen");function keyLines(e,t,{value:n="",error:s=null,verify:r=!1}={}){const o=themeOf(e),a=[];a.push([span(o.gold,"─".repeat(Math.max(1,t)))]),a.push([span(o.white+BOLD,"Connect your AEGIS account")]),a.push([span("","")]);for(const e of wrapped("Paste an API key to use AEGIS Cloud. It is stored in your user config directory with owner-only permissions, so later launches and scripts pick it up without an export.",t,o.white))a.push(e);a.push([span("","")]);const i=" No key yet? Free one at ";return w(i)+w(KEY_URL)+2<=t?a.push([span(o.white,i),span(o.cyan,KEY_URL)]):(a.push([span(o.white," No key yet? Free one:")]),a.push([span(o.cyan,` ${KEY_URL}`)])),a.push([span("","")]),a.push([span(o.lavender,GLYPH.cursor),span(o.gray," API key: "),span(o.white,"•".repeat(String(n).length)),span(r?o.cyan:o.gray,r?" verifying…":"")]),s&&a.push([span(o.coral,` ${s}`)]),a.push([span("","")]),a.push([span(o.gray,` ${GLYPH.check} `),span(o.gray,"Enter to save"),span(o.gray," · "),span(o.gray,"Esc to skip")]),a}async function requestApiKey(e,t={}){const n=t.submit||(async()=>({ok:!0})),{cols:s}=getSize();let r="",o=null,a=!1;const i=()=>paint(keyLines(e,s,{value:r,error:o,verify:a}));for(i();;){const e=await nextKey();if(e.name===KEY.ENTER){if(!r.trim())return{skipped:!0};let e;a=!0,o=null,i();try{e=await n(r)}catch(t){e={ok:!1,message:t&&t.message||String(t)}}if(a=!1,e&&!1===e.ok){o=e.message||"that key was refused",i();continue}return{key:r,result:e}}if(e.name===KEY.ESC)return{skipped:!0};if(e.name===KEY.CTRL_C||e.name===KEY.CTRL_D)return{exit:!0};if(e.name!==KEY.BACKSPACE)if("char"!==e.name)"paste"===e.name&&e.text&&(r=(r+String(e.text)).replace(/\s+/g,""),o=null,i());else{const t=e.ch;t&&t>=" "&&(r+=t,o=null,i())}else r=r.slice(0,-1),o=null,i()}}async function runOnboarding(e,t={}){const n=t.seen||configExists,s=t.save||updateConfig,r={showTrustCheck:showTrustCheck,showThemePicker:showThemePicker,showWelcome:showWelcome,requestApiKey:(e,n)=>requestApiKey(e,{submit:t.submitKey||(async()=>({ok:!0})),...n}),...t.ui||{}},o=t.needsKey||(()=>!credentials.hasApiKey()),a=t.canPrompt||(()=>!(!process.stdin||!process.stdin.isTTY)),i={set:!1,skipped:!1};if(t.continue)return{ok:!0,firstRun:!1,themeIndex:e.themeIndex,key:{set:!1,skipped:!1}};const c=!events.isKeyStreamAttached()&&!(!process.stdin||!process.stdin.isTTY);c&&events.attachKeyStream(process.stdin);try{return await async function(){if(!n()){if(!await r.showTrustCheck(e))return{ok:!1,firstRun:!0,themeIndex:e.themeIndex,key:i};if(await r.showThemePicker(e),s({themeIndex:e.themeIndex,light:e.light}),await p())return{ok:!1,firstRun:!0,themeIndex:e.themeIndex,key:i};const t=await r.showWelcome(e,!0);return t&&t.exit?{ok:!1,firstRun:!0,themeIndex:e.themeIndex,key:i}:{ok:!0,firstRun:!0,themeIndex:e.themeIndex,key:i}}if(await p())return{ok:!1,firstRun:!1,themeIndex:e.themeIndex,key:i};const t=await r.showWelcome(e,!1);return t&&t.exit?{ok:!1,firstRun:!1,themeIndex:e.themeIndex,key:i}:{ok:!0,firstRun:!1,themeIndex:e.themeIndex,key:i}}()}finally{c&&events.detachKeyStream()}async function p(){if(!o()||!a())return!1;const t=await r.requestApiKey(e);return!(!t||!t.exit)||(t&&t.key?i.set=!0:i.skipped=!0,!1)}}module.exports={PRODUCT:PRODUCT,TIPS:TIPS,KEY_HELP:KEY_HELP,CONNECT_BYOK:CONNECT_BYOK,CONNECT_CLOUD:CONNECT_CLOUD,CONNECT_BOTH:CONNECT_BOTH,CONNECT_DESKTOP:CONNECT_DESKTOP,connectRows:connectRows,connectNeeded:connectNeeded,byokRouteNeeded:byokRouteNeeded,cloudRouteNeeded:cloudRouteNeeded,providerRouteConfigured:providerRouteConfigured,trustLines:trustLines,themePickerLines:themePickerLines,keyLines:keyLines,applyTheme:applyTheme,welcomeLines:welcomeLines,boxes:boxes,boxLines:boxLines,centered:centered,wrapped:wrapped,wrapPlain:wrapPlain,showTrustCheck:showTrustCheck,showThemePicker:showThemePicker,requestApiKey:requestApiKey,showWelcome:showWelcome,runOnboarding:runOnboarding,KEY_URL:KEY_URL};
|
|
3
|
+
"use strict";const{getSize:getSize,paint:paint,span:span,lineWidth:lineWidth,clip:clip,w:w}=require("./screen.js"),events=require("./events.js"),{nextKey:nextKey,KEY:KEY}=events,{C:C,BOLD:BOLD,BOLD_OFF:BOLD_OFF,GLYPH:GLYPH,THEME_TABLE:THEME_TABLE,themeOf:themeOf,themeIsLight:themeIsLight,terminalIsLight:terminalIsLight}=require("./theme.js"),{TAGLINE:TAGLINE,TAGLINE_SHORT:TAGLINE_SHORT,welcomeArtParts:welcomeArtParts}=require("./art.js"),{renderDiffPreview:renderDiffPreview}=require("./markdown.js"),render=require("./render.js"),{updateConfig:updateConfig,configExists:configExists,loadConfig:loadConfig}=require("./config.js"),{updateNotice:updateNotice,updateLine:updateLine,serverNotice:serverNotice,serverUpdateLine:serverUpdateLine,decomposedVersion:decomposedVersion,decomposedUpdateLine:decomposedUpdateLine}=require("./update.js"),credentials=require("./credentials.js"),{signupUrl:signupUrl,signupDisplayUrl:signupDisplayUrl}=require("./signup.js"),{createSettingsStore:createSettingsStore,isReservedNamespace:isReservedNamespace}=require("./deps.js"),VERSION=require("../package.json").version,PRODUCT="AEGIS Code",TIPS=[" Run /init to create an AEGIS.md"," Use ↑↓ to recall past prompts"," Press / for commands"," Press Tab to complete a command"," Press ? for shortcuts"],KEY_HELP=[" Add a model: /model add"," <id> <name> <model> <url>"," Set a provider key: /byok-key"," <provider> — openai, anthropic"," Set your account key: /key <key>"," Switch model: /model, or alt+p"," Reasoning effort: /effort"," All commands: press / for the list"],CONNECT_BYOK=["Your own provider key: /byok-key <provider> — works with your AEGIS key"],CONNECT_CLOUD=["AEGIS Cloud, one account key: /key — no provider signup"],CONNECT_BOTH=["Your key, your bill: /byok-key <provider> — or AEGIS Cloud, /key"],CONNECT_DESKTOP=[`AEGIS Desktop: same engine on your machine — ${signupDisplayUrl()}`];function connectRows(){const e=[],t=byokRouteNeeded(),n=cloudRouteNeeded();return t&&n?e.push(...CONNECT_BOTH):t?e.push(...CONNECT_BYOK):n&&e.push(...CONNECT_CLOUD),e.length&&e.push(...CONNECT_DESKTOP),e}function centered(e,t,n){const s=clip(String(e),Math.max(1,t)),r=Math.max(0,Math.floor((t-w(s))/2));return[span(""," ".repeat(r)),span(n,s)]}function wrapped(e,t,n,s=0){const r=String(e).split(" "),o=[];let a=[],i=0;for(const e of r)i+w(e)+1>t-4-s&&a.length?(o.push([span(""," ".repeat(s)),span(n,a.join(" "))]),a=[e],i=w(e)):(a.length&&i++,a.push(e),i+=w(e));return a.length&&o.push([span(""," ".repeat(s)),span(n,a.join(" "))]),o}function trustLines(e,t,n=0,s=process.cwd()){const r=[];r.push([span(C.gold,"─".repeat(Math.max(1,t)))]),r.push([span(C.white+BOLD,"Accessing workspace:")]),r.push([span(C.white+BOLD,clip(s,Math.max(1,t-1)))]),r.push([span("","")]);for(const e of wrapped("Quick safety check: Is this a project you created or one you trust? (Like your own code, a well-known open source project, or work from your team). If not, take a moment to review what's in this folder first.",t,C.white))r.push(e);r.push([span("","")]),r.push([span(C.white,`${PRODUCT} will be able to read, edit, and execute files here.`)]),r.push([span("","")]),r.push([span(C.white+BOLD,"Security guide")]),r.push([span("","")]);for(let e=0;e<2;e++){const t=n===e,s=t?span(C.lavender,GLYPH.cursor):span(""," "),o=span(C.gray,` ${e+1}.`),a=0===e?"Yes, I trust this folder":"No, exit";r.push([s,o,span(t?C.lavender:C.white,a)])}return r.push([span("","")]),r.push([span(C.gray,`Enter to confirm ${GLYPH.bullet} Esc to cancel`)]),r}async function showTrustCheck(e){const{cols:t}=getSize();let n=0;const s=()=>paint(trustLines(e,t,n));for(s();;){const e=await nextKey();if(e.name===KEY.UP||e.name===KEY.DOWN||e.name===KEY.TAB)n=1-n,s();else{if(e.name===KEY.ENTER)return 0===n;if(e.name===KEY.ESC||e.name===KEY.CTRL_C||e.name===KEY.CTRL_D)return!1;if("char"===e.name){const t=String(e.ch).trim();"1"===t&&(n=0,s()),"2"===t&&(n=1,s())}}}}function applyTheme(e,t){return THEME_TABLE[t]||THEME_TABLE[1],e.themeIndex=t,e.light=themeIsLight(t),t}function themePickerLines(e,t,n,s){const r=[];r.push([span(C.coral,`Welcome to ${PRODUCT} v${VERSION}`)]),r.push([span(C.white+BOLD,"Let's get started.")]),r.push([span(C.white,"Choose the text style that looks best with your terminal")]),r.push([span(C.gray,"To change this later, run /theme")]),r.push([span("","")]);for(let e=0;e<THEME_TABLE.length;e++){const t=THEME_TABLE[e],n=s===e,o=n?span(C.lavender,GLYPH.cursor):span(""," "),a=span(C.gray,`${e+1}.`),i=n?span(C.green," "+GLYPH.check):span("","");r.push([o,a,span(n?C.lavender:C.white,t.name),...t.note?[span(C.gray," "+t.note)]:[],i])}for(const n of renderDiffPreview(t,e))r.push(n);for(r.push([span(C.gray," Syntax theme: Monokai Extended (ctrl+t to disable)")]);r.length<n-1;)r.push([span("","")]);return r}async function showThemePicker(e,t=`Welcome to ${PRODUCT}`){const{cols:n,rows:s}=getSize();let r="number"==typeof e.themeIndex?e.themeIndex:terminalIsLight()?2:1;const o=()=>paint(themePickerLines(e,n,s,r));for(o();;){const t=await nextKey();if(t.name===KEY.UP)r=Math.max(0,r-1),o();else if(t.name===KEY.DOWN)r=Math.min(THEME_TABLE.length-1,r+1),o();else{if(t.name===KEY.ENTER||t.name===KEY.ESC||t.name===KEY.CTRL_C||t.name===KEY.CTRL_D)return applyTheme(e,r);if(t.name===KEY.CTRL_T)e.light=!e.light,o();else if("char"===t.name){const e=parseInt(t.ch,10);e>=1&&e<=THEME_TABLE.length&&(r=e-1,o())}}}}function welcomeLines(e,t,n,s=!0){const r=themeOf(e),o=[];o.push([span(r.gold,"━"+"─".repeat(Math.max(0,t-2))+"━")]),o.push([span("","")]);let a=null;try{const e=loadConfig(),t=updateNotice({current:VERSION,cache:e.updateCheck,save:e=>{try{updateConfig({updateCheck:e})}catch{}}});a=updateLine({current:VERSION,...t});const n=serverNotice({current:VERSION,cache:e.updateCheckServer,save:e=>{try{updateConfig({updateCheckServer:e})}catch{}}});a=serverUpdateLine(n)||a,decomposedVersion(VERSION)&&(a=decomposedUpdateLine(VERSION)||a)}catch{}const i=welcomeArtParts();if(t>=i.width+2){const n=Math.max(0,Math.floor((t-i.width)/2));for(const t of i.rows)o.push(wrapPlain(render.artRow(e,t,i,n)))}else o.push(centered(`${PRODUCT}`,t,r.gold+BOLD));a&&(o.push([span("","")]),o.push(centered(a,t,r.gold))),o.push([span("","")]);const p=s?`Welcome to ${PRODUCT}`:"Welcome back!";o.push(centered(p,t,r.coral+BOLD));const c=t>=w(TAGLINE)+4?TAGLINE:TAGLINE_SHORT;o.push(centered(c,t,r.gray)),o.push([span("","")]),o.push(...boxes(r,t,n-o.length-4)),o.push([span("","")]);for(const e of connectRows())o.push(...wrapped(e,t,r.white,1));for(o.push([span(r.gray,GLYPH.hint),span(r.white,' Try "write a test for <filepath>"')]);o.length<n-1;)o.push([span("","")]);return o}function boxLines(e,t,n,s){const r=Math.max(1,s-4),o=` ${clip(t,Math.max(0,s-4))} `,a=[[span(e.gray,"╭─"),span(e.gray+BOLD,o),span(e.gray,"─".repeat(Math.max(0,s-3-o.length))+"╮")]];for(const t of n){const n=clip(String(t),r);a.push([span(e.gray,"│ "),span(e.white,n+" ".repeat(Math.max(0,r-w(n)))),span(e.gray," │")])}return a.push([span(e.gray,"╰"+"─".repeat(r+2)+"╯")]),a}function boxes(e,t,n){const s=Math.floor((t-2)/2),r=TIPS.map((e=>`${GLYPH.pointer}${e}`)),o=KEY_HELP,a=`Models & keys · v${VERSION}`;if(s>=30){let t=boxLines(e,"Tips for getting started",r,s),n=boxLines(e,a,o,s);const i=Math.max(t.length,n.length),p=t=>{if(t.length>=i)return t;const n=t.slice(0,t.length-1),r=[span(e.gray,"│ "),span(""," ".repeat(Math.max(0,s-4))),span(e.gray," │")];for(;n.length<i-1;)n.push(r);return n.push(t[t.length-1]),n};t=p(t),n=p(n);const c=[];for(let e=0;e<i;e++)c.push([...t[e],span(""," ".repeat(2)),...n[e]]);return c}const i=Math.max(20,t-1);return[...boxLines(e,"Tips for getting started",r,i),...boxLines(e,a,o,i)]}function wrapPlain(e){const t=[],n=/\x1b\[[0-9;]*m/g;let s,r=0,o="";for(;null!==(s=n.exec(e));)s.index>r&&t.push(make(o,e.slice(r,s.index))),o=s[0],r=s.index+s[0].length;return r<e.length&&t.push(make(o,e.slice(r))),t}function make(e,t){const n=span(e,t);return e&&(n.s=e,n.w=w(t)),n}function providerRouteConfigured(){try{return createSettingsStore({dir:credentials.aegisHome()}).list().some((e=>{if(!e||!e.provider||isReservedNamespace(e.provider))return!1;const t="string"==typeof e.baseURL?e.baseURL.trim():"";return Boolean(e.configured||t)}))}catch{return!1}}function connectNeeded(){try{return byokRouteNeeded()||cloudRouteNeeded()}catch{return!0}}function byokRouteNeeded(){try{return!providerRouteConfigured()}catch{return!0}}function cloudRouteNeeded(){try{return!credentials.keyStatus().configured}catch{return!0}}async function showWelcome(e,t=!0){for((()=>{const{cols:n,rows:s}=getSize();paint(welcomeLines(e,n,s,t))})();;){const e=await nextKey();if(e.name===KEY.ENTER||e.name===KEY.ESC)return{exit:!1};if(e.name===KEY.CTRL_C||e.name===KEY.CTRL_D)return{exit:!0}}}const KEY_URL=signupUrl("key_screen");function keyLines(e,t,{value:n="",error:s=null,verify:r=!1}={}){const o=themeOf(e),a=[];a.push([span(o.gold,"─".repeat(Math.max(1,t)))]),a.push([span(o.white+BOLD,"Connect your AEGIS account")]),a.push([span("","")]);for(const e of wrapped("Paste an API key to use AEGIS Cloud. It is stored in your user config directory with owner-only permissions, so later launches and scripts pick it up without an export.",t,o.white))a.push(e);a.push([span("","")]);const i=" No key yet? Free one at ";return w(i)+w(KEY_URL)+2<=t?a.push([span(o.white,i),span(o.cyan,KEY_URL)]):(a.push([span(o.white," No key yet? Free one:")]),a.push([span(o.cyan,` ${KEY_URL}`)])),a.push([span("","")]),a.push([span(o.lavender,GLYPH.cursor),span(o.gray," API key: "),span(o.white,"•".repeat(String(n).length)),span(r?o.cyan:o.gray,r?" verifying…":"")]),s&&a.push([span(o.coral,` ${s}`)]),a.push([span("","")]),a.push([span(o.gray,` ${GLYPH.check} `),span(o.gray,"Enter to save"),span(o.gray," · "),span(o.gray,"Esc to skip")]),a}async function requestApiKey(e,t={}){const n=t.submit||(async()=>({ok:!0})),{cols:s}=getSize();let r="",o=null,a=!1;const i=()=>paint(keyLines(e,s,{value:r,error:o,verify:a}));for(i();;){const e=await nextKey();if(e.name===KEY.ENTER){if(!r.trim())return{skipped:!0};let e;a=!0,o=null,i();try{e=await n(r)}catch(t){e={ok:!1,message:t&&t.message||String(t)}}if(a=!1,e&&!1===e.ok){o=e.message||"that key was refused",i();continue}return{key:r,result:e}}if(e.name===KEY.ESC)return{skipped:!0};if(e.name===KEY.CTRL_C||e.name===KEY.CTRL_D)return{exit:!0};if(e.name!==KEY.BACKSPACE)if("char"!==e.name)"paste"===e.name&&e.text&&(r=(r+String(e.text)).replace(/\s+/g,""),o=null,i());else{const t=e.ch;t&&t>=" "&&(r+=t,o=null,i())}else r=r.slice(0,-1),o=null,i()}}async function runOnboarding(e,t={}){const n=t.seen||configExists,s=t.save||updateConfig,r={showTrustCheck:showTrustCheck,showThemePicker:showThemePicker,showWelcome:showWelcome,requestApiKey:(e,n)=>requestApiKey(e,{submit:t.submitKey||(async()=>({ok:!0})),...n}),...t.ui||{}},o=t.needsKey||(()=>!credentials.hasApiKey()),a=t.canPrompt||(()=>!(!process.stdin||!process.stdin.isTTY)),i={set:!1,skipped:!1};if(t.continue)return{ok:!0,firstRun:!1,themeIndex:e.themeIndex,key:{set:!1,skipped:!1}};const p=!events.isKeyStreamAttached()&&!(!process.stdin||!process.stdin.isTTY);p&&events.attachKeyStream(process.stdin);try{return await async function(){if(!n()){if(!await r.showTrustCheck(e))return{ok:!1,firstRun:!0,themeIndex:e.themeIndex,key:i};if(await r.showThemePicker(e),s({themeIndex:e.themeIndex,light:e.light}),await c())return{ok:!1,firstRun:!0,themeIndex:e.themeIndex,key:i};const t=await r.showWelcome(e,!0);return t&&t.exit?{ok:!1,firstRun:!0,themeIndex:e.themeIndex,key:i}:{ok:!0,firstRun:!0,themeIndex:e.themeIndex,key:i}}if(await c())return{ok:!1,firstRun:!1,themeIndex:e.themeIndex,key:i};const t=await r.showWelcome(e,!1);return t&&t.exit?{ok:!1,firstRun:!1,themeIndex:e.themeIndex,key:i}:{ok:!0,firstRun:!1,themeIndex:e.themeIndex,key:i}}()}finally{p&&events.detachKeyStream()}async function c(){if(!o()||!a())return!1;const t=await r.requestApiKey(e);return!(!t||!t.exit)||(t&&t.key?i.set=!0:i.skipped=!0,!1)}}module.exports={PRODUCT:PRODUCT,TIPS:TIPS,KEY_HELP:KEY_HELP,CONNECT_BYOK:CONNECT_BYOK,CONNECT_CLOUD:CONNECT_CLOUD,CONNECT_BOTH:CONNECT_BOTH,CONNECT_DESKTOP:CONNECT_DESKTOP,connectRows:connectRows,connectNeeded:connectNeeded,byokRouteNeeded:byokRouteNeeded,cloudRouteNeeded:cloudRouteNeeded,providerRouteConfigured:providerRouteConfigured,trustLines:trustLines,themePickerLines:themePickerLines,keyLines:keyLines,applyTheme:applyTheme,welcomeLines:welcomeLines,boxes:boxes,boxLines:boxLines,centered:centered,wrapped:wrapped,wrapPlain:wrapPlain,showTrustCheck:showTrustCheck,showThemePicker:showThemePicker,requestApiKey:requestApiKey,showWelcome:showWelcome,runOnboarding:runOnboarding,KEY_URL:KEY_URL};
|
package/src/update.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const path=require("node:path"),fs=require("node:fs"),{execFileSync:execFileSync}=require("node:child_process"),{resolveShared:resolveShared}=require("./deps.js"),shared=require(resolveShared("client/update.js")),VERSION=require("../package.json").version,PKG=shared.PKG||"aegiscode";let methodCache=null;function installMethod(){if(methodCache)return methodCache;const e=shared.detectInstallMethod;if("function"!=typeof e)return methodCache="npm",methodCache;try{methodCache=e({env:process.env,argv:process.argv,pkg:PKG,entry:path.resolve(__dirname,".."),fileExists:e=>fs.existsSync(path.resolve(__dirname,"..","..",e))})}catch{methodCache="npm"}return methodCache}function compareVersions(e,n){const t=String(e||"0").split("-")[0].split(".").map((e=>Number.parseInt(e,10)||0)),r=String(n||"0").split("-")[0].split(".").map((e=>Number.parseInt(e,10)||0));for(let e=0;e<Math.max(t.length,r.length);e++){const n=(t[e]||0)-(r[e]||0);if(n)return n>0?1:-1}return 0}function upgradeAdvice({current:e=VERSION,latest:n=null,packageName:t=PKG,method:r="npm"}={}){if(!n)return{upToDate:null,lines:[` Could not read the npm registry — local version is ${e}.`]};if(compareVersions(n,e)>0){const
|
|
3
|
+
"use strict";const path=require("node:path"),fs=require("node:fs"),{execFileSync:execFileSync}=require("node:child_process"),{resolveShared:resolveShared}=require("./deps.js"),shared=require(resolveShared("client/update.js")),VERSION=require("../package.json").version,PKG=shared.PKG||"aegiscode",DECOMPOSED_VERSIONS=Object.freeze(["1.0.47"]);function decomposedVersion(e=VERSION){return DECOMPOSED_VERSIONS.includes(String(e||"").trim())}function decomposedUpdateLine(e=VERSION){return decomposedVersion(e)?`This version (${e}) is DECOMPOSED — update to the latest release.`:null}let methodCache=null;function installMethod(){if(methodCache)return methodCache;const e=shared.detectInstallMethod;if("function"!=typeof e)return methodCache="npm",methodCache;try{methodCache=e({env:process.env,argv:process.argv,pkg:PKG,entry:path.resolve(__dirname,".."),fileExists:e=>fs.existsSync(path.resolve(__dirname,"..","..",e))})}catch{methodCache="npm"}return methodCache}function compareVersions(e,n){const t=String(e||"0").split("-")[0].split(".").map((e=>Number.parseInt(e,10)||0)),r=String(n||"0").split("-")[0].split(".").map((e=>Number.parseInt(e,10)||0));for(let e=0;e<Math.max(t.length,r.length);e++){const n=(t[e]||0)-(r[e]||0);if(n)return n>0?1:-1}return 0}function upgradeAdvice({current:e=VERSION,latest:n=null,packageName:t=PKG,method:r="npm"}={}){if(!n)return{upToDate:null,lines:[` Could not read the npm registry — local version is ${e}.`]};if(compareVersions(n,e)>0){const s="function"==typeof shared.updatePlan?shared.updatePlan({current:e,latest:n,behind:!0,channel:"npm",pkg:t,method:r}):null,a=[` Installed: ${e}`,` Published: ${n}`,` Channel: ${r}`,` Upgrade: ${s&&s.instruction||`npm i -g ${t}@latest`}`];return s&&s.apply&&a.push(" (or run `/upgrade apply` to do it here)"),{upToDate:!1,lines:a,plan:s}}return{upToDate:!0,lines:[` Installed ${e} is the published ${n} — nothing to upgrade.`]}}function applyUpgrade({current:e=VERSION,packageName:n=PKG,method:t="npm",latest:r=null}={}){const s="function"==typeof shared.updatePlan&&r?shared.updatePlan({current:e,latest:r,behind:!0,channel:"npm",pkg:n,method:t}):null,a=s&&s.apply?s.apply:null;if(!a)return{ok:!0,skipped:!0,channel:t,command:null,instruction:s&&s.instruction||("npm"===t?`npm i -g ${n}@latest`:"restart to pick up the new version")};try{const e=("function"==typeof shared.installSpawn?shared.installSpawn(a,{env:process.env}):{command:a.command,args:a.args,shell:!1})||{command:a.command,args:a.args,shell:!1},n=execFileSync(e.command,e.args,{encoding:"utf8",timeout:18e4,stdio:["ignore","pipe","pipe"],shell:!0===e.shell,windowsHide:!0});return{ok:!0,channel:t,command:`${a.command} ${a.args.join(" ")}`,output:String(n||"").trim()}}catch(e){return{ok:!1,channel:t,command:`${a.command} ${a.args.join(" ")}`,error:String(e&&(e.stderr||e.message)||e).trim()}}}function latestPublishedVersion({packageName:e=PKG,timeoutMs:n=5e3}={}){try{const t=execFileSync("npm",["view",e,"version"],{encoding:"utf8",timeout:n,stdio:["ignore","pipe","ignore"]}),r=String(t).trim();return/^\d+\.\d+\.\d+/.test(r)?r:null}catch{return null}}module.exports={...shared,VERSION:VERSION,compareVersions:compareVersions,upgradeAdvice:upgradeAdvice,applyUpgrade:applyUpgrade,installMethod:installMethod,latestPublishedVersion:latestPublishedVersion,DECOMPOSED_VERSIONS:DECOMPOSED_VERSIONS,decomposedVersion:decomposedVersion,decomposedUpdateLine:decomposedUpdateLine};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const 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));
|
|
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};
|
package/vendor/client/update.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
const https=require("node:https"),fs=require("node:fs");let platformHelpers=null;try{platformHelpers=require("./platform.js")}catch{platformHelpers=null}const REGISTRY="https://registry.npmjs.org",PKG="aegiscode",CHECK_INTERVAL_MS=864e5,TIMEOUT_MS=2500;function isNewer(e,t){const n=e=>String(e||"").trim().replace(/^v/,"").split("-")[0].split(".").map((e=>Number.parseInt(e,10)||0)),r=n(e),s=n(t);for(let e=0;e<Math.max(r.length,s.length);e++){const t=r[e]||0,n=s[e]||0;if(t!==n)return t>n}return!1}const REASONS=Object.freeze({TIMEOUT:"timeout",NETWORK:"network",NOT_FOUND:"not-found",FORBIDDEN:"forbidden",HTTP:"http",MALFORMED:"malformed",TOO_LARGE:"too-large"});function isTransientReason(e,t=null){return e===REASONS.TIMEOUT||e===REASONS.NETWORK||e===REASONS.HTTP&&(!t||t>=500||429===t)}function fetchLatestDetailed({pkg:e=PKG,timeoutMs:t=TIMEOUT_MS}={}){return new Promise((n=>{let r=!1;const s=e=>{r||(r=!0,n(e))},l=(e,t=null)=>s({ok:!1,latest:null,reason:e,status:t});try{const n=https.get(`${REGISTRY}/${e}`,{headers:{accept:"application/vnd.npm.install-v1+json"},timeout:t},(e=>{const t=e.statusCode;if(200!==t)return e.resume(),l(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);let r="";e.setEncoding("utf8"),e.on("data",(e=>{r+=e,r.length>2e6&&(n.destroy(),l(REASONS.TOO_LARGE,t))})),e.on("end",(()=>{try{const e=JSON.parse(r)["dist-tags"],n=e&&e.latest||null;if(!n)return l(REASONS.MALFORMED,t);(e=>{s({ok:!0,latest:e,reason:null,status:200})})(n)}catch{l(REASONS.MALFORMED,t)}}))}));n.on("timeout",(()=>{n.destroy(),l(REASONS.TIMEOUT)})),n.on("error",(()=>l(REASONS.NETWORK)))}catch{l(REASONS.NETWORK)}}))}function fetchLatest(e={}){return fetchLatestDetailed(e).then((e=>e.ok?e.latest:null))}const DEFAULT_API_BASE="https://aegiscloud.org",VERSION_BODY_CAP=65536;function fetchServerVersionDetailed({base:e=DEFAULT_API_BASE,clientVersion:t=null,timeoutMs:n=TIMEOUT_MS,getImpl:r=null}={}){return new Promise((s=>{let l=!1;const o=e=>{l||(l=!0,s(e))},a=(e,t=null)=>o({ok:!1,minClient:null,latestCli:null,latestDesktop:null,upgradeRequired:null,downloadUrl:"",reason:e,status:t}),i=(e,n)=>{const r=e&&"string"==typeof e.min_client?e.min_client:null;if(!r)return a(REASONS.MALFORMED,n);o({ok:!0,minClient:r,latestCli:"string"==typeof e.latest_cli?e.latest_cli:"",latestDesktop:"string"==typeof e.latest_desktop?e.latest_desktop:"",upgradeRequired:t&&"boolean"==typeof e.upgrade_required?e.upgrade_required:null,downloadUrl:"string"==typeof e.download_url?e.download_url:"",reason:null,status:n})};try{const s=`${String(e||DEFAULT_API_BASE).replace(/\/+$/,"")}/api/v1/version`,o={accept:"application/json"};t&&(o["X-AEGIS-Version"]=String(t));const c=e=>{const t=e.statusCode;if(200!==t)return e.resume(),a(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);let n="";e.setEncoding("utf8"),e.on("data",(r=>{n+=r,n.length>VERSION_BODY_CAP&&(e.destroy(),a(REASONS.TOO_LARGE,t))})),e.on("end",(()=>{if(!l)try{i(JSON.parse(n),t)}catch{a(REASONS.MALFORMED,t)}}))};if("function"==typeof r)return void Promise.resolve(r({url:s,headers:o,timeoutMs:n})).then((e=>{const t=e&&null!=e.status?e.status:0;if(!t)return a(REASONS.NETWORK);if(200!==t)return a(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);const n=e&&"string"==typeof e.text?e.text:"";if(n.length>VERSION_BODY_CAP)return a(REASONS.TOO_LARGE,t);try{i(JSON.parse(n),t)}catch{a(REASONS.MALFORMED,t)}})).catch((()=>a(REASONS.NETWORK)));const u=require(/^http:\/\//i.test(s)?"node:http":"node:https").get(s,{headers:o,timeout:n},c);u.on("timeout",(()=>{u.destroy(),a(REASONS.TIMEOUT)})),u.on("error",(()=>a(REASONS.NETWORK)))}catch{a(REASONS.NETWORK)}}))}function fetchServerVersion(e={}){return fetchServerVersionDetailed(e).then((e=>e.ok?e.minClient:null))}async function serverUpdateVerdict({current:e,base:t=DEFAULT_API_BASE,timeoutMs:n=TIMEOUT_MS,getImpl:r=null}={}){const s=await fetchServerVersionDetailed({base:t,clientVersion:e,timeoutMs:n,getImpl:r});if(!s.ok)return{ok:!1,behind:!1,latest:null,required:null,downloadUrl:"",reason:s.reason,status:s.status};const l=s.minClient||null,o=!0===s.upgradeRequired||!1!==s.upgradeRequired&&!!l&&isNewer(l,e);return{ok:!0,behind:o,latest:o&&(s.latestCli||s.latestDesktop)||l,latestCli:s.latestCli,latestDesktop:s.latestDesktop,required:l,downloadUrl:s.downloadUrl,reason:null,status:s.status}}function updateNotice({current:e,cache:t,save:n,now:r=Date.now(),fetchImpl:s=fetchLatest,intervalMs:l=864e5}={}){const o=t||{};"number"==typeof o.checkedAt&&r-o.checkedAt<l||Promise.resolve(s()).then((e=>{e&&"function"==typeof n&&n({checkedAt:r,latest:e})})).catch((()=>{}));const a=o.latest||null;return{latest:a,behind:!(!a||!isNewer(a,e))}}function installSpawn(e,t={}){if(!e||"string"!=typeof e.command||!e.command)return null;const n=t&&"object"==typeof t?t:{},r="string"==typeof n.platform&&n.platform?n.platform:process.platform,s=n.env&&"object"==typeof n.env?n.env:process.env,l=void 0===n.helpers?platformHelpers:n.helpers,o=Array.isArray(e.args)?e.args.map(String):[],a=[e.command,...o].join(" ");if("win32"===r){const e=l&&"function"==typeof l.shellSpec?l.shellSpec({platform:r,env:s}):{cmd:"cmd.exe",arg:"/d /s /c"};return{command:e.cmd,args:[...String(e.arg).split(" "),a],shell:!1,script:a}}let i=e.command;if(l&&"function"==typeof l.resolveExecutable)try{const t=l.resolveExecutable(e.command,{platform:r,env:s,..."function"==typeof n.exists?{exists:n.exists}:{}});t&&(i=t)}catch{}return{command:i,args:o.slice(),shell:!1,script:a}}function updatePlan({current:e,latest:t,behind:n,channel:r="npm",pkg:s=PKG,method:l="npm"}={}){const o=String(null==e?"":e),a=t?String(t):null;if(!Boolean(n)||!Boolean(a))return{channel:r,method:l,current:o,latest:a,behind:!1,action:"none",applier:"none",instruction:null,apply:null};const i=APPLIERS[l]||APPLIERS.npm;return{channel:r,method:l,current:o,latest:a,behind:!0,action:i.action,applier:i.name,instruction:i.instruction(s),apply:i.apply?i.apply(s):null}}const APPLIERS=Object.freeze({npm:Object.freeze({name:"npm",action:"npm-update",instruction:e=>`npm i -g ${e}@latest`,apply:e=>({command:"npm",args:["i","-g",`${e}@latest`]})}),pip:Object.freeze({name:"pip",action:"pip-update",instruction:e=>`pip install -U ${e}`,apply:e=>({command:"win32"===process.platform?"python":"python3",args:["-m","pip","install","-U",e]})}),npx:Object.freeze({name:"none",action:"npx-update",instruction:()=>"already fetched fresh on every run — restart to pick up the new version",apply:null}),source:Object.freeze({name:"git",action:"source-update",instruction:()=>"git pull && npm ci (this copy is a source checkout)",apply:null})});function detectInstallMethod({env:e={},argv:t=[],pkg:n=PKG,fileExists:r=(()=>!1),entry:s=""}={}){const l=String(e&&e.AEGIS_INSTALL_METHOD||"").trim().toLowerCase();if(l&&Object.prototype.hasOwnProperty.call(APPLIERS,l))return l;const o=t.map((e=>String(e))).join(" ");return/\bnpx\b/.test(o)||/_npx[\\/]/.test(o)||/_npx[\\/]/.test(s)?"npx":/[\\/]pipx[\\/]venvs[\\/]/.test(s)||/[\\/]site-packages[\\/]/.test(s)?"pip":/[\\/]node_modules[\\/]/.test(s)?"npm":r(".git")&&r("client/update.js")?"source":"npm"}async function checkPublished({current:e,cache:t,save:n,now:r=Date.now(),fetchImpl:s=fetchLatestDetailed,intervalMs:l=864e5,timeoutMs:o=TIMEOUT_MS,pkg:a=PKG}={}){const i=t||null;if(Boolean(i)&&"number"==typeof i.checkedAt&&r-i.checkedAt<l){const t=i.latest||null;return{ok:Boolean(t),latest:t,behind:!(!t||!isNewer(t,e)),reason:t?null:i.reason||null,status:t?200:null==i.status?null:i.status,cached:!0,checkedAt:i.checkedAt}}let c;try{c=await s({pkg:a,timeoutMs:o})}catch(e){c={ok:!1,latest:null,reason:REASONS.NETWORK,status:null,error:String(e&&e.message||e)}}const u={checkedAt:r,latest:c&&c.latest?c.latest:null,reason:c&&c.reason||null,status:c&&null!=c.status?c.status:null};if("function"==typeof n)try{n(u)}catch{}return{ok:Boolean(c&&c.ok&&c.latest),latest:u.latest,behind:!(!u.latest||!isNewer(u.latest,e)),reason:u.reason,status:u.status,cached:!1,checkedAt:r}}function updateLine({current:e,latest:t,behind:n,pkg:r=PKG,method:s="npm"}){const l=updatePlan({current:e,latest:t,behind:n,channel:"npm",pkg:r,method:s});if(!l.behind)return null;const o=`Update available: ${l.current} → ${l.latest}`;return l.apply?`${o} run: ${l.instruction}`:`${o} ${l.instruction}`}function serverNotice({current:e,cache:t,save:n,now:r=Date.now(),verdictImpl:s=serverUpdateVerdict,intervalMs:l=864e5}={}){const o=t||{};return"number"==typeof o.checkedAt&&r-o.checkedAt<l||Promise.resolve().then((()=>s({current:e}))).then((e=>{e&&"function"==typeof n&&n({checkedAt:r,behind:Boolean(e.behind),required:e.required||null,latest:e.latest||null,downloadUrl:e.downloadUrl||"",reason:e.reason||null})})).catch((()=>{})),{behind:Boolean(o.behind),latest:o.latest||null,required:o.required||null,downloadUrl:o.downloadUrl||""}}function serverUpdateLine({behind:e,latest:t,required:n,downloadUrl:r}={}){if(!e)return null;const s=t||n||"";return`${s?`This build is no longer served — update to v${s}.`:"This build is no longer served — update to the latest release."}${r?` ${r}`:""}`}module.exports={isNewer:isNewer,fetchLatest:fetchLatest,fetchLatestDetailed:fetchLatestDetailed,fetchServerVersion:fetchServerVersion,fetchServerVersionDetailed:fetchServerVersionDetailed,serverUpdateVerdict:serverUpdateVerdict,serverNotice:serverNotice,serverUpdateLine:serverUpdateLine,isTransientReason:isTransientReason,updateNotice:updateNotice,checkPublished:checkPublished,updatePlan:updatePlan,installSpawn:installSpawn,updateLine:updateLine,detectInstallMethod:detectInstallMethod,APPLIERS:APPLIERS,PKG:PKG,CHECK_INTERVAL_MS:864e5,REASONS:REASONS,DEFAULT_API_BASE:DEFAULT_API_BASE};
|
|
3
|
+
const https=require("node:https"),fs=require("node:fs");let platformHelpers=null;try{platformHelpers=require("./platform.js")}catch{platformHelpers=null}const REGISTRY="https://registry.npmjs.org",PKG="aegiscode",CHECK_INTERVAL_MS=864e5,TIMEOUT_MS=2500;function isNewer(e,t){const n=e=>String(e||"").trim().replace(/^v/,"").split("-")[0].split(".").map((e=>Number.parseInt(e,10)||0)),s=n(e),r=n(t);for(let e=0;e<Math.max(s.length,r.length);e++){const t=s[e]||0,n=r[e]||0;if(t!==n)return t>n}return!1}const REASONS=Object.freeze({TIMEOUT:"timeout",NETWORK:"network",NOT_FOUND:"not-found",FORBIDDEN:"forbidden",HTTP:"http",MALFORMED:"malformed",TOO_LARGE:"too-large"});function isTransientReason(e,t=null){return e===REASONS.TIMEOUT||e===REASONS.NETWORK||e===REASONS.HTTP&&(!t||t>=500||429===t)}function fetchLatestDetailed({pkg:e=PKG,timeoutMs:t=TIMEOUT_MS}={}){return new Promise((n=>{let s=!1;const r=e=>{s||(s=!0,n(e))},o=(e,t=null)=>r({ok:!1,latest:null,reason:e,status:t});try{const n=https.get(`${REGISTRY}/${e}`,{headers:{accept:"application/vnd.npm.install-v1+json"},timeout:t},(e=>{const t=e.statusCode;if(200!==t)return e.resume(),o(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);let s="";e.setEncoding("utf8"),e.on("data",(e=>{s+=e,s.length>2e6&&(n.destroy(),o(REASONS.TOO_LARGE,t))})),e.on("end",(()=>{try{const e=JSON.parse(s)["dist-tags"],n=e&&e.latest||null;if(!n)return o(REASONS.MALFORMED,t);(e=>{r({ok:!0,latest:e,reason:null,status:200})})(n)}catch{o(REASONS.MALFORMED,t)}}))}));n.on("timeout",(()=>{n.destroy(),o(REASONS.TIMEOUT)})),n.on("error",(()=>o(REASONS.NETWORK)))}catch{o(REASONS.NETWORK)}}))}function fetchLatest(e={}){return fetchLatestDetailed(e).then((e=>e.ok?e.latest:null))}const DEFAULT_API_BASE="https://aegiscloud.org",VERSION_BODY_CAP=65536;function fetchServerVersionDetailed({base:e=DEFAULT_API_BASE,clientVersion:t=null,timeoutMs:n=TIMEOUT_MS,getImpl:s=null}={}){return new Promise((r=>{let o=!1;const l=e=>{o||(o=!0,r(e))},a=(e,t=null)=>l({ok:!1,minClient:null,latestCli:null,latestDesktop:null,upgradeRequired:null,decomposed:null,downloadUrl:"",reason:e,status:t}),i=(e,n)=>{const s=e&&"string"==typeof e.min_client?e.min_client:null;if(!s)return a(REASONS.MALFORMED,n);l({ok:!0,minClient:s,latestCli:"string"==typeof e.latest_cli?e.latest_cli:"",latestDesktop:"string"==typeof e.latest_desktop?e.latest_desktop:"",upgradeRequired:t&&"boolean"==typeof e.upgrade_required?e.upgrade_required:null,decomposed:t&&"boolean"==typeof e.decomposed?e.decomposed:null,downloadUrl:"string"==typeof e.download_url?e.download_url:"",reason:null,status:n})};try{const r=`${String(e||DEFAULT_API_BASE).replace(/\/+$/,"")}/api/v1/version`,l={accept:"application/json"};t&&(l["X-AEGIS-Version"]=String(t));const c=e=>{const t=e.statusCode;if(200!==t)return e.resume(),a(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);let n="";e.setEncoding("utf8"),e.on("data",(s=>{n+=s,n.length>VERSION_BODY_CAP&&(e.destroy(),a(REASONS.TOO_LARGE,t))})),e.on("end",(()=>{if(!o)try{i(JSON.parse(n),t)}catch{a(REASONS.MALFORMED,t)}}))};if("function"==typeof s)return void Promise.resolve(s({url:r,headers:l,timeoutMs:n})).then((e=>{const t=e&&null!=e.status?e.status:0;if(!t)return a(REASONS.NETWORK);if(200!==t)return a(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);const n=e&&"string"==typeof e.text?e.text:"";if(n.length>VERSION_BODY_CAP)return a(REASONS.TOO_LARGE,t);try{i(JSON.parse(n),t)}catch{a(REASONS.MALFORMED,t)}})).catch((()=>a(REASONS.NETWORK)));const u=require(/^http:\/\//i.test(r)?"node:http":"node:https").get(r,{headers:l,timeout:n},c);u.on("timeout",(()=>{u.destroy(),a(REASONS.TIMEOUT)})),u.on("error",(()=>a(REASONS.NETWORK)))}catch{a(REASONS.NETWORK)}}))}function fetchServerVersion(e={}){return fetchServerVersionDetailed(e).then((e=>e.ok?e.minClient:null))}async function serverUpdateVerdict({current:e,base:t=DEFAULT_API_BASE,timeoutMs:n=TIMEOUT_MS,getImpl:s=null}={}){const r=await fetchServerVersionDetailed({base:t,clientVersion:e,timeoutMs:n,getImpl:s});if(!r.ok)return{ok:!1,behind:!1,latest:null,required:null,decomposed:null,downloadUrl:"",reason:r.reason,status:r.status};const o=r.minClient||null,l=!0===r.upgradeRequired||!1!==r.upgradeRequired&&!!o&&isNewer(o,e);return{ok:!0,behind:l,latest:l&&(r.latestCli||r.latestDesktop)||o,latestCli:r.latestCli,latestDesktop:r.latestDesktop,required:o,decomposed:r.decomposed,downloadUrl:r.downloadUrl,reason:null,status:r.status}}function updateNotice({current:e,cache:t,save:n,now:s=Date.now(),fetchImpl:r=fetchLatest,intervalMs:o=864e5}={}){const l=t||{};"number"==typeof l.checkedAt&&s-l.checkedAt<o||Promise.resolve(r()).then((e=>{e&&"function"==typeof n&&n({checkedAt:s,latest:e})})).catch((()=>{}));const a=l.latest||null,i=!0===l.decomposed;return{latest:a,behind:!(!a||!isNewer(a,e)),decomposed:i}}function installSpawn(e,t={}){if(!e||"string"!=typeof e.command||!e.command)return null;const n=t&&"object"==typeof t?t:{},s="string"==typeof n.platform&&n.platform?n.platform:process.platform,r=n.env&&"object"==typeof n.env?n.env:process.env,o=void 0===n.helpers?platformHelpers:n.helpers,l=Array.isArray(e.args)?e.args.map(String):[],a=[e.command,...l].join(" ");if("win32"===s){const e=o&&"function"==typeof o.shellSpec?o.shellSpec({platform:s,env:r}):{cmd:"cmd.exe",arg:"/d /s /c"};return{command:e.cmd,args:[...String(e.arg).split(" "),a],shell:!1,script:a}}let i=e.command;if(o&&"function"==typeof o.resolveExecutable)try{const t=o.resolveExecutable(e.command,{platform:s,env:r,..."function"==typeof n.exists?{exists:n.exists}:{}});t&&(i=t)}catch{}return{command:i,args:l.slice(),shell:!1,script:a}}function updatePlan({current:e,latest:t,behind:n,channel:s="npm",pkg:r=PKG,method:o="npm"}={}){const l=String(null==e?"":e),a=t?String(t):null;if(!Boolean(n)||!Boolean(a))return{channel:s,method:o,current:l,latest:a,behind:!1,action:"none",applier:"none",instruction:null,apply:null};const i=APPLIERS[o]||APPLIERS.npm;return{channel:s,method:o,current:l,latest:a,behind:!0,action:i.action,applier:i.name,instruction:i.instruction(r),apply:i.apply?i.apply(r):null}}const APPLIERS=Object.freeze({npm:Object.freeze({name:"npm",action:"npm-update",instruction:e=>`npm i -g ${e}@latest`,apply:e=>({command:"npm",args:["i","-g",`${e}@latest`]})}),pip:Object.freeze({name:"pip",action:"pip-update",instruction:e=>`pip install -U ${e}`,apply:e=>({command:"win32"===process.platform?"python":"python3",args:["-m","pip","install","-U",e]})}),npx:Object.freeze({name:"none",action:"npx-update",instruction:()=>"already fetched fresh on every run — restart to pick up the new version",apply:null}),source:Object.freeze({name:"git",action:"source-update",instruction:()=>"git pull && npm ci (this copy is a source checkout)",apply:null})});function detectInstallMethod({env:e={},argv:t=[],pkg:n=PKG,fileExists:s=(()=>!1),entry:r=""}={}){const o=String(e&&e.AEGIS_INSTALL_METHOD||"").trim().toLowerCase();if(o&&Object.prototype.hasOwnProperty.call(APPLIERS,o))return o;const l=t.map((e=>String(e))).join(" ");return/\bnpx\b/.test(l)||/_npx[\\/]/.test(l)||/_npx[\\/]/.test(r)?"npx":/[\\/]pipx[\\/]venvs[\\/]/.test(r)||/[\\/]site-packages[\\/]/.test(r)?"pip":/[\\/]node_modules[\\/]/.test(r)?"npm":s(".git")&&s("client/update.js")?"source":"npm"}async function checkPublished({current:e,cache:t,save:n,now:s=Date.now(),fetchImpl:r=fetchLatestDetailed,intervalMs:o=864e5,timeoutMs:l=TIMEOUT_MS,pkg:a=PKG}={}){const i=t||null;if(Boolean(i)&&"number"==typeof i.checkedAt&&s-i.checkedAt<o){const t=i.latest||null;return{ok:Boolean(t),latest:t,behind:!(!t||!isNewer(t,e)),reason:t?null:i.reason||null,status:t?200:null==i.status?null:i.status,cached:!0,checkedAt:i.checkedAt}}let c;try{c=await r({pkg:a,timeoutMs:l})}catch(e){c={ok:!1,latest:null,reason:REASONS.NETWORK,status:null,error:String(e&&e.message||e)}}const u={checkedAt:s,latest:c&&c.latest?c.latest:null,reason:c&&c.reason||null,status:c&&null!=c.status?c.status:null};if("function"==typeof n)try{n(u)}catch{}return{ok:Boolean(c&&c.ok&&c.latest),latest:u.latest,behind:!(!u.latest||!isNewer(u.latest,e)),reason:u.reason,status:u.status,cached:!1,checkedAt:s}}function updateLine({current:e,latest:t,behind:n,pkg:s=PKG,method:r="npm"}){const o=updatePlan({current:e,latest:t,behind:n,channel:"npm",pkg:s,method:r});if(!o.behind)return null;const l=`Update available: ${o.current} → ${o.latest}`;return o.apply?`${l} run: ${o.instruction}`:`${l} ${o.instruction}`}function serverNotice({current:e,cache:t,save:n,now:s=Date.now(),verdictImpl:r=serverUpdateVerdict,intervalMs:o=864e5}={}){const l=t||{};return"number"==typeof l.checkedAt&&s-l.checkedAt<o||Promise.resolve().then((()=>r({current:e}))).then((e=>{e&&"function"==typeof n&&n({checkedAt:s,behind:Boolean(e.behind),decomposed:!0===e.decomposed,required:e.required||null,latest:e.latest||null,downloadUrl:e.downloadUrl||"",reason:e.reason||null})})).catch((()=>{})),{behind:Boolean(l.behind),decomposed:!0===l.decomposed,latest:l.latest||null,required:l.required||null,downloadUrl:l.downloadUrl||""}}function serverUpdateLine({behind:e,latest:t,required:n,decomposed:s,downloadUrl:r}={}){if(s)return`${t||n?`This version is DECOMPOSED — update to v${t||n}.`:"This version is DECOMPOSED — update to the latest release."}${r?` ${r}`:""}`;if(!e)return null;const o=t||n||"";return`${o?`This build is no longer served — update to v${o}.`:"This build is no longer served — update to the latest release."}${r?` ${r}`:""}`}module.exports={isNewer:isNewer,fetchLatest:fetchLatest,fetchLatestDetailed:fetchLatestDetailed,fetchServerVersion:fetchServerVersion,fetchServerVersionDetailed:fetchServerVersionDetailed,serverUpdateVerdict:serverUpdateVerdict,serverNotice:serverNotice,serverUpdateLine:serverUpdateLine,isTransientReason:isTransientReason,updateNotice:updateNotice,checkPublished:checkPublished,updatePlan:updatePlan,installSpawn:installSpawn,updateLine:updateLine,detectInstallMethod:detectInstallMethod,APPLIERS:APPLIERS,PKG:PKG,CHECK_INTERVAL_MS:864e5,REASONS:REASONS,DEFAULT_API_BASE:DEFAULT_API_BASE};
|
|
@@ -134,7 +134,7 @@ const UNITS = Object.freeze([
|
|
|
134
134
|
* (`tools/desktop-seal.mjs` in the source tree, `tools/obfuscate-faces.mjs`
|
|
135
135
|
* after obfuscation), never by hand.
|
|
136
136
|
*/
|
|
137
|
-
const SEALED = '
|
|
137
|
+
const SEALED = 'd1e46f8ffd2c652e44faffd66a6d227fafbb82ad62168511f4c19c838a2e1b57';
|
|
138
138
|
|
|
139
139
|
/**
|
|
140
140
|
* Ask the question. Never throws — a check that can break the program it is
|
package/vendor/desktop/main.js
CHANGED
|
@@ -4264,6 +4264,10 @@ function createNpmUpdateManager({
|
|
|
4264
4264
|
plan: null,
|
|
4265
4265
|
method: null,
|
|
4266
4266
|
canDownload: false,
|
|
4267
|
+
// A release the server has declared retired (`decomposed: true` from
|
|
4268
|
+
// /api/v1/version) is not a suggestion — the banner must say it even
|
|
4269
|
+
// when no newer version resolves and no download can be offered.
|
|
4270
|
+
decomposed: false,
|
|
4267
4271
|
};
|
|
4268
4272
|
const set = (patch) => {
|
|
4269
4273
|
state = { ...state, ...patch };
|
|
@@ -4376,6 +4380,22 @@ function createNpmUpdateManager({
|
|
|
4376
4380
|
return reason === 'unknown'; // unclassified: assume retryable, stay quiet
|
|
4377
4381
|
};
|
|
4378
4382
|
|
|
4383
|
+
// The server is asked at most once per process for this: a retired release
|
|
4384
|
+
// does not un-retire, and re-asking on every 4h check is the nagging the
|
|
4385
|
+
// checker's once-a-day rule exists to avoid.
|
|
4386
|
+
let decomposedCache = null; // null = no answer yet (failures are not cached)
|
|
4387
|
+
async function decomposedVerdict() {
|
|
4388
|
+
if (decomposedCache !== null) return decomposedCache;
|
|
4389
|
+
if (!updater || typeof updater.serverUpdateVerdict !== 'function') return null;
|
|
4390
|
+
try {
|
|
4391
|
+
const v = await updater.serverUpdateVerdict({ current });
|
|
4392
|
+
if (v && v.ok) decomposedCache = Boolean(v.decomposed);
|
|
4393
|
+
return decomposedCache;
|
|
4394
|
+
} catch {
|
|
4395
|
+
return null;
|
|
4396
|
+
}
|
|
4397
|
+
}
|
|
4398
|
+
|
|
4379
4399
|
/**
|
|
4380
4400
|
* `announce: false` (the default) is the background check: a network failure
|
|
4381
4401
|
* is swallowed and re-tried on the backoff ladder. `announce: true` is a
|
|
@@ -4407,6 +4427,16 @@ function createNpmUpdateManager({
|
|
|
4407
4427
|
attempts = 0;
|
|
4408
4428
|
retryAt = 0;
|
|
4409
4429
|
clearRetry();
|
|
4430
|
+
// A retired release is reported whether or not the registry found a
|
|
4431
|
+
// newer one — DECOMPOSED is the strongest thing the banner can say,
|
|
4432
|
+
// and it must not be swallowed by an 'up-to-date' registry answer.
|
|
4433
|
+
const decomposed = await decomposedVerdict();
|
|
4434
|
+
if (decomposed) {
|
|
4435
|
+
return set({
|
|
4436
|
+
status: 'decomposed', version: res.latest, error: null, reason: null,
|
|
4437
|
+
transient: false, attempts: 0, retryInMs: 0, decomposed: true,
|
|
4438
|
+
});
|
|
4439
|
+
}
|
|
4410
4440
|
if (!updater.isNewer(res.latest, current)) {
|
|
4411
4441
|
return set({
|
|
4412
4442
|
status: 'up-to-date', version: res.latest, error: null, reason: null,
|
|
@@ -5185,7 +5215,15 @@ function bootstrap() {
|
|
|
5185
5215
|
// "AEGIS One" is the casing a short-lived build used. A user can arrive
|
|
5186
5216
|
// from either, so both are candidates and neither is assumed to exist.
|
|
5187
5217
|
const parentDir = path.dirname(userDataDir);
|
|
5188
|
-
|
|
5218
|
+
// FOUR prior names, not two. `aegis one` is the fifth name this app has
|
|
5219
|
+
// shipped under: "AEGIS Desktop" (the packaged identity in
|
|
5220
|
+
// electron-builder.yml, still frozen) is what the first installs wrote, and
|
|
5221
|
+
// "AEGIS One" is the casing a short-lived build used. "Electron" is what
|
|
5222
|
+
// an un-renamed dev/running-from-source launch wrote (`app.name` defaults
|
|
5223
|
+
// to Electron before the first setName), and "aegiscode-gui" is the
|
|
5224
|
+
// pre-rename name of the very first GUI. A user can arrive from any of
|
|
5225
|
+
// the four, so all are candidates and none is assumed to exist.
|
|
5226
|
+
const LEGACY_NAMES = ['AEGIS Desktop', 'AEGIS One', 'Electron', 'aegiscode-gui'];
|
|
5189
5227
|
// Electron creates the userData directory eagerly, and a single launch of
|
|
5190
5228
|
// this version before the guard was correct leaves a NON-empty root full of
|
|
5191
5229
|
// Chromium profile junk (Cache/, GPUCache/, Local Storage/, Preferences,
|
|
@@ -5215,6 +5253,10 @@ function bootstrap() {
|
|
|
5215
5253
|
};
|
|
5216
5254
|
// settings.json only counts as state when it carries the account key; the
|
|
5217
5255
|
// stub a pre-migration launch wrote holds nothing but __quickLauncher.
|
|
5256
|
+
// A key found in the CURRENT root is not state: adoption moves TOWARD the
|
|
5257
|
+
// current root, so a key there means the last launch already stored its
|
|
5258
|
+
// account (safeStorage entries are still being written there); treating it
|
|
5259
|
+
// as state would point the legacy scan at the wrong end.
|
|
5218
5260
|
const hasAccountKey = (dir) => {
|
|
5219
5261
|
try {
|
|
5220
5262
|
return fs.readFileSync(path.join(dir, 'settings.json'), 'utf8').includes('"__aegis"');
|
|
@@ -5236,12 +5278,24 @@ function bootstrap() {
|
|
|
5236
5278
|
if (['sessions.json', 'avatar', 'xp.json', 'queue.jsonl'].some((n) => names.includes(n))) return true;
|
|
5237
5279
|
return hasAccountKey(dir);
|
|
5238
5280
|
};
|
|
5281
|
+
const isCurrentRoot = (dir) =>
|
|
5282
|
+
(() => {
|
|
5283
|
+
try {
|
|
5284
|
+
return fs.realpathSync(dir) === fs.realpathSync(userDataDir);
|
|
5285
|
+
} catch {
|
|
5286
|
+
return false;
|
|
5287
|
+
}
|
|
5288
|
+
})();
|
|
5239
5289
|
const isEmptyDir = (p) => isDir(p) && fs.readdirSync(p).length === 0;
|
|
5240
5290
|
|
|
5241
5291
|
// Prefer whichever legacy root actually carries state; among two that do,
|
|
5242
|
-
// take the larger sessions.json (the more recently used install).
|
|
5292
|
+
// take the larger sessions.json (the more recently used install). The
|
|
5293
|
+
// CURRENT root is never a candidate — a symlink (or a launch that already
|
|
5294
|
+
// adopted and then moved on) would otherwise make the app try to adopt
|
|
5295
|
+
// itself, and a root holding only the account key written by THIS build is
|
|
5296
|
+
// not "legacy" state to move.
|
|
5243
5297
|
const legacyDir = LEGACY_NAMES.map((n) => path.join(parentDir, n))
|
|
5244
|
-
.filter((d) => hasUserState(d))
|
|
5298
|
+
.filter((d) => hasUserState(d) && !isCurrentRoot(d))
|
|
5245
5299
|
.sort((a, b) => sizeOf(path.join(b, 'sessions.json')) - sizeOf(path.join(a, 'sessions.json')))[0];
|
|
5246
5300
|
|
|
5247
5301
|
if (legacyDir && !hasUserState(userDataDir)) {
|
|
@@ -5287,6 +5341,106 @@ function bootstrap() {
|
|
|
5287
5341
|
app.setPath('userData', legacyDir);
|
|
5288
5342
|
}
|
|
5289
5343
|
}
|
|
5344
|
+
|
|
5345
|
+
// The pre-unification desktop chats live in ~/.aegiscode/native-chat-history/
|
|
5346
|
+
// (one JSON file per conversation, catalogued by native-chat-index.json) —
|
|
5347
|
+
// a store nothing ever imports. The shared session-store's adopt() merges
|
|
5348
|
+
// a whole legacy sessions.json, but these are individual transcripts with
|
|
5349
|
+
// no session ids, so they need one import of their own: any file not
|
|
5350
|
+
// already represented in the shared store becomes a session, id minted by
|
|
5351
|
+
// the transcript's own timestamp, once and idempotently. No other store
|
|
5352
|
+
// in the tree reads these files, so the import makes them visible rather
|
|
5353
|
+
// than duplicating them.
|
|
5354
|
+
try {
|
|
5355
|
+
const nativeHistoryDir = path.join(os.homedir(), '.aegiscode', 'native-chat-history');
|
|
5356
|
+
const isDir = (p) => {
|
|
5357
|
+
try {
|
|
5358
|
+
return fs.statSync(p).isDirectory();
|
|
5359
|
+
} catch {
|
|
5360
|
+
return false;
|
|
5361
|
+
}
|
|
5362
|
+
};
|
|
5363
|
+
if (isDir(nativeHistoryDir)) {
|
|
5364
|
+
const entries = fs
|
|
5365
|
+
.readdirSync(nativeHistoryDir)
|
|
5366
|
+
.filter((f) => f.endsWith('.json'))
|
|
5367
|
+
.sort();
|
|
5368
|
+
const existing = new Set(
|
|
5369
|
+
(sessionStore.listSessions(sessionStore.resolveStoreDir(null)) || [])
|
|
5370
|
+
.map((s) => s && s.id)
|
|
5371
|
+
.filter(Boolean)
|
|
5372
|
+
);
|
|
5373
|
+
let adopted = 0;
|
|
5374
|
+
for (const file of entries) {
|
|
5375
|
+
let parsed = null;
|
|
5376
|
+
try {
|
|
5377
|
+
parsed = JSON.parse(fs.readFileSync(path.join(nativeHistoryDir, file), 'utf8'));
|
|
5378
|
+
} catch {
|
|
5379
|
+
/* not JSON or not readable: not a conversation */
|
|
5380
|
+
}
|
|
5381
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) continue;
|
|
5382
|
+
const marker =
|
|
5383
|
+
(typeof parsed.createdAt === 'string' && parsed.createdAt) ||
|
|
5384
|
+
(typeof parsed.created_at === 'string' && parsed.created_at) ||
|
|
5385
|
+
String(parsed.timestamp || '');
|
|
5386
|
+
if (!marker) continue;
|
|
5387
|
+
// Mint the id from the transcript's own timestamp — stable across
|
|
5388
|
+
// launches, and one id per file (duplicate timestamps get a suffix).
|
|
5389
|
+
let sessionId = `native-${marker.replace(/[^0-9T:.Z+-]/g, '')}`.slice(0, 80);
|
|
5390
|
+
if (existing.has(sessionId)) sessionId = `${sessionId}-${file.replace(/\.json$/, '').slice(-24)}`;
|
|
5391
|
+
if (existing.has(sessionId)) continue;
|
|
5392
|
+
const messages = Array.isArray(parsed.messages)
|
|
5393
|
+
? parsed.messages
|
|
5394
|
+
: parsed.history && Array.isArray(parsed.history.messages)
|
|
5395
|
+
? parsed.history.messages
|
|
5396
|
+
: parsed.history && Array.isArray(parsed.history)
|
|
5397
|
+
? parsed.history
|
|
5398
|
+
: parsed.entries && Array.isArray(parsed.entries)
|
|
5399
|
+
? parsed.entries
|
|
5400
|
+
: [];
|
|
5401
|
+
const clean = messages
|
|
5402
|
+
.map((m) => {
|
|
5403
|
+
const text =
|
|
5404
|
+
(m && (m.content || m.text)) !== undefined
|
|
5405
|
+
? m.content || m.text
|
|
5406
|
+
: m && typeof m.prompt === 'string'
|
|
5407
|
+
? m.prompt
|
|
5408
|
+
: m && typeof m.reply === 'string'
|
|
5409
|
+
? m.reply
|
|
5410
|
+
: null;
|
|
5411
|
+
if (text == null || text === '') return null;
|
|
5412
|
+
const role =
|
|
5413
|
+
m && (m.role === 'user' || m.role === 'assistant')
|
|
5414
|
+
? m.role
|
|
5415
|
+
: m && typeof m.prompt === 'string'
|
|
5416
|
+
? 'user'
|
|
5417
|
+
: m && typeof m.reply === 'string'
|
|
5418
|
+
? 'assistant'
|
|
5419
|
+
: 'unknown';
|
|
5420
|
+
return { role, content: String(text) };
|
|
5421
|
+
})
|
|
5422
|
+
.filter(Boolean);
|
|
5423
|
+
if (!clean.length) continue;
|
|
5424
|
+
const title = String(parsed.title || (parsed.session && parsed.session.title) || '').trim();
|
|
5425
|
+
sessionStore.upsertSession(sessionStore.resolveStoreDir(null), {
|
|
5426
|
+
id: sessionId,
|
|
5427
|
+
title: title || String((clean.find((m) => m.role === 'user') || {}).content || '').slice(0, 60),
|
|
5428
|
+
messages: clean,
|
|
5429
|
+
cwd: typeof parsed.cwd === 'string' ? parsed.cwd : '',
|
|
5430
|
+
updatedAt:
|
|
5431
|
+
Date.parse(parsed.updatedAt || parsed.updated_at || parsed.createdAt || parsed.created_at || 0) ||
|
|
5432
|
+
Date.now(),
|
|
5433
|
+
origin: 'native-chat',
|
|
5434
|
+
pending: false,
|
|
5435
|
+
});
|
|
5436
|
+
existing.add(sessionId);
|
|
5437
|
+
adopted += 1;
|
|
5438
|
+
}
|
|
5439
|
+
if (adopted) console.warn(`aegis: imported ${adopted} conversation(s) from ${nativeHistoryDir}`);
|
|
5440
|
+
}
|
|
5441
|
+
} catch (nativeErr) {
|
|
5442
|
+
console.warn(`aegis: native-chat import skipped: ${nativeErr && nativeErr.message}`);
|
|
5443
|
+
}
|
|
5290
5444
|
} catch (renameErr) {
|
|
5291
5445
|
console.warn(`aegis: userData adoption skipped: ${renameErr && renameErr.message}`);
|
|
5292
5446
|
}
|