aegiscode 7.0.25 → 7.0.27

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/src/models.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"),{resolveShared:resolveShared}=require("./sharedpaths.js"),{offerableCatalog:offerableCatalog}=require(resolveShared(path.join("client","brain-catalog.js"))),envFile=require(resolveShared(path.join("client","env-file.js"))),claudePro=require(resolveShared(path.join("desktop","lib","local","claude-pro.js")));function claudeProLoggedIn(){try{return!!claudePro.claudeProStatus({env:process.env}).loggedIn}catch{return!1}}const NO_PIN=null,ID_NOTES=Object.freeze({"openai-gpt4o-mini":"OpenAI gpt-4o-mini, pooled","anthropic-haiku":"Anthropic Haiku, pooled","nexus-brain":"pooled brain · multi-call fan-out, sized by /effort"});function normalizeModel(e){const o="string"==typeof e?{id:e}:e;if(!o||"object"!=typeof o)return null;const r="string"==typeof o.id?o.id.trim():"";if(!r)return null;const n="string"==typeof o.alias_of&&o.alias_of.trim()?o.alias_of.trim():null,i=Array.isArray(o.capabilities)?o.capabilities.filter((e=>"string"==typeof e&&e)):[],t={id:r,label:"string"==typeof o.label&&o.label.trim()||"string"==typeof o.name&&o.name.trim()||r,note:("string"==typeof o.note&&o.note.trim()?o.note.trim():"")||(n?`alias of ${n}`:ID_NOTES[r]||i.join(", ")),hidden:!0===o.hidden,aliasOf:n,capabilities:i};return"string"==typeof o.provider&&o.provider.trim()&&(t.provider=o.provider.trim()),!0===o.configured&&(t.configured=!0),"string"==typeof o.cls&&o.cls.trim()&&(t.cls=o.cls.trim()),t}function normalizeModelCatalog(e){const o=Array.isArray(e)?e:Array.isArray(e&&e.models)?e.models:[],r=[],n=new Set;for(const e of o){const o=normalizeModel(e);o&&!n.has(o.id)&&(n.add(o.id),r.push(o))}return r}function pickerEntries(e){const o=Array.isArray(e)?e.filter(Boolean):[],r=offerableCatalog(o).map(normalizeModel).filter(Boolean);if(r.length)return r;const n=o.filter((e=>!e.aliasOf));return n.length?n:o}function findModel(e,o){const r="string"==typeof o?o.trim():"";return r&&(Array.isArray(e)?e:[]).find((e=>e&&e.id===r))||null}function catalogIds(e){return new Set((Array.isArray(e)?e:[]).map((e=>String(e&&e.id||"").toLowerCase())).filter(Boolean))}function modelKeyPlan(e,o={}){const r=e&&e.id||"",n=envFile.keyForModelId(r,e&&e.cls);if(!n.env)return{needed:!1,env:"",provider:"",pooled:n.pooled,status:null,why:"this id has no key variable"};if(n.foreign){const e=!!envFile.resolveForeignSecret(n.env)||claudeProLoggedIn();return{needed:!e,env:n.env,provider:"",pooled:!1,status:{present:e,inFile:e,source:e?"file":"none"},why:e?`${n.env} is already set aside for Claude Code Pro`:`no ${n.env} is set aside for Claude Code Pro`}}const i=envFile.keyStatus(n.env);if(n.pooled){const e=!i.present&&!o.accountConfigured;return{needed:e,env:n.env,provider:"",pooled:!0,status:i,why:e?`no ${n.env} is set on this machine`:`account key present (${o.accountConfigured&&!i.present?"credentials.json":i.source})`}}const t=!i.inFile&&!o.hasStored;return{needed:t,env:n.env,provider:n.provider,pooled:!1,status:i,why:t?`no ${n.env} is stored for provider "${n.provider}"`:`${n.env} is already stored (${i.inFile?i.source:"provider store"})`}}function modelKeyQueue(e,o={}){const r=e&&e.id||"";if(!String(r).trim())return[];const n=envFile.keyForModelId(r,e&&e.cls);if(!n.env)return[];if(n.foreign)return envFile.resolveForeignSecret(n.env)||claudeProLoggedIn()?[]:[{env:n.env,provider:"",vendor:"",role:"claude-pro",needed:!0,status:{present:!1},why:`no ${n.env} is set aside for Claude Code Pro`}];const i=[],t=envFile.keyStatus(envFile.ACCOUNT_ENV_VAR);t.present||o.accountConfigured||i.push({env:envFile.ACCOUNT_ENV_VAR,provider:"",vendor:"",role:"account",needed:!0,status:t,why:`no ${envFile.ACCOUNT_ENV_VAR} is set on this machine`});const l=n.vendor||"",d=l?envFile.envVarFor(l):"",s=!(!l||"function"!=typeof o.hasStoredFor||!o.hasStoredFor(l));if(d){const e=envFile.keyStatus(d);e.inFile||s||i.push({env:d,provider:l,vendor:l,role:"provider",needed:!0,status:e,why:e.present?`${d} is exported in this shell only — the desktop cannot see it`:`no ${d} is stored for provider "${l}"`})}return i}function storeModelKey(e,o,r={}){const n=envFile.keyForModelId(e&&e.id,e&&e.cls),i=String(r.env||"").trim()||n.env;if(!i)return{ok:!1,file:"",changed:!1,error:`cannot name a key variable for "${e&&e.id||""}"`,env:"",provider:"",pooled:n.pooled};const t={...r};delete t.env;const l=n.foreign?envFile.setForeignSecret(i,o,t):envFile.setEnvValue(i,o,t),d=!n.foreign&&i===envFile.ACCOUNT_ENV_VAR;return{...l,env:i,provider:i===n.env?n.provider:"",pooled:d,foreign:!!n.foreign}}function keyVarForModel(e){return envFile.keyForModelId(e&&e.id,e&&e.cls).env}function providerForModel(e){const o=String(e&&e.id||"").trim();return o&&(envFile.keyForModelId(o,e&&e.cls).provider||envFile.providerForModelId(o,e&&e.cls))||""}module.exports={NO_PIN:null,ID_NOTES:ID_NOTES,normalizeModel:normalizeModel,normalizeModelCatalog:normalizeModelCatalog,pickerEntries:pickerEntries,findModel:findModel,catalogIds:catalogIds,modelKeyPlan:modelKeyPlan,modelKeyQueue:modelKeyQueue,storeModelKey:storeModelKey,keyVarForModel:keyVarForModel,providerForModel:providerForModel,claudeProLoggedIn:claudeProLoggedIn};
3
+ const e=require("node:path"),{resolveShared:r}=require("./sharedpaths.js"),{offerableCatalog:o}=require(r(e.join("client","brain-catalog.js"))),n=require(r(e.join("client","env-file.js"))),t=require(r(e.join("desktop","lib","local","claude-pro.js")));function i(){try{return!!t.claudeProStatus({env:process.env}).loggedIn}catch{return!1}}const s=Object.freeze({"openai-gpt4o-mini":"OpenAI gpt-4o-mini, pooled","anthropic-haiku":"Anthropic Haiku, pooled","nexus-brain":"pooled brain · multi-call fan-out, sized by /effort"});function d(e){const r="string"==typeof e?{id:e}:e;if(!r||"object"!=typeof r)return null;const o="string"==typeof r.id?r.id.trim():"";if(!o)return null;const n="string"==typeof r.alias_of&&r.alias_of.trim()?r.alias_of.trim():null,t=Array.isArray(r.capabilities)?r.capabilities.filter((e=>"string"==typeof e&&e)):[],i={id:o,label:"string"==typeof r.label&&r.label.trim()||"string"==typeof r.name&&r.name.trim()||o,note:("string"==typeof r.note&&r.note.trim()?r.note.trim():"")||(n?`alias of ${n}`:s[o]||t.join(", ")),hidden:!0===r.hidden,aliasOf:n,capabilities:t};return"string"==typeof r.provider&&r.provider.trim()&&(i.provider=r.provider.trim()),!0===r.configured&&(i.configured=!0),"string"==typeof r.cls&&r.cls.trim()&&(i.cls=r.cls.trim()),i}module.exports={NO_PIN:null,ID_NOTES:s,normalizeModel:d,normalizeModelCatalog:function(e){const r=Array.isArray(e)?e:Array.isArray(e&&e.models)?e.models:[],o=[],n=new Set;for(const e of r){const r=d(e);r&&!n.has(r.id)&&(n.add(r.id),o.push(r))}return o},pickerEntries:function(e){const r=Array.isArray(e)?e.filter(Boolean):[],n=o(r).map(d).filter(Boolean);if(n.length)return n;const t=r.filter((e=>!e.aliasOf));return t.length?t:r},findModel:function(e,r){const o="string"==typeof r?r.trim():"";return o&&(Array.isArray(e)?e:[]).find((e=>e&&e.id===o))||null},catalogIds:function(e){return new Set((Array.isArray(e)?e:[]).map((e=>String(e&&e.id||"").toLowerCase())).filter(Boolean))},modelKeyPlan:function(e,r={}){const o=e&&e.id||"",t=n.keyForModelId(o,e&&e.cls);if(!t.env)return{needed:!1,env:"",provider:"",pooled:t.pooled,status:null,why:"this id has no key variable"};if(t.foreign){const e=!!n.resolveForeignSecret(t.env)||i();return{needed:!e,env:t.env,provider:"",pooled:!1,status:{present:e,inFile:e,source:e?"file":"none"},why:e?`${t.env} is already set aside for Claude Code Pro`:`no ${t.env} is set aside for Claude Code Pro`}}const s=n.keyStatus(t.env);if(t.pooled){const e=!s.present&&!r.accountConfigured;return{needed:e,env:t.env,provider:"",pooled:!0,status:s,why:e?`no ${t.env} is set on this machine`:`account key present (${r.accountConfigured&&!s.present?"credentials.json":s.source})`}}const d=!s.inFile&&!r.hasStored;return{needed:d,env:t.env,provider:t.provider,pooled:!1,status:s,why:d?`no ${t.env} is stored for provider "${t.provider}"`:`${t.env} is already stored (${s.inFile?s.source:"provider store"})`}},modelKeyQueue:function(e,r={}){const o=e&&e.id||"";if(!String(o).trim())return[];const t=n.keyForModelId(o,e&&e.cls);if(!t.env)return[];if(t.foreign)return n.resolveForeignSecret(t.env)||i()?[]:[{env:t.env,provider:"",vendor:"",role:"claude-pro",needed:!0,status:{present:!1},why:`no ${t.env} is set aside for Claude Code Pro`}];const s=[],d=n.keyStatus(n.ACCOUNT_ENV_VAR);d.present||r.accountConfigured||s.push({env:n.ACCOUNT_ENV_VAR,provider:"",vendor:"",role:"account",needed:!0,status:d,why:`no ${n.ACCOUNT_ENV_VAR} is set on this machine`});const l=t.vendor||"",a=l?n.envVarFor(l):"",c=!(!l||"function"!=typeof r.hasStoredFor||!r.hasStoredFor(l));if(a){const e=n.keyStatus(a);e.inFile||c||s.push({env:a,provider:l,vendor:l,role:"provider",needed:!0,status:e,why:e.present?`${a} is exported in this shell only — the desktop cannot see it`:`no ${a} is stored for provider "${l}"`})}return s},storeModelKey:function(e,r,o={}){const t=n.keyForModelId(e&&e.id,e&&e.cls),i=String(o.env||"").trim()||t.env;if(!i)return{ok:!1,file:"",changed:!1,error:`cannot name a key variable for "${e&&e.id||""}"`,env:"",provider:"",pooled:t.pooled};const s={...o};delete s.env;const d=t.foreign?n.setForeignSecret(i,r,s):n.setEnvValue(i,r,s),l=!t.foreign&&i===n.ACCOUNT_ENV_VAR;return{...d,env:i,provider:i===t.env?t.provider:"",pooled:l,foreign:!!t.foreign}},keyVarForModel:function(e){return n.keyForModelId(e&&e.id,e&&e.cls).env},providerForModel:function(e){const r=String(e&&e.id||"").trim();return r&&(n.keyForModelId(r,e&&e.cls).provider||n.providerForModelId(r,e&&e.cls))||""},claudeProLoggedIn:i};
package/src/panels.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{span:span,getSize:getSize,lineWidth:lineWidth}=require("./screen.js"),{themeOf:themeOf,BOLD:BOLD,BOLD_OFF:BOLD_OFF,GLYPH:GLYPH}=require("./theme.js"),{goUrl:goUrl}=require("./signup.js"),{cwdName:cwdName,pathName:pathName}=require("./format.js"),VERSION=require("../package.json").version;function num(s){const e=Number(s);return Number.isFinite(e)?e:0}function str(s){return null==s?"":String(s)}function wrapRows(s,e,n,a){const t=Math.max(20,(Number(a)||80)-2-e),o=" ".repeat(e),r=str(s).split(/\s+/).filter(Boolean),p=[];let i="";for(const s of r){const e=i?`${i} ${s}`:s;i&&e.length>t?(p.push([span("",o),span(n,i)]),i=s):i=e}return i&&p.push([span("",o),span(n,i)]),p.length?p:[[span("",o),span(n,"")]]}function tokenBuckets(s){const e=num(s.input),n=num(s.output),a=num(s.cacheRead),t=num(s.cacheWrite),o=e+a+t;return{input:e,output:n,cacheRead:a,cacheWrite:t,prompt:o,total:num(s.total)||o+n}}function fmtTokens(s){const e=Number(s);return!Number.isFinite(e)||e<=0?"0":Math.round(e).toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}function fmtEur(s){const e=Number(s);if(!Number.isFinite(e))return"€?";const n=Math.abs(e);return`€${n<.01?n.toFixed(4):n.toFixed(2)}`}function ago(s){if(!s)return"";const e=Date.now()-new Date(String(s)).getTime();return e>=0&&!Number.isNaN(e)?e<6e4?`${Math.max(1,Math.round(e/1e3))}s ago`:e<36e5?`${Math.round(e/6e4)}m ago`:e<864e5?`${Math.round(e/36e5)}h ago`:`${Math.round(e/864e5)}d ago`:""}function contextBar(s,e,n,a=50){const t=Math.max(0,Math.min(1,e>0?num(s)/e:0)),o=Math.round(t*a);return[span(""," "),span(n.green,"█".repeat(o)),span(n.dim,"█".repeat(Math.max(0,a-o))),span(n.gray,` ${Math.round(100*t)}% used`)]}function kv(s,e,{indent:n=" ",keyStyle:a=null,valStyle:t=null}={}){const o=e.reduce(((s,e)=>Math.max(s,[...e[0]].length)),0);return e.map((([e,r])=>[span(null!=a?a:s.gray,n+e+" ".repeat(o-[...e].length)+" : "),span(null!=t?t:s.white,str(r))]))}function obj(s){return s&&"object"==typeof s?s:{}}function statsFrom(s){const e=obj(s);return e.stats&&"object"==typeof e.stats?e.stats:e.memory&&"object"==typeof e.memory&&(null!=e.memory.total||e.memory.tiers||null!=e.memory.sessions||e.memory.roles)?e.memory:null!=e.total||e.tiers||e.roles?e:null}const CATEGORY_LABELS={session:"Session & context",workspace:"Workspace",model:"Model & behavior",data:"Data",auth:"Auth",support:"Support",fun:"Fun",aegis:"Aegis plugin",custom:"Custom"};function categoryLabel(s){if(s&&s.categoryLabel)return String(s.categoryLabel);const e=str(s&&s.category);return CATEGORY_LABELS[e]?CATEGORY_LABELS[e]:e?e.charAt(0).toUpperCase()+e.slice(1):"Commands"}function buildHelp(s,e={}){const n=themeOf(e),a=Array.isArray(s)?s:Array.isArray(obj(s).commands)?s.commands:[],t=[];t.push([span(n.gold+BOLD,"Commands"),span(BOLD_OFF,"")]),t.push([span(n.gray,"─".repeat(30))]);let o=null;for(const s of a){if(!s||!s.name)continue;const e=str(s.category);e!==o&&(t.push([span("","")]),t.push([span(n.gray+BOLD,categoryLabel(s)),span(BOLD_OFF,"")]),o=e);const a=String(s.name),r=" ".repeat(Math.max(1,16-[...a].length)),p=str(null!=s.desc?s.desc:s.help),i=s.unavailable?n.gray:n.white,u=s.unavailable?n.dim:n.gray,l=s.unavailable?" (unavailable)":"";t.push([span(i,"/"+a),span(u,r+p+l)])}return a.length||(t.push([span("","")]),t.push([span(n.gray,"No commands registered.")])),t.push([span("","")]),t.push([span(n.gray,"Shortcuts: "),span(n.white,"?"),span(n.gray," · "),span(n.white,"/help"),span(n.gray," commands · "),span(n.white,"↑↓"),span(n.gray," history · "),span(n.white,"Ctrl-L"),span(n.gray," clear · "),span(n.white,"Ctrl-D"),span(n.gray," exit")]),t}function buildStatus(s,e={}){const n=themeOf(e),a=obj(s),t=[];t.push([span(n.gold+BOLD,"Status"),span(BOLD_OFF,"")]);const o=[],r=(s,e)=>{const n=str(e);""!==n&&o.push([s,n])};r("Session ID",a.sessionId),r("Working directory",a.cwd),r("Home",a.home),r("Model",a.model),r("Effort",a.effort||"high"),null!=a.thinking&&r("Thinking",a.thinking?"on":"off"),null!=a.stream&&r("Streaming",!1===a.stream?"off":"on"),null!=a.vim&&r("Vim keymap",a.vim?"on":"off"),r("Theme",a.theme?str(a.theme):e&&e.light?"Light mode":"Dark mode"),r("Backend",a.backend),r("Base",a.base),r("Plan",a.plan),r("Account",a.account),null!=a.online&&r("Online",a.online?"yes":"no"),null!=a.turns&&r("Turns",str(num(a.turns))),null!=a.calls&&r("Tool calls",str(num(a.calls))),null!=a.version&&r("Version","v"+str(a.version)),r("Node",process.version),r("Platform",`${process.platform} ${process.arch}`);const p=Array.isArray(e.caps)?e.caps:[],i=s=>{const e=p.find((e=>Array.isArray(e)&&String(e[0])===s));return e?str(e[1]):""};r("Terminal",i("terminal")),r("Mark",i("mark")),r("Star",i("star")),r("Color",i("color")),r("Control",i("control")),r("Frame",i("size"));for(const s of kv(n,o,{keyStyle:n.gray,valStyle:n.white}))t.push(s);t.push([span("","")]);const u=a.permissions&&a.permissions.mode?str(a.permissions.mode):"default";return t.push([span(n.gray,`Permissions: ${u} — tool use follows your AEGIS settings.`)]),t}function buildCost(s,e={}){const n=themeOf(e),a=obj(s),{cols:t}=getSize(),o=Math.max(30,t-2),r=a.tokens&&"object"==typeof a.tokens?a.tokens:{},{input:p,output:i,cacheRead:u,cacheWrite:l,prompt:h,total:c}=tokenBuckets(r),d=num(a.costEur),m=str(a.model)||"the pinned model",g=num(a.contextWindow)||2e5,y=g>0?Math.min(100,Math.round(c/g*100)):0,f=[];return f.push([span(n.gray,"─".repeat(o))]),f.push([span(""," "),span(n.white+BOLD,"Session"),span(BOLD_OFF,""),span(n.gray," Status Config Usage Stats")]),f.push([span(""," "),span(n.gray,"Session")]),f.push([span(""," "),span(n.white,"Total cost:"),span(n.gray," "+" ".repeat(Math.max(0,14-fmtEur(d).length))+fmtEur(d))]),null!=a.balance&&f.push([span(""," "),span(n.white,"Balance:"),span(n.gray," "+" ".repeat(Math.max(0,14-fmtEur(a.balance).length))+fmtEur(a.balance))]),null==a.turns&&null==a.calls||f.push([span(""," "),span(n.white,"Turns:"),span(n.gray,` ${num(a.turns)} turns · ${num(a.calls)} calls`)]),f.push([span(""," "),span(n.white," Usage by model:")]),f.push([span(""," "),span(n.gray,` ${m}: ${fmtTokens(h)} input, ${fmtTokens(i)} output (${fmtEur(d)})`)]),(u||l)&&f.push([span(""," "),span(n.dim,` ↳ miss ${fmtTokens(p)} · cache read ${fmtTokens(u)} · cache write ${fmtTokens(l)}`)]),f.push([span(""," ")]),f.push([span(""," "),span(n.white+BOLD,"Current session"),span(BOLD_OFF,"")]),f.push(contextBar(c,g,n)),f.push([span(""," ")]),f.push([span(""," "),span(n.gray,`Session context: ${y}% of ${fmtTokens(g)} used.`)]),f.push([span(""," "),span(n.dim,"Cost is metered from the AEGIS token bank; tokens are counted this session.")]),f}function buildContext(s,e={}){const n=themeOf(e),a=obj(s),{cols:t}=getSize(),o=Math.max(30,t-2),r=a.tokens&&"object"==typeof a.tokens?a.tokens:{},{input:p,output:i,cacheRead:u,cacheWrite:l,prompt:h,total:c}=tokenBuckets(r),d=num(a.contextWindow)||2e5,m=[];m.push([span(n.gold+BOLD,"Context usage"),span(BOLD_OFF,"")]),m.push([span(""," "),span(n.gray,"─".repeat(Math.max(1,o-2)))]);const g=(s,e)=>[span(""," "),span(n.white,s),span(""," ".repeat(Math.max(1,16-[...s].length))),span(n.gray,fmtTokens(e)),span(""," ".repeat(Math.max(1,10-fmtTokens(e).length))),...contextBar(e,d,n)];return m.push(g("Prompt tokens",h)),(u||l)&&m.push([span(""," "),span(n.dim,` ↳ miss ${fmtTokens(p)} · cache read ${fmtTokens(u)} · cache write ${fmtTokens(l)}`)]),m.push(g("Output tokens",i)),m.push([span(""," ")]),m.push([span(""," "),span(n.gray,"─".repeat(Math.max(1,o-2)))]),m.push([span(""," "),span(n.white+BOLD,"Total"),span(""," ".repeat(9)),span(n.gray,fmtTokens(c)),span(""," ".repeat(Math.max(1,10-fmtTokens(c).length))),...contextBar(c,d,n)]),m.push([span(""," ")]),m.push([span(""," "),span(n.gray,`Context window: ${fmtTokens(d)} tokens`)]),m}function renderSessionsOverlay(s,e,n,a={}){const t=themeOf(a),o=obj(s),r=Math.max(30,num(e)?num(e)-4:76),p=str(o.version),i=str(o.model)||"default model",u=cwdName(o.cwd),l=Array.isArray(o.sessions)?o.sessions.filter(Boolean):[],h=l.filter((s=>s.awaiting||s.needsInput)).length,c=l.filter((s=>s.working)).length,d=l.filter((s=>s.completed)).length,m=s=>[span(t.gray,"│"),span(""," "),...s,span(""," ".repeat(Math.max(0,r-1-lineWidth(s)))),span(t.gray,"│")],g=[];return g.push([span(t.coral,"╭─── Aegiscode v"+p+" "+"─".repeat(Math.max(0,r-24))+"╮")]),g.push(m([span(t.white,i),span(t.gray," · "),span(t.white,u)])),g.push(m([span(t.gray,`${h} awaiting input · ${c} working · ${d} completed`)])),g.push([span(t.gray,"├"+"─".repeat(r)+"┤")]),g.push(m([span(t.white+BOLD,"Needs input"),span(BOLD_OFF,"")])),g.push(m([span(t.gray,"Sessions that have a question or need your decision land here")])),g.push(m([span(t.coral,GLYPH.bloom),span(t.gray," current session send a prompt to start "),span(t.gray,"—")])),g.push(m([span(t.white+BOLD,"Working"),span(BOLD_OFF,"")])),g.push(m([span(t.gray,"Sessions AEGIS is actively working on — they keep running even if you close the terminal")])),g.push(m([span(t.white+BOLD,"Completed"),span(BOLD_OFF,"")])),g.push(m([span(t.gray,"Finished sessions wait here for you to review")])),g.push([span(t.gray,"╰"+"─".repeat(r)+"╯")]),g.push([span(""," "),span(t.gray,"Sub-agents that keep working in the background need a local agent loop;")]),g.push([span(""," "),span(t.gray,"this build hands a bigger task to the pooled brain instead.")]),g}function buildAgents(s,e={}){const{cols:n,rows:a}=getSize();return renderSessionsOverlay(s,n,a,e)}function buildPermissions(s,e,n={}){const a=themeOf(n),t=obj(s),o=s=>Array.isArray(s)?s:[],r=null!=e&&""!==e?String(e):null!=t.defaultMode?String(t.defaultMode):"default",p=[];p.push([span(a.gold+BOLD,"Permissions"),span(BOLD_OFF,"")]),p.push([span(""," "),span(a.gray,"Default mode: "),span(a.white,r)]),p.push([span(""," ")]);const i=(s,e)=>{const n=[[span(""," "),span(a.white+BOLD,s),span(BOLD_OFF,"")]];e.length||n.push([span(""," "),span(a.gray,"(none)")]);for(const s of e)n.push([span(""," "),span(a.gray,str(s))]);return n};for(const s of i("Allow",o(t.allow)))p.push(s);for(const s of i("Deny",o(t.deny)))p.push(s);for(const s of i("Ask",o(t.ask)))p.push(s);return p.push([span("","")]),p.push([span(a.gray,"Usage:")]),p.push([span(a.gray,' /permissions allow "Bash(npm run *)"')]),p.push([span(a.gray,' /permissions deny "Edit(src/**)"')]),p.push([span(a.gray,' /permissions ask "Read(**/*.env)"')]),p.push([span(a.gray," /permissions default ask · /permissions clear")]),p.push([span("","")]),p.push([span(a.dim,`Stored in ${str(t._path)||"~/.aegiscode/permissions.json"}`)]),p}function buildModelList(s,e,n={}){const a=themeOf(n),t=Array.isArray(e)?e:[],o=str(s),r=s=>s.cls?"byok"===s.cls:"byok"===n.modelClass,p=t.some(r),i=[];i.push([span(a.gold+BOLD,"Models"),span(BOLD_OFF,"")]),i.push([span(a.gray,"─".repeat(30))]);for(const s of t){if(!s)continue;const e=str(s.id)||str(s.model),n=(""!==e&&e===o?"▶ ":" ")+e,t=str(s.name||s.label||s.model),p=r(s)?str(s.note)||str(s.model):str(s.model)||"(default)";i.push([span(a.white,n),span(""," ".repeat(Math.max(1,26-[...n].length))),span(a.gray,t),span(""," ".repeat(Math.max(1,22-[...t].length))),span(a.gray,p)])}return t.length||i.push([span(""," "),span(a.gray,"(no models configured)")]),i.push([span("","")]),i.push([span(a.gray,p?"Switch: /model <id> · Add a provider key: /byok-key <provider> · Run on it: /class byok":"Switch: /model <id> · Add: /model add <id> <name> <model> <baseURL> [apiKey] · Remove: /model remove <id>")]),i}function buildRewindList(s,e={}){const n=themeOf(e),a=Array.isArray(s)?s:[],t=[];t.push([span(n.gold+BOLD,"Rewind"),span(BOLD_OFF,"")]),t.push([span(""," "),span(n.gray,"Snapshots are taken after every exchange.")]),t.push([span(""," ")]);for(const s of a){if(!s)continue;const e=str(num(s.idx));t.push([span(""," "),span(n.green,e),span(""," ".repeat(Math.max(1,4-[...e].length))),span(n.white,`${num(s.depth)} messages`),span(n.gray,` · ${num(s.words)} words · ${ago(s.ts)}`)])}return a.length||t.push([span(""," "),span(n.gray,"(no checkpoints)")]),t.push([span("","")]),t.push([span(n.gray,"Usage: /rewind N to restore that checkpoint (0 = session start)")]),t}function buildHooksStatus(s,e={}){const n=themeOf(e),a=obj(s),t=Array.isArray(a.events)?a.events:[],o=a.byEvent&&"object"==typeof a.byEvent?a.byEvent:{},r=Array.isArray(a.fromPaths)?a.fromPaths:Array.isArray(a.sources)?a.sources:[],p=[];p.push([span(n.gold+BOLD,"Hooks status"),span(BOLD_OFF,"")]);const i=[["status",a.enabled?"enabled":"disabled"],["hooks",str(num(a.hooks))],["events",str(t.length)]];for(const s of kv(n,i,{keyStyle:n.gray,valStyle:n.white}))p.push(s);if(num(a.hooks)>0){p.push([span("","")]),p.push([span(""," "),span(n.white+BOLD,"by event"),span(BOLD_OFF,"")]);for(const[s,e]of Object.entries(o))p.push([span(""," "),span(n.green,GLYPH.bullet),span(n.white,` ${s}`),span(n.gray,` ${num(e)}`)])}return p.push([span("","")]),p.push([span(n.gray,"/hooks list for full config")]),p.push([span("","")]),p.push([span(n.dim,r.length?`Settings: ${r.join(", ")}`:"Settings: no settings.json with hooks found (checked ~/.aegis, .aegis, ~/.aegiscode, .aegiscode, ~/.claude)")]),p.push([span(n.gray,"Config hooks are read, not managed — edit the files above.")]),p.push([span(n.gray,"The repo guard hooks (.githooks/) are installed by /hooks install.")]),p}function buildHooksList(s,e={}){const n=themeOf(e),a=obj(s),t=a.hooks&&"object"==typeof a.hooks?a.hooks:{},o=[];o.push([span(n.gold+BOLD,"Hooks config"),span(BOLD_OFF,"")]);let r=!1;for(const[s,e]of Object.entries(t))if(Array.isArray(e)&&0!==e.length){r=!0,o.push([span("","")]),o.push([span(""," "),span(n.white+BOLD,s),span(BOLD_OFF,"")]);for(const s of e)s&&(o.push([span(""," "),span(n.lavender,str(s.name)||"(unnamed)")]),s.matcher&&(s.matcher.tools&&o.push([span(""," - tools: "),span(n.gray,str(s.matcher.tools))]),s.matcher.paths&&o.push([span(""," - paths: "),span(n.gray,str(s.matcher.paths))]),s.matcher.commands&&o.push([span(""," - commands: "),span(n.gray,str(s.matcher.commands))])),o.push([span("",` - hooks: ${Array.isArray(s.hooks)?s.hooks.length:0}`)]),o.push([span("","")]))}return r?(o.push([span("","")]),o.push([span(n.gray,"/hooks status for the summary")])):(o.push([span(""," "),span(n.gray,"no hooks configured.")]),o.push([span("","")]),o.push([span(""," "),span(n.gray,"add hooks to settings.json:")]),o.push([span(""," "),span(n.gray,"- ~/.aegis/settings.json (user)")]),o.push([span(""," "),span(n.gray,"- .aegis/settings.json (project)")])),o}function buildTroubleshooting(s,e={}){const n=themeOf(e),a=[];a.push([span(n.gold+BOLD,"Troubleshooting"),span(BOLD_OFF,"")]);const t=[["No output / blank screen","Run with TERM=xterm-256color, or switch to a lighter theme (/theme light)."],["Keys not responding","This client needs a real TTY — run it from a terminal, not a CI job."],["401 / unauthorized","Check the account line with /status, or set a provider key with /byok-set."],["No answers from the brain","Confirm the token-bank balance with /billing."],["Memory looks empty","Recall is per-topic — try /aegis-recall <topic> or save one with /aegis-remember <note>."]];for(const[s,e]of t)a.push([span(n.green,GLYPH.bullet),span(n.white," "+s)]),a.push([span(""," "),span(n.gray,e)]);return a.push([span("","")]),a.push([span(n.gray,"Run /status for account state. Help: https://aegiscloud.org")]),a}function buildOnboarding(s,e={}){const n=themeOf(e),a=[];a.push([span(n.gold+BOLD,"Getting started"),span(BOLD_OFF,"")]);const t=[["/help","list every command"],["/","open the command palette"],["?","shortcuts"],["/model <id>","pin a model"],["/theme light|dark","switch the colour theme"],["/aegis-ask","ask the pooled brain a question"],["/memory","show your AEGIS cloud memory"],["Ctrl-D","exit"]];for(const[s,e]of t)a.push([span(""," "),span(n.lavender,s),span(""," ".repeat(Math.max(1,20-[...s].length))),span(n.gray,e)]);return a.push([span("","")]),a.push([span(n.gray,'Try "summarize this file for me" to see the full flow.')]),a}function buildShellCompletion(s,e={}){const n=themeOf(e),a=[];a.push([span(n.gold+BOLD,"Shell completion"),span(BOLD_OFF,"")]),a.push([span(""," "),span(n.gray,"Aegiscode completes /commands with Tab inside the app.")]),a.push([span(""," "),span(n.gray,"For shell-level completion of the aegiscode CLI itself:")]),a.push([span(""," ")]);const t=[["bash",'eval "$(aegiscode shell-completion bash)"'],["zsh",'eval "$(aegiscode shell-completion zsh)"'],["fish","aegiscode shell-completion fish | source"]];for(const[s,e]of t)a.push([span(""," "),span(n.white+BOLD,s),span(""," ".repeat(Math.max(1,6-s.length))),span(n.gray,e)]);return a.push([span("","")]),a.push([span(n.dim,"Add the eval line to your ~/.bashrc or ~/.zshrc to make it persist.")]),a}function buildTerminalSetup(s,e={}){const n=themeOf(e),a=obj(s),t="undefined"!=typeof process&&process.env?process.env:{},{cols:o,rows:r}=getSize(),p=str(a.shell)||pathName(str(t.SHELL)),i=[["TERM",str(a.term)||str(t.TERM)||"(unset)"],["LANG",str(a.lang)||str(t.LANG)||"(unset)"],["Shell",p||"unknown"],["Size",`${o}x${r}`]],u=[];u.push([span(n.gold+BOLD,"Terminal setup"),span(BOLD_OFF,"")]);for(const s of kv(n,i,{keyStyle:n.white,valStyle:n.gray}))u.push(s);return u.push([span("","")]),u.push([span(n.gray,"Tips:")]),u.push([span(n.gray," • TERM=xterm-256color enables full color + resize handling")]),u.push([span(n.gray," • Set LANG (e.g. en_US.UTF-8) for correct glyphs and word wrap")]),u.push([span(n.gray," • Resize mid-session is handled (SIGWINCH); overlays adapt")]),u}function buildTerminalCaps(s,e={}){const n=themeOf(e),a=(Array.isArray(s)?s:[]).filter((s=>Array.isArray(s)&&s.length>=2)).map((([s,e])=>[str(s),str(e)])),t=[];if(t.push([span(n.gold+BOLD,"Terminal capabilities"),span(BOLD_OFF,"")]),!a.length)return t.push([span(""," "),span(n.gray,"No capability report available.")]),t;for(const s of kv(n,a,{keyStyle:n.white,valStyle:n.gray}))t.push(s);return t.push([span("","")]),e&&e.pinned&&(t.push([span(n.coral,GLYPH.warn),span(n.gold," width is pinned — resizes are ignored until /terminal auto")]),t.push([span("","")])),t.push([span(n.gray,"Override: /terminal ascii | unicode | color | no-color | background <dark|light> | star <native|narrow>")]),t.push([span(n.gray," /terminal width <cols> | auto | status")]),t.push([span(n.gray,"At launch: --ascii --unicode --no-color --width <cols> --terminal")]),t}function buildPRs(s,e={}){const n=themeOf(e),a=[];a.push([span(n.gold+BOLD,"Open pull requests"),span(BOLD_OFF,"")]);const t=str(s).trim();if(!t)return a.push([span(""," "),span(n.gray,"No open PRs in this repository.")]),a;for(const s of t.split("\n").slice(0,10))a.push([span(""," "),span(n.white,s)]);return a.push([span("","")]),a.push([span(n.gray,"Review with /review · comments via /pr-comments")]),a}function buildBenchmark(s,e={}){const n=themeOf(e),a=Array.isArray(s)?s:[],t=[];t.push([span(n.gold+BOLD,"Benchmark"),span(BOLD_OFF,"")]),t.push([span(""," "),span(n.gray,"In-app micro-benchmarks (this process, this machine):")]),t.push([span(""," ")]);for(const s of a){if(!Array.isArray(s)||s.length<2)continue;const e=str(s[0]);t.push([span(""," "),span(n.white,e),span(""," ".repeat(Math.max(1,30-[...e].length))),span(n.gray,`${num(s[1])} ms`)])}return a.length||t.push([span(""," "),span(n.gray,"(no benchmarks run)")]),t.push([span("","")]),t.push([span(n.dim,"Spoiler: the terminal renders faster than you type.")]),t}const WAIFU_ART=[" ▄▄▄▄▄▄▄▄▄▄▄▄"," ▄█▓▓▓▓▓▓▓▓▓▓▓▓█▄"," █▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█"," █▓▓▓█▓▓▓▓▓▓▓█▓▓▓█"," █▓▓█▓▓█▓▓▓█▓▓█▓▓█"," █▓▓█▓█▓▓▓█▓█▓▓█"," █▓▓▓█▓▓▓█▓▓▓█"," ██▓▓▓▓▓▓▓▓▓▓▓▓▓██"," █▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█"," █▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█"," █▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█"," ▀█▓▓▓▓▓▓▓▓▓▓▓▓▓█▀"," ▀▀▀███████▀▀▀"];function buildWaifu(s={}){const e=themeOf(s),n=[];n.push([span(e.gold+BOLD,"Waifu"),span(BOLD_OFF,"")]);for(const s of WAIFU_ART)n.push([span(e.lavender,s)]);return n.push([span("","")]),n.push([span(e.gray,"A distinguished gentleman, rendered in block characters.")]),n}function buildAegisStatus(s,e={}){const n=themeOf(e),a=obj(s),t=statsFrom(a),o=a.cloud&&"object"==typeof a.cloud?a.cloud:null,r=str(a.cloudNote),p=str(a.version),i=str(a.backend||a.store),u=[];u.push([span(n.gold+BOLD,"ÆGIS Status"),span(BOLD_OFF,"")]),u.push([span(n.gray,"─".repeat(30))]);const l=t?num(t.total):0,h=t?num(t.sessions):0;if(u.push([span(n.white,`Memory: ${l.toLocaleString()} entries across ${h} sessions`)]),t&&t.roles&&(null!=t.roles.user||null!=t.roles.assistant)){const s=t.roles,e=[];null!=s.user&&e.push(`${num(s.user)} user`),null!=s.assistant&&e.push(`${num(s.assistant)} assistant`),s.other&&e.push(`${num(s.other)} other`),e.length&&u.push([span(n.gray,` roles: ${e.join(" · ")}`)])}if(t&&t.tiers&&u.push([span(n.gray,` tiers: ${JSON.stringify(t.tiers)}`)]),i&&u.push([span(n.gray,` store: ${i}`)]),t&&null!=t.total){const s=num(t.withEmbeddings),e=l?Math.round(s/l*100):0;if(!0===t.embeddingsEnabled){const s=t.embeddingModels&&Object.keys(t.embeddingModels)[0]||"embedding";u.push([span(n.gray,` embed: ${s} · ${e}% coverage`)])}else!1===t.embeddingsEnabled&&l&&u.push([span(n.gray," embed: keyword-only")]);t.stale&&u.push([span(n.gray,` stale: ${num(t.stale)} entries >90d`)])}if(o){const s=o.key?"✓ connected":"✗ no API key",e=o.sync?"sync on":"sync off";u.push([span(n.white,`Cloud: ${s}, ${e}`)])}else r?u.push([span(n.gray,`Cloud: ${r}`)]):u.push([span(n.gray,"Cloud: not checked (aegis /cloud status unavailable)")]);return p&&u.push([span(n.gray,`CLI: aegis ${p}`)]),u}function buildAegisRecall(s,e={}){const n=themeOf(e),a=Array.isArray(s)?s.filter(Boolean):[],t=[];if(t.push([span(n.gold+BOLD,"ÆGIS Memory"),span(BOLD_OFF,"")]),t.push([span(n.gray,"─".repeat(30))]),!a.length)return t.push([span(n.gray,"No memory found for this topic.")]),t.push([span(n.gray,"Nothing relevant is stored yet — /aegis-remember <note> saves one.")]),t;for(const s of a.slice(0,10)){const e=str(s.content).split("\n")[0].slice(0,90);t.push([span(n.white+BOLD,`• ${e}`),span(BOLD_OFF,"")]);const a=s.timestamp?str(s.timestamp).slice(0,10):"",o=s.source?` (${str(s.source)})`:"",r=Array.isArray(s.tags)&&s.tags.length?" · tags: "+s.tags.join(", "):"";t.push([span(n.gray,` ${a}${o}${r}`)])}return a.length>10&&t.push([span(n.gray,`…and ${a.length-10} more`)]),t}function buildAegisMulti(s,e={}){const n=themeOf(e),a=str(s),t=[];return t.push([span(n.gold+BOLD,"ÆGIS Multi — compose"),span(BOLD_OFF,"")]),t.push([span(n.gray,"─".repeat(30))]),t.push([span(n.gray,"Paste into your aegis-cli session (the confirmation prompt works there):")]),t.push([span(n.white,` /multi ${a}`)]),t.push([span(n.gray," /multiyolo "+a+" — auto-approved variant")]),t.push([span("","")]),t.push([span(n.gray,"Optional flags: --save-as <name> · --template <id>")]),t.push([span(n.gray,'Add "run" to execute headless here instead: /aegis-multi <task> run')]),t}function buildAegisPrint(s,e={},n={}){const a=themeOf(n),t=obj(e),o=[];o.push([span(a.gold+BOLD,str(s)),span(BOLD_OFF,"")]),o.push([span(a.gray,"─".repeat(30))]);for(const s of str(t.result).split("\n"))o.push([span(a.white,s)]);return(t.model||t.provider)&&o.push([span(a.gray,` via ${str(t.provider)||"aegis"}${t.model?" · "+str(t.model):""}`)]),o}function buildBilling(s,e={}){const n=themeOf(e),a=obj(s),t=[];t.push([span(n.gold+BOLD,"Billing"),span(BOLD_OFF,"")]),t.push([span(n.gray,"─".repeat(30))]);const o=[];if(null!=a.balance&&o.push(["Balance",fmtEur(a.balance)]),null!=a.plan&&o.push(["Plan",str(a.plan)]),null!=a.account&&o.push(["Account",str(a.account)]),null!=a.costEur&&o.push(["This session",fmtEur(a.costEur)]),o.length)for(const s of kv(n,o,{indent:" ",keyStyle:n.gray,valStyle:n.white}))t.push(s);else t.push([span(""," "),span(n.gray,"No billing data available.")]);t.push([span("","")]),t.push([span(n.white,"AEGIS pooled inference"),span(n.gray," metered against your token bank")]);const r=a.payment&&"object"==typeof a.payment?a.payment:null;if(r){const{cols:s}=getSize(),e=r.paid?"✔":"✦";t.push(...wrapRows(`${e} ${str(r.label)||"Unlimited"}: ${str(r.reason)}`,2,r.paid?n.green:n.gold,s)),t.push(...wrapRows(str(r.honesty),2,n.gray,s)),!r.paid&&r.unlock&&t.push(...wrapRows(str(r.unlock),2,n.gray,s)),r.byok&&t.push(...wrapRows(str(r.byok),2,n.gray,s)),!1===r.verified&&t.push(...wrapRows("(account not confirmed this session — verdict may be stale)",2,n.gray,s)),r.url&&t.push([span(""," "),span(n.gray,str(r.url))])}else t.push([span(n.gray,` Top-ups and invoices: ${goUrl("topup","cost_screen")}`)]);return t}function buildTokens(s,e={}){const n=themeOf(e),a=obj(s),{cols:t}=getSize(),o=Math.max(24,t-2),r=a.tokens&&"object"==typeof a.tokens?a.tokens:{},{input:p,output:i,cacheRead:u,cacheWrite:l,total:h}=tokenBuckets(r),c=num(a.costEur),d=num(a.contextWindow)||2e5,m=d>0?Math.min(100,Math.round(h/d*100)):0,g=[];g.push([span(n.gold+BOLD,"Token usage"),span(BOLD_OFF,"")]),g.push([span(n.gray,"─".repeat(Math.min(30,o)))]);const y=Math.max(p,i,u,l,1),f=(s,e)=>{const a=Math.min(1,e/y),t=Math.max(0,Math.round(24*a));return[span(""," "),span(n.white,s),span(""," ".repeat(Math.max(1,11-[...s].length))),span(n.green,"█".repeat(t)),span(n.dim,"█".repeat(Math.max(0,24-t))),span(n.gray,` ${fmtTokens(e)}`)]};return g.push(f("input",p)),g.push(f("output",i)),g.push(f("cache read",u)),g.push(f("cache write",l)),g.push([span(""," ")]),g.push([span(""," "),span(n.white,"Total:"),span(n.gray,` ${fmtTokens(h)}`),span(""," ".repeat(8)),span(n.white,"Est. cost:"),span(n.gray,` ${fmtEur(c)}`)]),g.push([span(""," "),span(n.gray,`Context: ${m}% of ${fmtTokens(d)} window`)]),g.push([span(""," "),span(n.gray,"Tokens are counted from this session; cost is metered in euro.")]),g}function buildSkills(s,e,n={}){const a=themeOf(n),t=Array.isArray(s)?s.filter(Boolean):[],o=Array.isArray(e)?e:[],r=[];if(r.push([span(a.gold+BOLD,"Skills"),span(BOLD_OFF,"")]),r.push([span(a.gray,"─".repeat(30))]),!t.length){r.push([span(a.gray,"No skills found.")]),r.push([span(a.gray,"Skill dirs scanned:")]);for(const s of o)r.push([span(a.dim,` ${str(s)}`)]);return r.push([span("","")]),r.push([span(a.gray,"Add one: mkdir -p .aegis/skills/<name> and drop a SKILL.md inside.")]),r}let p=null;for(const s of t){s.source!==p&&(r.push([span(a.gray+BOLD,"user"===s.source?"User":"Project"),span(BOLD_OFF,"")]),p=s.source);const e=s.namespace?`${str(s.namespace)}/${str(s.name)}`:str(s.name),n=str(s.description)||"(no description)";r.push([span(a.white,` ${e}`),span(a.gray," ".repeat(Math.max(1,18-[...e].length))+n)])}return r.push([span("","")]),r.push([span(a.gray,"/skills <name> for details · /skills refresh to rescan")]),r}function buildSkillDetail(s,e={}){const n=themeOf(e),a=obj(s),t=a.namespace?`${str(a.namespace)}/${str(a.name)}`:str(a.name),o=[];o.push([span(n.gold+BOLD,`Skill: ${t}`),span(BOLD_OFF,"")]),o.push([span(n.gray,"─".repeat(30))]),a.description&&o.push([span(n.gray,str(a.description))]),o.push([span(n.dim,str(a.path))]),o.push([span("","")]);const r=str(a.content).split("\n"),p=r.slice(0,8).join("\n");for(const s of p.split("\n"))o.push([span(n.white,s)]);return r.length>8&&o.push([span(n.gray,`… (${r.length} lines)`)]),o}function buildMcp(s,e,n={}){const a=themeOf(n),t=Array.isArray(s)?s.map(((s,e)=>[str(s&&s.name)||String(e),s])):s&&"object"==typeof s?Object.entries(s):[],o=Array.isArray(e)?e:[],r=[];if(r.push([span(a.gold+BOLD,"MCP servers"),span(BOLD_OFF,"")]),r.push([span(a.gray,"─".repeat(30))]),t.length)for(const[s,e]of t){const n="string"==typeof e?e:(str(e&&e.command)+" "+(Array.isArray(e&&e.args)?e.args.join(" "):"")).trim();r.push([span(a.white,` ${str(s)}`),span(a.gray," ".repeat(Math.max(1,14-[...str(s)].length))+n)])}else r.push([span(a.gray,"No MCP servers configured.")]);return r.push([span("","")]),r.push([span(a.gray,"This build has no MCP runtime — servers are configuration only.")]),r.push([span(a.gray,"/mcp add <name> <command> [args…] · /mcp remove <name>")]),o.length&&r.push([span(a.dim,"Sources: "+o.join(", "))]),r}function buildRouter(s,e={}){const n=themeOf(e),a=obj(s),t=a.autoRouter&&"object"==typeof a.autoRouter?a.autoRouter:a.router&&"object"==typeof a.router?a.router:{enabled:!1,tiers:{}},o=t.tiers&&"object"==typeof t.tiers?t.tiers:{},r=[];return r.push([span(n.gold+BOLD,"Model router"),span(BOLD_OFF,"")]),r.push([span(n.gray,"─".repeat(30))]),r.push([span(n.white,"auto-router: "+(t.enabled?"on":"off"))]),r.push([span(n.gray,` simple ${str(o.simple)||"(auto)"}`)]),r.push([span(n.gray,` medium ${str(o.medium)||"(auto)"}`)]),r.push([span(n.gray,` complex ${str(o.complex)||"(auto)"}`)]),r.push([span("","")]),r.push([span(n.gray,"/router on|off · /router set <simple|medium|complex> <modelId>")]),r.push([span(n.dim,"Routing config is persisted for the real CLI; this build serves the model chosen by /model.")]),r}function buildMemory(s,e={}){const n=themeOf(e),a=obj(s),t=statsFrom(a),o=a.embedStatus&&"object"==typeof a.embedStatus?a.embedStatus:null,r=a.compactState&&"object"==typeof a.compactState?a.compactState:a.at?a:null,p=a.compactCfg&&"object"==typeof a.compactCfg?a.compactCfg:null,i=[];i.push([span(n.gold+BOLD,"ÆGIS Memory"),span(BOLD_OFF,"")]),i.push([span(n.gray,"─".repeat(30))]);const u=t?num(t.total):0,l=t?num(t.sessions):0;if(i.push([span(n.white,`${u.toLocaleString()} memories across ${l} sessions`)]),t&&t.roles&&"object"==typeof t.roles){const s=[];null!=t.roles.user&&s.push(`${num(t.roles.user)} user`),null!=t.roles.assistant&&s.push(`${num(t.roles.assistant)} assistant`),t.roles.other&&s.push(`${num(t.roles.other)} other`),s.length&&i.push([span(n.gray,` roles: ${s.join(" · ")}`)])}if(t&&t.tiers&&i.push([span(n.gray,` tiers: ${JSON.stringify(t.tiers)}`)]),t&&null!=t.total){const s=u?Math.round(num(t.withEmbeddings)/u*100):0;o&&o.engine?i.push([span(n.gray,` embed: ${str(o.engine)} · ${s}% coverage`)]):o&&i.push([span(n.gray," embed: keyword-only")]),t.stale&&i.push([span(n.gray,` stale: ${num(t.stale)} entries >90d`)])}return r&&i.push([span(n.gray,r.at?` last compact: ${str(r.at).slice(0,10)}`:" auto-compact: never run")]),p&&i.push([span(n.gray,` auto-compact: ${p.enabled?"on":"off"} (min ${num(p.minL1)} L1 · ${num(p.cooldownMin)}m cooldown)`)]),i.push([span("","")]),i.push([span(n.gray,"/memory tiers · /memory embeddings · /memory recall <q>")]),i.push([span(n.gray,"/memory compact · /memory profile · /aegis-remember <note> to save")]),i}function buildMemoryTiers(s,e={}){const n=themeOf(e),a=obj(s),t=statsFrom(a),o=Array.isArray(a.pending)?a.pending:[],r=a.compactState&&"object"==typeof a.compactState?a.compactState:null,p=a.compactCfg&&"object"==typeof a.compactCfg?a.compactCfg:null,i=[];if(i.push([span(n.gold+BOLD,"Memory Tiers"),span(BOLD_OFF,"")]),i.push([span(n.gray,"─".repeat(30))]),t&&t.tiers&&(i.push([span(n.white,`L0 turns ${num(t.tiers.L0)} raw session turns, volatile`)]),i.push([span(n.white,`L1 atomic ${num(t.tiers.L1)} facts · decisions · breakthroughs`)]),i.push([span(n.white,`L2 scenario ${num(t.tiers.L2)} distilled reusable context`)]),i.push([span(n.white,`L3 profile ${num(t.tiers.L3)} single distilled identity row`)])),i.push([span("","")]),i.push([span(n.gray,`pending L1 (auto-compact trigger): ${o.length}`)]),r&&r.at){const s=Array.isArray(r.scenarios)?r.scenarios.length:0;i.push([span(n.gray,`last auto-compact: ${str(r.at).slice(0,16)} · ${s} scenario${1===s?"":"s"}`)])}else i.push([span(n.gray,"last auto-compact: never")]);return i.push([span(n.gray,p?`auto-compact: ${p.enabled?"on":"off"} · min ${num(p.minL1)} L1 · ${num(p.cooldownMin)}m cooldown`:"auto-compact: on · min 5 L1 · 15m cooldown")]),i.push([span("","")]),i.push([span(n.gray,"/memory compact runs maintenance manually")]),i}function buildMemoryEmbeddings(s,e,n={}){const a=themeOf(n),t=s&&"object"==typeof s?s:null,o=e&&"object"==typeof e?e:null,r=[];if(r.push([span(a.gold+BOLD,"Memory Embeddings"),span(BOLD_OFF,"")]),r.push([span(a.gray,"─".repeat(30))]),t&&t.engine?(r.push([span(a.white,`engine: ${str(t.engine)} · ${str(t.model)}`)]),t.dim&&r.push([span(a.gray,` dim: ${num(t.dim)}`)])):(r.push([span(a.white,"engine: keyword-only (no embedder resolved)")]),t&&t.reason&&r.push([span(a.gray,` reason: ${str(t.reason)}`)])),r.push([span(a.gray,`mode: ${t&&str(t.mode)||"auto"} (env AEGIS_MEMORY_EMBED or memoryConfig.embedMode)`)]),o&&null!=o.total){const s=num(o.total),e=num(o.withEmbeddings),n=s?Math.round(e/s*100):0;if(r.push([span(a.gray,`coverage: ${e}/${s} rows (${n}%)`)]),o.embeddingModels&&Object.keys(o.embeddingModels).length){const s=Object.entries(o.embeddingModels).map((([s,e])=>`${s}: ${num(e)}`));r.push([span(a.gray,` models: ${s.join(" · ")}`)])}o.stale&&r.push([span(a.gray,` stale (>90d): ${num(o.stale)}`)])}return r.push([span("","")]),r.push([span(a.gray,"/memory embeddings on|off toggles the engine chain")]),r}function buildAutomode(s,e={}){const n=themeOf(e),a=[];return a.push([span(n.gold+BOLD,"⚠ automode enabled"),span(BOLD_OFF,"")]),a.push([span(n.gray,"─".repeat(30))]),a.push([span(n.white,"All tool executions are auto-approved: file writes,")]),a.push([span(n.white,"bash commands, and network requests run without asking.")]),a.push([span("","")]),a.push([span(n.gray,"Run /automode off to restore confirmations.")]),a.push([span(n.gray,"(/yolo is accepted as an alias.)")]),a}const buildYolo=buildAutomode;function buildReleaseNotes(s,e={}){const n=themeOf(e),a=[];a.push([span(n.gold+BOLD,`What's new in v${VERSION}`),span(BOLD_OFF,"")]),a.push([span(n.gray,"─".repeat(30))]);const t=["v6.7.3 — the shared renderer is re-staged into cli/vendor.","v6.7.1 — terminal capabilities are read from the terminal, not the platform.","v6.7.0 — a file edit renders as a coloured diff block.","v6.6.0 — autonomous mode: a persistent work queue with a detached worker.","v6.5.x — the live tool row, /cost billed from the ledger the server settled at.","v6.4.0 — `aegiscode login`/`logout`/`key`, a 0600 credential store, /cloud and /sync."];for(const s of t){const e=s.indexOf(" — "),t=-1===e?s:s.slice(0,e),o=-1===e?"":s.slice(e+3);a.push([span(n.green,"•"),span(n.gold,` ${t}`),span(n.white,o?` — ${o}`:"")])}let o=null;try{const s=require("./commands.js");o={n:s.visibleCommands().length,cats:s.CATEGORIES.length}}catch{}return o&&(a.push([span("","")]),a.push([span(n.gray,` ${o.n} commands across ${o.cats} categories — /help lists them.`)])),a.push([span(n.gray," The version above is read from the package; the prose is not.")]),a.push([span(n.gray," Repo: https://aegiscloud.org")]),a}function stubPanel(s,e,n){const a=themeOf(s);return[[span(a.gold+BOLD,e),span(BOLD_OFF,"")],[span(a.gray,` ${e} is not available in aegiscode — ${n}`)]]}function buildDoctor(s,e={}){return stubPanel(e,"Doctor","it needs the local environment diagnostic suite.")}function buildBuildPanel(s,e={}){const n=obj(s),a=themeOf(e);return[[span(a.gold+BOLD,`⬡ Build: ${str(n.plan&&n.plan.appName)||"build"}`),span(BOLD_OFF,"")],[span(a.gray," Build is not available in aegiscode — it needs a local multi-model agent build loop.")]]}module.exports={buildHelp:buildHelp,buildStatus:buildStatus,buildCost:buildCost,buildContext:buildContext,buildTokens:buildTokens,buildAgents:buildAgents,buildPermissions:buildPermissions,buildModelList:buildModelList,buildRewindList:buildRewindList,buildOnboarding:buildOnboarding,buildShellCompletion:buildShellCompletion,buildTerminalSetup:buildTerminalSetup,buildTerminalCaps:buildTerminalCaps,buildPRs:buildPRs,buildBenchmark:buildBenchmark,buildWaifu:buildWaifu,buildAegisStatus:buildAegisStatus,buildAegisRecall:buildAegisRecall,buildAegisMulti:buildAegisMulti,buildBilling:buildBilling,buildMemory:buildMemory,buildMemoryTiers:buildMemoryTiers,buildRouter:buildRouter,buildAutomode:buildAutomode,buildYolo:buildYolo,buildSkills:buildSkills,buildMcp:buildMcp,buildHooksStatus:buildHooksStatus,buildHooksList:buildHooksList,buildTroubleshooting:buildTroubleshooting,buildReleaseNotes:buildReleaseNotes,renderSessionsOverlay:renderSessionsOverlay,buildAegisPrint:buildAegisPrint,buildSkillDetail:buildSkillDetail,buildMemoryEmbeddings:buildMemoryEmbeddings,buildDoctor:buildDoctor,buildBuildPanel:buildBuildPanel,fmtEur:fmtEur,fmtTokens:fmtTokens};
3
+ const{span:e,getSize:t,lineWidth:s}=require("./screen.js"),{themeOf:o,BOLD:r,BOLD_OFF:n,GLYPH:a}=require("./theme.js"),{goUrl:i}=require("./signup.js"),{cwdName:u,pathName:l}=require("./format.js"),h=require("../package.json").version;function p(e){const t=Number(e);return Number.isFinite(t)?t:0}function c(e){return null==e?"":String(e)}function d(t,s,o,r){const n=Math.max(20,(Number(r)||80)-2-s),a=" ".repeat(s),i=c(t).split(/\s+/).filter(Boolean),u=[];let l="";for(const t of i){const s=l?`${l} ${t}`:t;l&&s.length>n?(u.push([e("",a),e(o,l)]),l=t):l=s}return l&&u.push([e("",a),e(o,l)]),u.length?u:[[e("",a),e(o,"")]]}function g(e){const t=p(e.input),s=p(e.output),o=p(e.cacheRead),r=p(e.cacheWrite),n=t+o+r;return{input:t,output:s,cacheRead:o,cacheWrite:r,prompt:n,total:p(e.total)||n+s}}function m(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"0":Math.round(t).toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}function y(e){const t=Number(e);if(!Number.isFinite(t))return"€?";const s=Math.abs(t);return`€${s<.01?s.toFixed(4):s.toFixed(2)}`}function f(e){if(!e)return"";const t=Date.now()-new Date(String(e)).getTime();return t>=0&&!Number.isNaN(t)?t<6e4?`${Math.max(1,Math.round(t/1e3))}s ago`:t<36e5?`${Math.round(t/6e4)}m ago`:t<864e5?`${Math.round(t/36e5)}h ago`:`${Math.round(t/864e5)}d ago`:""}function b(t,s,o,r=50){const n=Math.max(0,Math.min(1,s>0?p(t)/s:0)),a=Math.round(n*r);return[e(""," "),e(o.green,"█".repeat(a)),e(o.dim,"█".repeat(Math.max(0,r-a))),e(o.gray,` ${Math.round(100*n)}% used`)]}function w(t,s,{indent:o=" ",keyStyle:r=null,valStyle:n=null}={}){const a=s.reduce(((e,t)=>Math.max(e,[...t[0]].length)),0);return s.map((([s,i])=>[e(null!=r?r:t.gray,o+s+" ".repeat(a-[...s].length)+" : "),e(null!=n?n:t.white,c(i))]))}function k(e){return e&&"object"==typeof e?e:{}}function $(e){const t=k(e);return t.stats&&"object"==typeof t.stats?t.stats:t.memory&&"object"==typeof t.memory&&(null!=t.memory.total||t.memory.tiers||null!=t.memory.sessions||t.memory.roles)?t.memory:null!=t.total||t.tiers||t.roles?t:null}const v={session:"Session & context",workspace:"Workspace",model:"Model & behavior",data:"Data",auth:"Auth",support:"Support",fun:"Fun",aegis:"Aegis plugin",custom:"Custom"};function S(e){if(e&&e.categoryLabel)return String(e.categoryLabel);const t=c(e&&e.category);return v[t]?v[t]:t?t.charAt(0).toUpperCase()+t.slice(1):"Commands"}function M(t,i,l,h={}){const d=o(h),g=k(t),m=Math.max(30,p(i)?p(i)-4:76),y=c(g.version),f=c(g.model)||"default model",b=u(g.cwd),w=Array.isArray(g.sessions)?g.sessions.filter(Boolean):[],$=w.filter((e=>e.awaiting||e.needsInput)).length,v=w.filter((e=>e.working)).length,S=w.filter((e=>e.completed)).length,M=t=>[e(d.gray,"│"),e(""," "),...t,e(""," ".repeat(Math.max(0,m-1-s(t)))),e(d.gray,"│")],A=[];return A.push([e(d.coral,"╭─── Aegiscode v"+y+" "+"─".repeat(Math.max(0,m-24))+"╮")]),A.push(M([e(d.white,f),e(d.gray," · "),e(d.white,b)])),A.push(M([e(d.gray,`${$} awaiting input · ${v} working · ${S} completed`)])),A.push([e(d.gray,"├"+"─".repeat(m)+"┤")]),A.push(M([e(d.white+r,"Needs input"),e(n,"")])),A.push(M([e(d.gray,"Sessions that have a question or need your decision land here")])),A.push(M([e(d.coral,a.bloom),e(d.gray," current session send a prompt to start "),e(d.gray,"—")])),A.push(M([e(d.white+r,"Working"),e(n,"")])),A.push(M([e(d.gray,"Sessions AEGIS is actively working on — they keep running even if you close the terminal")])),A.push(M([e(d.white+r,"Completed"),e(n,"")])),A.push(M([e(d.gray,"Finished sessions wait here for you to review")])),A.push([e(d.gray,"╰"+"─".repeat(m)+"╯")]),A.push([e(""," "),e(d.gray,"Sub-agents that keep working in the background need a local agent loop;")]),A.push([e(""," "),e(d.gray,"this build hands a bigger task to the pooled brain instead.")]),A}const A=[" ▄▄▄▄▄▄▄▄▄▄▄▄"," ▄█▓▓▓▓▓▓▓▓▓▓▓▓█▄"," █▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█"," █▓▓▓█▓▓▓▓▓▓▓█▓▓▓█"," █▓▓█▓▓█▓▓▓█▓▓█▓▓█"," █▓▓█▓█▓▓▓█▓█▓▓█"," █▓▓▓█▓▓▓█▓▓▓█"," ██▓▓▓▓▓▓▓▓▓▓▓▓▓██"," █▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█"," █▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█"," █▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█"," ▀█▓▓▓▓▓▓▓▓▓▓▓▓▓█▀"," ▀▀▀███████▀▀▀"];function x(t,s={}){const a=o(s),i=[];return i.push([e(a.gold+r,"⚠ automode enabled"),e(n,"")]),i.push([e(a.gray,"─".repeat(30))]),i.push([e(a.white,"All tool executions are auto-approved: file writes,")]),i.push([e(a.white,"bash commands, and network requests run without asking.")]),i.push([e("","")]),i.push([e(a.gray,"Run /automode off to restore confirmations.")]),i.push([e(a.gray,"(/yolo is accepted as an alias.)")]),i}const j=x;module.exports={buildHelp:function(t,s={}){const a=o(s),i=Array.isArray(t)?t:Array.isArray(k(t).commands)?t.commands:[],u=[];u.push([e(a.gold+r,"Commands"),e(n,"")]),u.push([e(a.gray,"─".repeat(30))]);let l=null;for(const t of i){if(!t||!t.name)continue;const s=c(t.category);s!==l&&(u.push([e("","")]),u.push([e(a.gray+r,S(t)),e(n,"")]),l=s);const o=String(t.name),i=" ".repeat(Math.max(1,16-[...o].length)),h=c(null!=t.desc?t.desc:t.help),p=t.unavailable?a.gray:a.white,d=t.unavailable?a.dim:a.gray,g=t.unavailable?" (unavailable)":"";u.push([e(p,"/"+o),e(d,i+h+g)])}return i.length||(u.push([e("","")]),u.push([e(a.gray,"No commands registered.")])),u.push([e("","")]),u.push([e(a.gray,"Shortcuts: "),e(a.white,"?"),e(a.gray," · "),e(a.white,"/help"),e(a.gray," commands · "),e(a.white,"↑↓"),e(a.gray," history · "),e(a.white,"Ctrl-L"),e(a.gray," clear · "),e(a.white,"Ctrl-D"),e(a.gray," exit")]),u},buildStatus:function(t,s={}){const a=o(s),i=k(t),u=[];u.push([e(a.gold+r,"Status"),e(n,"")]);const l=[],h=(e,t)=>{const s=c(t);""!==s&&l.push([e,s])};h("Session ID",i.sessionId),h("Working directory",i.cwd),h("Home",i.home),h("Model",i.model),h("Effort",i.effort||"high"),null!=i.thinking&&h("Thinking",i.thinking?"on":"off"),null!=i.stream&&h("Streaming",!1===i.stream?"off":"on"),null!=i.vim&&h("Vim keymap",i.vim?"on":"off"),h("Theme",i.theme?c(i.theme):s&&s.light?"Light mode":"Dark mode"),h("Backend",i.backend),h("Base",i.base),h("Plan",i.plan),h("Account",i.account),null!=i.online&&h("Online",i.online?"yes":"no"),null!=i.turns&&h("Turns",c(p(i.turns))),null!=i.calls&&h("Tool calls",c(p(i.calls))),null!=i.version&&h("Version","v"+c(i.version)),h("Node",process.version),h("Platform",`${process.platform} ${process.arch}`);const d=Array.isArray(s.caps)?s.caps:[],g=e=>{const t=d.find((t=>Array.isArray(t)&&String(t[0])===e));return t?c(t[1]):""};h("Terminal",g("terminal")),h("Mark",g("mark")),h("Star",g("star")),h("Color",g("color")),h("Control",g("control")),h("Frame",g("size"));for(const e of w(a,l,{keyStyle:a.gray,valStyle:a.white}))u.push(e);u.push([e("","")]);const m=i.permissions&&i.permissions.mode?c(i.permissions.mode):"default";return u.push([e(a.gray,`Permissions: ${m} — tool use follows your AEGIS settings.`)]),u},buildCost:function(s,a={}){const i=o(a),u=k(s),{cols:l}=t(),h=Math.max(30,l-2),d=u.tokens&&"object"==typeof u.tokens?u.tokens:{},{input:f,output:w,cacheRead:$,cacheWrite:v,prompt:S,total:M}=g(d),A=p(u.costEur),x=c(u.model)||"the pinned model",j=p(u.contextWindow)||2e5,C=j>0?Math.min(100,Math.round(M/j*100)):0,T=[];return T.push([e(i.gray,"─".repeat(h))]),T.push([e(""," "),e(i.white+r,"Session"),e(n,""),e(i.gray," Status Config Usage Stats")]),T.push([e(""," "),e(i.gray,"Session")]),T.push([e(""," "),e(i.white,"Total cost:"),e(i.gray," "+" ".repeat(Math.max(0,14-y(A).length))+y(A))]),null!=u.balance&&T.push([e(""," "),e(i.white,"Balance:"),e(i.gray," "+" ".repeat(Math.max(0,14-y(u.balance).length))+y(u.balance))]),null==u.turns&&null==u.calls||T.push([e(""," "),e(i.white,"Turns:"),e(i.gray,` ${p(u.turns)} turns · ${p(u.calls)} calls`)]),T.push([e(""," "),e(i.white," Usage by model:")]),T.push([e(""," "),e(i.gray,` ${x}: ${m(S)} input, ${m(w)} output (${y(A)})`)]),($||v)&&T.push([e(""," "),e(i.dim,` ↳ miss ${m(f)} · cache read ${m($)} · cache write ${m(v)}`)]),T.push([e(""," ")]),T.push([e(""," "),e(i.white+r,"Current session"),e(n,"")]),T.push(b(M,j,i)),T.push([e(""," ")]),T.push([e(""," "),e(i.gray,`Session context: ${C}% of ${m(j)} used.`)]),T.push([e(""," "),e(i.dim,"Cost is metered from the AEGIS token bank; tokens are counted this session.")]),T},buildContext:function(s,a={}){const i=o(a),u=k(s),{cols:l}=t(),h=Math.max(30,l-2),c=u.tokens&&"object"==typeof u.tokens?u.tokens:{},{input:d,output:y,cacheRead:f,cacheWrite:w,prompt:$,total:v}=g(c),S=p(u.contextWindow)||2e5,M=[];M.push([e(i.gold+r,"Context usage"),e(n,"")]),M.push([e(""," "),e(i.gray,"─".repeat(Math.max(1,h-2)))]);const A=(t,s)=>[e(""," "),e(i.white,t),e(""," ".repeat(Math.max(1,16-[...t].length))),e(i.gray,m(s)),e(""," ".repeat(Math.max(1,10-m(s).length))),...b(s,S,i)];return M.push(A("Prompt tokens",$)),(f||w)&&M.push([e(""," "),e(i.dim,` ↳ miss ${m(d)} · cache read ${m(f)} · cache write ${m(w)}`)]),M.push(A("Output tokens",y)),M.push([e(""," ")]),M.push([e(""," "),e(i.gray,"─".repeat(Math.max(1,h-2)))]),M.push([e(""," "),e(i.white+r,"Total"),e(""," ".repeat(9)),e(i.gray,m(v)),e(""," ".repeat(Math.max(1,10-m(v).length))),...b(v,S,i)]),M.push([e(""," ")]),M.push([e(""," "),e(i.gray,`Context window: ${m(S)} tokens`)]),M},buildTokens:function(s,a={}){const i=o(a),u=k(s),{cols:l}=t(),h=Math.max(24,l-2),c=u.tokens&&"object"==typeof u.tokens?u.tokens:{},{input:d,output:f,cacheRead:b,cacheWrite:w,total:$}=g(c),v=p(u.costEur),S=p(u.contextWindow)||2e5,M=S>0?Math.min(100,Math.round($/S*100)):0,A=[];A.push([e(i.gold+r,"Token usage"),e(n,"")]),A.push([e(i.gray,"─".repeat(Math.min(30,h)))]);const x=Math.max(d,f,b,w,1),j=(t,s)=>{const o=Math.min(1,s/x),r=Math.max(0,Math.round(24*o));return[e(""," "),e(i.white,t),e(""," ".repeat(Math.max(1,11-[...t].length))),e(i.green,"█".repeat(r)),e(i.dim,"█".repeat(Math.max(0,24-r))),e(i.gray,` ${m(s)}`)]};return A.push(j("input",d)),A.push(j("output",f)),A.push(j("cache read",b)),A.push(j("cache write",w)),A.push([e(""," ")]),A.push([e(""," "),e(i.white,"Total:"),e(i.gray,` ${m($)}`),e(""," ".repeat(8)),e(i.white,"Est. cost:"),e(i.gray,` ${y(v)}`)]),A.push([e(""," "),e(i.gray,`Context: ${M}% of ${m(S)} window`)]),A.push([e(""," "),e(i.gray,"Tokens are counted from this session; cost is metered in euro.")]),A},buildAgents:function(e,s={}){const{cols:o,rows:r}=t();return M(e,o,0,s)},buildPermissions:function(t,s,a={}){const i=o(a),u=k(t),l=e=>Array.isArray(e)?e:[],h=null!=s&&""!==s?String(s):null!=u.defaultMode?String(u.defaultMode):"default",p=[];p.push([e(i.gold+r,"Permissions"),e(n,"")]),p.push([e(""," "),e(i.gray,"Default mode: "),e(i.white,h)]),p.push([e(""," ")]);const d=(t,s)=>{const o=[[e(""," "),e(i.white+r,t),e(n,"")]];s.length||o.push([e(""," "),e(i.gray,"(none)")]);for(const t of s)o.push([e(""," "),e(i.gray,c(t))]);return o};for(const e of d("Allow",l(u.allow)))p.push(e);for(const e of d("Deny",l(u.deny)))p.push(e);for(const e of d("Ask",l(u.ask)))p.push(e);return p.push([e("","")]),p.push([e(i.gray,"Usage:")]),p.push([e(i.gray,' /permissions allow "Bash(npm run *)"')]),p.push([e(i.gray,' /permissions deny "Edit(src/**)"')]),p.push([e(i.gray,' /permissions ask "Read(**/*.env)"')]),p.push([e(i.gray," /permissions default ask · /permissions clear")]),p.push([e("","")]),p.push([e(i.dim,`Stored in ${c(u._path)||"~/.aegiscode/permissions.json"}`)]),p},buildModelList:function(t,s,a={}){const i=o(a),u=Array.isArray(s)?s:[],l=c(t),h=e=>e.cls?"byok"===e.cls:"byok"===a.modelClass,p=u.some(h),d=[];d.push([e(i.gold+r,"Models"),e(n,"")]),d.push([e(i.gray,"─".repeat(30))]);for(const t of u){if(!t)continue;const s=c(t.id)||c(t.model),o=(""!==s&&s===l?"▶ ":" ")+s,r=c(t.name||t.label||t.model),n=h(t)?c(t.note)||c(t.model):c(t.model)||"(default)";d.push([e(i.white,o),e(""," ".repeat(Math.max(1,26-[...o].length))),e(i.gray,r),e(""," ".repeat(Math.max(1,22-[...r].length))),e(i.gray,n)])}return u.length||d.push([e(""," "),e(i.gray,"(no models configured)")]),d.push([e("","")]),d.push([e(i.gray,p?"Switch: /model <id> · Add a provider key: /byok-key <provider> · Run on it: /class byok":"Switch: /model <id> · Add: /model add <id> <name> <model> <baseURL> [apiKey] · Remove: /model remove <id>")]),d},buildRewindList:function(t,s={}){const a=o(s),i=Array.isArray(t)?t:[],u=[];u.push([e(a.gold+r,"Rewind"),e(n,"")]),u.push([e(""," "),e(a.gray,"Snapshots are taken after every exchange.")]),u.push([e(""," ")]);for(const t of i){if(!t)continue;const s=c(p(t.idx));u.push([e(""," "),e(a.green,s),e(""," ".repeat(Math.max(1,4-[...s].length))),e(a.white,`${p(t.depth)} messages`),e(a.gray,` · ${p(t.words)} words · ${f(t.ts)}`)])}return i.length||u.push([e(""," "),e(a.gray,"(no checkpoints)")]),u.push([e("","")]),u.push([e(a.gray,"Usage: /rewind N to restore that checkpoint (0 = session start)")]),u},buildOnboarding:function(t,s={}){const a=o(s),i=[];i.push([e(a.gold+r,"Getting started"),e(n,"")]);const u=[["/help","list every command"],["/","open the command palette"],["?","shortcuts"],["/model <id>","pin a model"],["/theme light|dark","switch the colour theme"],["/aegis-ask","ask the pooled brain a question"],["/memory","show your AEGIS cloud memory"],["Ctrl-D","exit"]];for(const[t,s]of u)i.push([e(""," "),e(a.lavender,t),e(""," ".repeat(Math.max(1,20-[...t].length))),e(a.gray,s)]);return i.push([e("","")]),i.push([e(a.gray,'Try "summarize this file for me" to see the full flow.')]),i},buildShellCompletion:function(t,s={}){const a=o(s),i=[];i.push([e(a.gold+r,"Shell completion"),e(n,"")]),i.push([e(""," "),e(a.gray,"Aegiscode completes /commands with Tab inside the app.")]),i.push([e(""," "),e(a.gray,"For shell-level completion of the aegiscode CLI itself:")]),i.push([e(""," ")]);const u=[["bash",'eval "$(aegiscode shell-completion bash)"'],["zsh",'eval "$(aegiscode shell-completion zsh)"'],["fish","aegiscode shell-completion fish | source"]];for(const[t,s]of u)i.push([e(""," "),e(a.white+r,t),e(""," ".repeat(Math.max(1,6-t.length))),e(a.gray,s)]);return i.push([e("","")]),i.push([e(a.dim,"Add the eval line to your ~/.bashrc or ~/.zshrc to make it persist.")]),i},buildTerminalSetup:function(s,a={}){const i=o(a),u=k(s),h="undefined"!=typeof process&&process.env?process.env:{},{cols:p,rows:d}=t(),g=c(u.shell)||l(c(h.SHELL)),m=[["TERM",c(u.term)||c(h.TERM)||"(unset)"],["LANG",c(u.lang)||c(h.LANG)||"(unset)"],["Shell",g||"unknown"],["Size",`${p}x${d}`]],y=[];y.push([e(i.gold+r,"Terminal setup"),e(n,"")]);for(const e of w(i,m,{keyStyle:i.white,valStyle:i.gray}))y.push(e);return y.push([e("","")]),y.push([e(i.gray,"Tips:")]),y.push([e(i.gray," • TERM=xterm-256color enables full color + resize handling")]),y.push([e(i.gray," • Set LANG (e.g. en_US.UTF-8) for correct glyphs and word wrap")]),y.push([e(i.gray," • Resize mid-session is handled (SIGWINCH); overlays adapt")]),y},buildTerminalCaps:function(t,s={}){const i=o(s),u=(Array.isArray(t)?t:[]).filter((e=>Array.isArray(e)&&e.length>=2)).map((([e,t])=>[c(e),c(t)])),l=[];if(l.push([e(i.gold+r,"Terminal capabilities"),e(n,"")]),!u.length)return l.push([e(""," "),e(i.gray,"No capability report available.")]),l;for(const e of w(i,u,{keyStyle:i.white,valStyle:i.gray}))l.push(e);return l.push([e("","")]),s&&s.pinned&&(l.push([e(i.coral,a.warn),e(i.gold," width is pinned — resizes are ignored until /terminal auto")]),l.push([e("","")])),l.push([e(i.gray,"Override: /terminal ascii | unicode | color | no-color | background <dark|light> | star <native|narrow>")]),l.push([e(i.gray," /terminal width <cols> | auto | status")]),l.push([e(i.gray,"At launch: --ascii --unicode --no-color --width <cols> --terminal")]),l},buildPRs:function(t,s={}){const a=o(s),i=[];i.push([e(a.gold+r,"Open pull requests"),e(n,"")]);const u=c(t).trim();if(!u)return i.push([e(""," "),e(a.gray,"No open PRs in this repository.")]),i;for(const t of u.split("\n").slice(0,10))i.push([e(""," "),e(a.white,t)]);return i.push([e("","")]),i.push([e(a.gray,"Review with /review · comments via /pr-comments")]),i},buildBenchmark:function(t,s={}){const a=o(s),i=Array.isArray(t)?t:[],u=[];u.push([e(a.gold+r,"Benchmark"),e(n,"")]),u.push([e(""," "),e(a.gray,"In-app micro-benchmarks (this process, this machine):")]),u.push([e(""," ")]);for(const t of i){if(!Array.isArray(t)||t.length<2)continue;const s=c(t[0]);u.push([e(""," "),e(a.white,s),e(""," ".repeat(Math.max(1,30-[...s].length))),e(a.gray,`${p(t[1])} ms`)])}return i.length||u.push([e(""," "),e(a.gray,"(no benchmarks run)")]),u.push([e("","")]),u.push([e(a.dim,"Spoiler: the terminal renders faster than you type.")]),u},buildWaifu:function(t={}){const s=o(t),a=[];a.push([e(s.gold+r,"Waifu"),e(n,"")]);for(const t of A)a.push([e(s.lavender,t)]);return a.push([e("","")]),a.push([e(s.gray,"A distinguished gentleman, rendered in block characters.")]),a},buildAegisStatus:function(t,s={}){const a=o(s),i=k(t),u=$(i),l=i.cloud&&"object"==typeof i.cloud?i.cloud:null,h=c(i.cloudNote),d=c(i.version),g=c(i.backend||i.store),m=[];m.push([e(a.gold+r,"ÆGIS Status"),e(n,"")]),m.push([e(a.gray,"─".repeat(30))]);const y=u?p(u.total):0,f=u?p(u.sessions):0;if(m.push([e(a.white,`Memory: ${y.toLocaleString()} entries across ${f} sessions`)]),u&&u.roles&&(null!=u.roles.user||null!=u.roles.assistant)){const t=u.roles,s=[];null!=t.user&&s.push(`${p(t.user)} user`),null!=t.assistant&&s.push(`${p(t.assistant)} assistant`),t.other&&s.push(`${p(t.other)} other`),s.length&&m.push([e(a.gray,` roles: ${s.join(" · ")}`)])}if(u&&u.tiers&&m.push([e(a.gray,` tiers: ${JSON.stringify(u.tiers)}`)]),g&&m.push([e(a.gray,` store: ${g}`)]),u&&null!=u.total){const t=p(u.withEmbeddings),s=y?Math.round(t/y*100):0;if(!0===u.embeddingsEnabled){const t=u.embeddingModels&&Object.keys(u.embeddingModels)[0]||"embedding";m.push([e(a.gray,` embed: ${t} · ${s}% coverage`)])}else!1===u.embeddingsEnabled&&y&&m.push([e(a.gray," embed: keyword-only")]);u.stale&&m.push([e(a.gray,` stale: ${p(u.stale)} entries >90d`)])}if(l){const t=l.key?"✓ connected":"✗ no API key",s=l.sync?"sync on":"sync off";m.push([e(a.white,`Cloud: ${t}, ${s}`)])}else h?m.push([e(a.gray,`Cloud: ${h}`)]):m.push([e(a.gray,"Cloud: not checked (aegis /cloud status unavailable)")]);return d&&m.push([e(a.gray,`CLI: aegis ${d}`)]),m},buildAegisRecall:function(t,s={}){const a=o(s),i=Array.isArray(t)?t.filter(Boolean):[],u=[];if(u.push([e(a.gold+r,"ÆGIS Memory"),e(n,"")]),u.push([e(a.gray,"─".repeat(30))]),!i.length)return u.push([e(a.gray,"No memory found for this topic.")]),u.push([e(a.gray,"Nothing relevant is stored yet — /aegis-remember <note> saves one.")]),u;for(const t of i.slice(0,10)){const s=c(t.content).split("\n")[0].slice(0,90);u.push([e(a.white+r,`• ${s}`),e(n,"")]);const o=t.timestamp?c(t.timestamp).slice(0,10):"",i=t.source?` (${c(t.source)})`:"",l=Array.isArray(t.tags)&&t.tags.length?" · tags: "+t.tags.join(", "):"";u.push([e(a.gray,` ${o}${i}${l}`)])}return i.length>10&&u.push([e(a.gray,`…and ${i.length-10} more`)]),u},buildAegisMulti:function(t,s={}){const a=o(s),i=c(t),u=[];return u.push([e(a.gold+r,"ÆGIS Multi — compose"),e(n,"")]),u.push([e(a.gray,"─".repeat(30))]),u.push([e(a.gray,"Paste into your aegis-cli session (the confirmation prompt works there):")]),u.push([e(a.white,` /multi ${i}`)]),u.push([e(a.gray," /multiyolo "+i+" — auto-approved variant")]),u.push([e("","")]),u.push([e(a.gray,"Optional flags: --save-as <name> · --template <id>")]),u.push([e(a.gray,'Add "run" to execute headless here instead: /aegis-multi <task> run')]),u},buildBilling:function(s,a={}){const u=o(a),l=k(s),h=[];h.push([e(u.gold+r,"Billing"),e(n,"")]),h.push([e(u.gray,"─".repeat(30))]);const p=[];if(null!=l.balance&&p.push(["Balance",y(l.balance)]),null!=l.plan&&p.push(["Plan",c(l.plan)]),null!=l.account&&p.push(["Account",c(l.account)]),null!=l.costEur&&p.push(["This session",y(l.costEur)]),p.length)for(const e of w(u,p,{indent:" ",keyStyle:u.gray,valStyle:u.white}))h.push(e);else h.push([e(""," "),e(u.gray,"No billing data available.")]);h.push([e("","")]),h.push([e(u.white,"AEGIS pooled inference"),e(u.gray," metered against your token bank")]);const g=l.payment&&"object"==typeof l.payment?l.payment:null;if(g){const{cols:s}=t(),o=g.paid?"✔":"✦";h.push(...d(`${o} ${c(g.label)||"Unlimited"}: ${c(g.reason)}`,2,g.paid?u.green:u.gold,s)),h.push(...d(c(g.honesty),2,u.gray,s)),!g.paid&&g.unlock&&h.push(...d(c(g.unlock),2,u.gray,s)),g.byok&&h.push(...d(c(g.byok),2,u.gray,s)),!1===g.verified&&h.push(...d("(account not confirmed this session — verdict may be stale)",2,u.gray,s)),g.url&&h.push([e(""," "),e(u.gray,c(g.url))])}else h.push([e(u.gray,` Top-ups and invoices: ${i("topup","cost_screen")}`)]);return h},buildMemory:function(t,s={}){const a=o(s),i=k(t),u=$(i),l=i.embedStatus&&"object"==typeof i.embedStatus?i.embedStatus:null,h=i.compactState&&"object"==typeof i.compactState?i.compactState:i.at?i:null,d=i.compactCfg&&"object"==typeof i.compactCfg?i.compactCfg:null,g=[];g.push([e(a.gold+r,"ÆGIS Memory"),e(n,"")]),g.push([e(a.gray,"─".repeat(30))]);const m=u?p(u.total):0,y=u?p(u.sessions):0;if(g.push([e(a.white,`${m.toLocaleString()} memories across ${y} sessions`)]),u&&u.roles&&"object"==typeof u.roles){const t=[];null!=u.roles.user&&t.push(`${p(u.roles.user)} user`),null!=u.roles.assistant&&t.push(`${p(u.roles.assistant)} assistant`),u.roles.other&&t.push(`${p(u.roles.other)} other`),t.length&&g.push([e(a.gray,` roles: ${t.join(" · ")}`)])}if(u&&u.tiers&&g.push([e(a.gray,` tiers: ${JSON.stringify(u.tiers)}`)]),u&&null!=u.total){const t=m?Math.round(p(u.withEmbeddings)/m*100):0;l&&l.engine?g.push([e(a.gray,` embed: ${c(l.engine)} · ${t}% coverage`)]):l&&g.push([e(a.gray," embed: keyword-only")]),u.stale&&g.push([e(a.gray,` stale: ${p(u.stale)} entries >90d`)])}return h&&g.push([e(a.gray,h.at?` last compact: ${c(h.at).slice(0,10)}`:" auto-compact: never run")]),d&&g.push([e(a.gray,` auto-compact: ${d.enabled?"on":"off"} (min ${p(d.minL1)} L1 · ${p(d.cooldownMin)}m cooldown)`)]),g.push([e("","")]),g.push([e(a.gray,"/memory tiers · /memory embeddings · /memory recall <q>")]),g.push([e(a.gray,"/memory compact · /memory profile · /aegis-remember <note> to save")]),g},buildMemoryTiers:function(t,s={}){const a=o(s),i=k(t),u=$(i),l=Array.isArray(i.pending)?i.pending:[],h=i.compactState&&"object"==typeof i.compactState?i.compactState:null,d=i.compactCfg&&"object"==typeof i.compactCfg?i.compactCfg:null,g=[];if(g.push([e(a.gold+r,"Memory Tiers"),e(n,"")]),g.push([e(a.gray,"─".repeat(30))]),u&&u.tiers&&(g.push([e(a.white,`L0 turns ${p(u.tiers.L0)} raw session turns, volatile`)]),g.push([e(a.white,`L1 atomic ${p(u.tiers.L1)} facts · decisions · breakthroughs`)]),g.push([e(a.white,`L2 scenario ${p(u.tiers.L2)} distilled reusable context`)]),g.push([e(a.white,`L3 profile ${p(u.tiers.L3)} single distilled identity row`)])),g.push([e("","")]),g.push([e(a.gray,`pending L1 (auto-compact trigger): ${l.length}`)]),h&&h.at){const t=Array.isArray(h.scenarios)?h.scenarios.length:0;g.push([e(a.gray,`last auto-compact: ${c(h.at).slice(0,16)} · ${t} scenario${1===t?"":"s"}`)])}else g.push([e(a.gray,"last auto-compact: never")]);return g.push([e(a.gray,d?`auto-compact: ${d.enabled?"on":"off"} · min ${p(d.minL1)} L1 · ${p(d.cooldownMin)}m cooldown`:"auto-compact: on · min 5 L1 · 15m cooldown")]),g.push([e("","")]),g.push([e(a.gray,"/memory compact runs maintenance manually")]),g},buildRouter:function(t,s={}){const a=o(s),i=k(t),u=i.autoRouter&&"object"==typeof i.autoRouter?i.autoRouter:i.router&&"object"==typeof i.router?i.router:{enabled:!1,tiers:{}},l=u.tiers&&"object"==typeof u.tiers?u.tiers:{},h=[];return h.push([e(a.gold+r,"Model router"),e(n,"")]),h.push([e(a.gray,"─".repeat(30))]),h.push([e(a.white,"auto-router: "+(u.enabled?"on":"off"))]),h.push([e(a.gray,` simple ${c(l.simple)||"(auto)"}`)]),h.push([e(a.gray,` medium ${c(l.medium)||"(auto)"}`)]),h.push([e(a.gray,` complex ${c(l.complex)||"(auto)"}`)]),h.push([e("","")]),h.push([e(a.gray,"/router on|off · /router set <simple|medium|complex> <modelId>")]),h.push([e(a.dim,"Routing config is persisted for the real CLI; this build serves the model chosen by /model.")]),h},buildAutomode:x,buildYolo:j,buildSkills:function(t,s,a={}){const i=o(a),u=Array.isArray(t)?t.filter(Boolean):[],l=Array.isArray(s)?s:[],h=[];if(h.push([e(i.gold+r,"Skills"),e(n,"")]),h.push([e(i.gray,"─".repeat(30))]),!u.length){h.push([e(i.gray,"No skills found.")]),h.push([e(i.gray,"Skill dirs scanned:")]);for(const t of l)h.push([e(i.dim,` ${c(t)}`)]);return h.push([e("","")]),h.push([e(i.gray,"Add one: mkdir -p .aegis/skills/<name> and drop a SKILL.md inside.")]),h}let p=null;for(const t of u){t.source!==p&&(h.push([e(i.gray+r,"user"===t.source?"User":"Project"),e(n,"")]),p=t.source);const s=t.namespace?`${c(t.namespace)}/${c(t.name)}`:c(t.name),o=c(t.description)||"(no description)";h.push([e(i.white,` ${s}`),e(i.gray," ".repeat(Math.max(1,18-[...s].length))+o)])}return h.push([e("","")]),h.push([e(i.gray,"/skills <name> for details · /skills refresh to rescan")]),h},buildMcp:function(t,s,a={}){const i=o(a),u=Array.isArray(t)?t.map(((e,t)=>[c(e&&e.name)||String(t),e])):t&&"object"==typeof t?Object.entries(t):[],l=Array.isArray(s)?s:[],h=[];if(h.push([e(i.gold+r,"MCP servers"),e(n,"")]),h.push([e(i.gray,"─".repeat(30))]),u.length)for(const[t,s]of u){const o="string"==typeof s?s:(c(s&&s.command)+" "+(Array.isArray(s&&s.args)?s.args.join(" "):"")).trim();h.push([e(i.white,` ${c(t)}`),e(i.gray," ".repeat(Math.max(1,14-[...c(t)].length))+o)])}else h.push([e(i.gray,"No MCP servers configured.")]);return h.push([e("","")]),h.push([e(i.gray,"This build has no MCP runtime — servers are configuration only.")]),h.push([e(i.gray,"/mcp add <name> <command> [args…] · /mcp remove <name>")]),l.length&&h.push([e(i.dim,"Sources: "+l.join(", "))]),h},buildHooksStatus:function(t,s={}){const i=o(s),u=k(t),l=Array.isArray(u.events)?u.events:[],h=u.byEvent&&"object"==typeof u.byEvent?u.byEvent:{},d=Array.isArray(u.fromPaths)?u.fromPaths:Array.isArray(u.sources)?u.sources:[],g=[];g.push([e(i.gold+r,"Hooks status"),e(n,"")]);const m=[["status",u.enabled?"enabled":"disabled"],["hooks",c(p(u.hooks))],["events",c(l.length)]];for(const e of w(i,m,{keyStyle:i.gray,valStyle:i.white}))g.push(e);if(p(u.hooks)>0){g.push([e("","")]),g.push([e(""," "),e(i.white+r,"by event"),e(n,"")]);for(const[t,s]of Object.entries(h))g.push([e(""," "),e(i.green,a.bullet),e(i.white,` ${t}`),e(i.gray,` ${p(s)}`)])}return g.push([e("","")]),g.push([e(i.gray,"/hooks list for full config")]),g.push([e("","")]),g.push([e(i.dim,d.length?`Settings: ${d.join(", ")}`:"Settings: no settings.json with hooks found (checked ~/.aegis, .aegis, ~/.aegiscode, .aegiscode, ~/.claude)")]),g.push([e(i.gray,"Config hooks are read, not managed — edit the files above.")]),g.push([e(i.gray,"The repo guard hooks (.githooks/) are installed by /hooks install.")]),g},buildHooksList:function(t,s={}){const a=o(s),i=k(t),u=i.hooks&&"object"==typeof i.hooks?i.hooks:{},l=[];l.push([e(a.gold+r,"Hooks config"),e(n,"")]);let h=!1;for(const[t,s]of Object.entries(u))if(Array.isArray(s)&&0!==s.length){h=!0,l.push([e("","")]),l.push([e(""," "),e(a.white+r,t),e(n,"")]);for(const t of s)t&&(l.push([e(""," "),e(a.lavender,c(t.name)||"(unnamed)")]),t.matcher&&(t.matcher.tools&&l.push([e(""," - tools: "),e(a.gray,c(t.matcher.tools))]),t.matcher.paths&&l.push([e(""," - paths: "),e(a.gray,c(t.matcher.paths))]),t.matcher.commands&&l.push([e(""," - commands: "),e(a.gray,c(t.matcher.commands))])),l.push([e("",` - hooks: ${Array.isArray(t.hooks)?t.hooks.length:0}`)]),l.push([e("","")]))}return h?(l.push([e("","")]),l.push([e(a.gray,"/hooks status for the summary")])):(l.push([e(""," "),e(a.gray,"no hooks configured.")]),l.push([e("","")]),l.push([e(""," "),e(a.gray,"add hooks to settings.json:")]),l.push([e(""," "),e(a.gray,"- ~/.aegis/settings.json (user)")]),l.push([e(""," "),e(a.gray,"- .aegis/settings.json (project)")])),l},buildTroubleshooting:function(t,s={}){const i=o(s),u=[];u.push([e(i.gold+r,"Troubleshooting"),e(n,"")]);const l=[["No output / blank screen","Run with TERM=xterm-256color, or switch to a lighter theme (/theme light)."],["Keys not responding","This client needs a real TTY — run it from a terminal, not a CI job."],["401 / unauthorized","Check the account line with /status, or set a provider key with /byok-set."],["No answers from the brain","Confirm the token-bank balance with /billing."],["Memory looks empty","Recall is per-topic — try /aegis-recall <topic> or save one with /aegis-remember <note>."]];for(const[t,s]of l)u.push([e(i.green,a.bullet),e(i.white," "+t)]),u.push([e(""," "),e(i.gray,s)]);return u.push([e("","")]),u.push([e(i.gray,"Run /status for account state. Help: https://aegiscloud.org")]),u},buildReleaseNotes:function(t,s={}){const a=o(s),i=[];i.push([e(a.gold+r,`What's new in v${h}`),e(n,"")]),i.push([e(a.gray,"─".repeat(30))]);const u=["v6.7.3 — the shared renderer is re-staged into cli/vendor.","v6.7.1 — terminal capabilities are read from the terminal, not the platform.","v6.7.0 — a file edit renders as a coloured diff block.","v6.6.0 — autonomous mode: a persistent work queue with a detached worker.","v6.5.x — the live tool row, /cost billed from the ledger the server settled at.","v6.4.0 — `aegiscode login`/`logout`/`key`, a 0600 credential store, /cloud and /sync."];for(const t of u){const s=t.indexOf(" — "),o=-1===s?t:t.slice(0,s),r=-1===s?"":t.slice(s+3);i.push([e(a.green,"•"),e(a.gold,` ${o}`),e(a.white,r?` — ${r}`:"")])}let l=null;try{const e=require("./commands.js");l={n:e.visibleCommands().length,cats:e.CATEGORIES.length}}catch{}return l&&(i.push([e("","")]),i.push([e(a.gray,` ${l.n} commands across ${l.cats} categories — /help lists them.`)])),i.push([e(a.gray," The version above is read from the package; the prose is not.")]),i.push([e(a.gray," Repo: https://aegiscloud.org")]),i},renderSessionsOverlay:M,buildAegisPrint:function(t,s={},a={}){const i=o(a),u=k(s),l=[];l.push([e(i.gold+r,c(t)),e(n,"")]),l.push([e(i.gray,"─".repeat(30))]);for(const t of c(u.result).split("\n"))l.push([e(i.white,t)]);return(u.model||u.provider)&&l.push([e(i.gray,` via ${c(u.provider)||"aegis"}${u.model?" · "+c(u.model):""}`)]),l},buildSkillDetail:function(t,s={}){const a=o(s),i=k(t),u=i.namespace?`${c(i.namespace)}/${c(i.name)}`:c(i.name),l=[];l.push([e(a.gold+r,`Skill: ${u}`),e(n,"")]),l.push([e(a.gray,"─".repeat(30))]),i.description&&l.push([e(a.gray,c(i.description))]),l.push([e(a.dim,c(i.path))]),l.push([e("","")]);const h=c(i.content).split("\n"),p=h.slice(0,8).join("\n");for(const t of p.split("\n"))l.push([e(a.white,t)]);return h.length>8&&l.push([e(a.gray,`… (${h.length} lines)`)]),l},buildMemoryEmbeddings:function(t,s,a={}){const i=o(a),u=t&&"object"==typeof t?t:null,l=s&&"object"==typeof s?s:null,h=[];if(h.push([e(i.gold+r,"Memory Embeddings"),e(n,"")]),h.push([e(i.gray,"─".repeat(30))]),u&&u.engine?(h.push([e(i.white,`engine: ${c(u.engine)} · ${c(u.model)}`)]),u.dim&&h.push([e(i.gray,` dim: ${p(u.dim)}`)])):(h.push([e(i.white,"engine: keyword-only (no embedder resolved)")]),u&&u.reason&&h.push([e(i.gray,` reason: ${c(u.reason)}`)])),h.push([e(i.gray,`mode: ${u&&c(u.mode)||"auto"} (env AEGIS_MEMORY_EMBED or memoryConfig.embedMode)`)]),l&&null!=l.total){const t=p(l.total),s=p(l.withEmbeddings),o=t?Math.round(s/t*100):0;if(h.push([e(i.gray,`coverage: ${s}/${t} rows (${o}%)`)]),l.embeddingModels&&Object.keys(l.embeddingModels).length){const t=Object.entries(l.embeddingModels).map((([e,t])=>`${e}: ${p(t)}`));h.push([e(i.gray,` models: ${t.join(" · ")}`)])}l.stale&&h.push([e(i.gray,` stale (>90d): ${p(l.stale)}`)])}return h.push([e("","")]),h.push([e(i.gray,"/memory embeddings on|off toggles the engine chain")]),h},buildDoctor:function(t,s={}){return function(t,s,a){const i=o(t);return[[e(i.gold+r,s),e(n,"")],[e(i.gray,` ${s} is not available in aegiscode — it needs the local environment diagnostic suite.`)]]}(s,"Doctor")},buildBuildPanel:function(t,s={}){const a=k(t),i=o(s);return[[e(i.gold+r,`⬡ Build: ${c(a.plan&&a.plan.appName)||"build"}`),e(n,"")],[e(i.gray," Build is not available in aegiscode — it needs a local multi-model agent build loop.")]]},fmtEur:y,fmtTokens:m};
package/src/render.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{RGB:RGB,BG:BG,RESET:RESET,BOLD:BOLD,DIM:DIM,ITALIC:ITALIC,UNDER:UNDER,RESET_FG:RESET_FG,RESET_BG:RESET_BG,GLYPH:GLYPH,VERBS:VERBS,DONE_VERBS:DONE_VERBS,themeOf:themeOf}=require("./theme.js"),{WELCOME_TITLE:WELCOME_TITLE,WELCOME_BACK:WELCOME_BACK,TAGLINE:TAGLINE,STAR:STAR,stencilGlyph:stencilGlyph,welcomeArtParts:welcomeArtParts}=require("./art.js"),{w:w,pad:pad,padStart:padStart,wrapBlock:wrapBlock,clip:clip,span:span}=require("./screen.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,fmtElapsed:fmtElapsed,fmtUsageSplit:fmtUsageSplit,displayTokens:displayTokens,feeBillable:feeBillable}=require("./format.js"),{renderDiffBlock:renderDiffBlock}=require("./diffview.js"),{extractPreview:extractPreview,renderFilePreview:renderFilePreview,extractNewContent:extractNewContent}=require("./filepreview.js");let markdown=null;try{markdown=require("./markdown.js")}catch{markdown=null}const errMark=()=>GLYPH.err,warnMark=()=>GLYPH.warn,fg=(e,t)=>`${t}`,bg=e=>BG(...e),spansToString=e=>e.map((e=>(e.s||"")+e.t)).join("")+RESET;function centerStyled(e,t,r){const n=clip(e,t),s=Math.max(0,Math.floor((t-w(n))/2));return" ".repeat(s)+r+n+RESET}function tintWhale(e,t){const r={"▓":t.blue,"▒":t.lavender,"░":t.dim,"█":t.white,[STAR]:t.gold,"·":t.dim},n={};for(const e of Object.keys(r))n[stencilGlyph(e)]=r[e];const s=[];let o=null,a="";for(const t of e){const e=null!=n[t]?n[t]:"";null!==o&&e===a?o+=t:(null!==o&&s.push(span(a,o)),o=t,a=e)}return null!==o&&s.push(span(a,o)),s}function artRow(e,t,r,n){const s=themeOf(e),o=t[0]||"",a=t[1]||"",l=[span(""," ".repeat(n))];return o&&a?(l.push(span(s.gold,o)),l.push(span(""," ".repeat(r.gutter))),l.push(...tintWhale(a,s))):o?(l.push(span(s.gold,o)),w(o)<r.width&&l.push(span(""," ".repeat(r.width-w(o))))):a?(l.push(...tintWhale(a,s)),w(a)<r.width&&l.push(span(""," ".repeat(r.width-w(a))))):l.push(span(""," ".repeat(r.width))),spansToString(l)}function renderBanner(e,t={}){const r=themeOf(e),n=Math.max(20,Number(t.width)||80),s=[];s.push(`${r.gold}${GLYPH.ruleHeavy}${GLYPH.rule.repeat(Math.max(0,n-2))}${GLYPH.ruleHeavy}${RESET}`),s.push("");const o=welcomeArtParts();if(n>=o.width+2){const t=Math.max(0,Math.floor((n-o.width)/2));for(const r of o.rows)s.push(artRow(e,r,o,t))}else s.push(centerStyled("AEGIS CODE",n,r.gold+BOLD));s.push("");const a=!1===t.firstRun?WELCOME_BACK:WELCOME_TITLE;s.push(centerStyled(a,n,r.coral+BOLD));const l=[t.version?`v${t.version}`:null,TAGLINE].filter(Boolean).join(` ${GLYPH.bullet} `);return s.push(centerStyled(l,n,r.gray)),s.push(""),s.push(...renderIdentityBox(e,t,n)),s}function renderIdentityBox(e,t={},r=80){const n=themeOf(e),s=[renderHeading(e,"aegiscode",r)],o=[["version",t.version?`v${t.version}`:null],["model",t.model||"server default"],["base",t.base||""],["key",t.key||"not set"],["render",!1===t.stream?"buffered":"streaming"]].filter((([,e])=>e));for(const[e,t]of o){const o=clip(String(t),Math.max(0,r-12));s.push(` ${n.gray}${e.padEnd(8)}${RESET}${n.white}${o}${RESET}`)}const a=clip(` type /help for commands ${GLYPH.bullet} /quit to exit`,r);return s.push(""),s.push(`${n.dim}${a}${RESET}`),s}function mdLines(e,t,r){const n=themeOf(r),s=[];let o=!1;const a=Math.max(20,t-4);for(const t of String(null==e?"":e).split("\n")){if(/^\s*```/.test(t)){o=!o;continue}if(o){for(const e of wrapBlock(t,a))s.push(`${n.gray} ${e}${RESET}`);continue}if(""===t.trim()){s.push("");continue}const e=/^(\s*)[-*]\s+(.*)$/.exec(t);if(e){const t=" ".repeat(Math.min(6,e[1].length));for(const o of wrapBlock(inline(e[2],r),a-2))s.push(`${t}${n.gray}${GLYPH.bullet}${RESET} ${o}`);continue}const l=/^(#{1,6})\s+(.*)$/.exec(t);if(l)s.push(`${n.gold}${BOLD}${inline(l[2],r)}${RESET}`);else for(const e of wrapBlock(inline(t,r),a,""))s.push(e)}return s}function inline(e,t){const r=themeOf(t);return String(null==e?"":e).replace(/`([^`]+)`/g,((e,t)=>`${r.green}${t}${RESET}`)).replace(/\*\*([^*]+)\*\*/g,((e,t)=>`${BOLD}${t}${RESET}`))}function assistantLines(e,t,r){return markdown&&"function"==typeof markdown.renderMarkdown?markdown.renderMarkdown(String(null==t?"":t),r,e).map(spansToString):mdLines(t,r,e)}function renderTurn(e,t,r=80){const n=themeOf(e),s=t.role||"assistant",o=String(null==t.text?"":t.text),a=[];if("user"===s)wrapBlock(o,Math.max(8,r-2)).forEach(((e,t)=>{0===t?a.push(`${n.gray}${GLYPH.cursor}${RESET} ${n.white}${e}${RESET}`):a.push(` ${n.white}${e}${RESET}`)}));else if("assistant"===s||"system"===s){const t=assistantLines(e,o,Math.max(8,r-2));t.length||t.push(""),t[0]=`${n.white}${GLYPH.block}${RESET} `+t[0],a.push(...t)}else if("tool"===s){const s=void 0===t.ok?"":t.ok?` ${n.green}${GLYPH.check}${RESET}`:` ${n.red}${errMark()}${RESET}`;a.push(`${n.gray}${t.label||"tool"}${RESET}${s}`);const o=null==t.args?"":"string"==typeof t.args?t.args:JSON.stringify(t.args),l=t.label&&(t.label.includes("writeFile")||t.label.includes("Write"));if(l&&t.args){const n=extractNewContent(t.label.split(/\s+/)[1],t.args);if(n){const s=t.args.file_path||t.args.path,o=extractPreview(s,n);o&&a.push(...renderFilePreview(o,e,r))}}t.diff&&!l?a.push(...renderDiffBlock(t.diff,e,r,{open:!!t.diffOpen})):o&&!l&&a.push(` ${n.gray}${GLYPH.hook} $ ${clip(o,Math.max(0,r-6))}${RESET}`)}else if("error"===s)a.push(`${n.red}${errMark()} ${o}${RESET}`);else for(const e of wrapBlock(o,Math.max(8,r-2)))a.push(`${n.white}${e}${RESET}`);if(t.meta){const n=renderMeta(e,t.meta,r);n&&a.push(n)}return a}function renderMeta(e,t={},r=80){const n=themeOf(e),s=[];t.model&&s.push(`${n.blue}${t.model}${RESET}`);const o=t.usage&&"object"==typeof t.usage?t.usage:t,a=fmtUsageSplit(o);if(a)s.push(`${n.white}${a.output}${RESET}`);else{const e=displayTokens(o);null!=e&&s.push(`${n.white}${fmtTokens(e)} tokens${RESET}`)}if(null!=t.eur&&feeBillable()&&s.push(`${t.eur>0?n.coral:n.green}${fmtEur(t.eur)}${RESET}`),null!=t.ms&&s.push(`${n.gray}${fmtElapsed(t.ms)}${RESET}`),t.calls>1&&s.push(`${n.gray}${t.calls} calls${RESET}`),!s.length)return"";const l=`${n.dim} ${GLYPH.bullet} ${RESET}`;return`${n.dim}${GLYPH.hook} ${RESET}${s.join(l)}`}function renderStatus(e,t={},r=80){const n=themeOf(e),s=["aegis"];t.model&&s.push(t.model),null!=t.tokens&&s.push(`${fmtTokens(t.tokens)} tokens`),null!=t.spend&&s.push(fmtEur(t.spend)),t.mode&&s.push(t.mode);const o=t.hint||"ctrl+c quit",a=` ${s.join(` ${GLYPH.bullet} `)} `,l=r-w(a)-w(o)-1,i=l>0?a+" ".repeat(l)+o+" ":clip(a,r);return`${n.gray}${pad(i,r)}${RESET}`}function renderWorking(e,t={}){const r=themeOf(e);if(t.done){const e=t.verb||DONE_VERBS[t.tools?1:0]||DONE_VERBS[0],n=null!=t.secs?t.secs:Math.max(1,Math.round((t.elapsedMs||0)/1e3));return`${r.gray}${GLYPH.bloom} ${e} for ${n}s${RESET}`}const n=GLYPH.spin[Math.abs(Math.floor(t.tick||0))%GLYPH.spin.length],s=t.verb||VERBS[0],o=[];null!=t.elapsedMs&&o.push(fmtElapsed(t.elapsedMs)),null!=t.streamed&&o.push(`↓${t.streamedFloor?"≥":""}${fmtTokens(t.streamed)} tokens`);const a=o.length?` ${r.gray}(${o.join(` ${GLYPH.bullet} `)})${RESET}`:"";return`${r.coral}${n}${RESET} ${r.white}${s}${RESET}${r.white}…${RESET}${a}${r.dim} esc to interrupt${RESET}`}function renderHeading(e,t,r=80){const n=themeOf(e),s=` ${t} `,o=Math.max(0,r-w(s)),a=Math.floor(o/2),l=GLYPH.rule;return`${n.gray}${l.repeat(a)}${RESET}${n.gold}${BOLD}${s}${RESET}${n.gray}${l.repeat(Math.max(0,o-a))}${RESET}`}function renderToolResult(e,t,r,n=80){const s=themeOf(e),o=[renderHeading(e,t,n)];for(const e of wrapBlock(String(null==r?"":r),Math.max(8,n-2)))o.push(e?` ${s.white}${e}${RESET}`:"");return o}function renderApproval(e,t={},r=80){const n=themeOf(e),s=[renderHeading(e,`confirm ${t.tool||"tool"}`,r)],o=t.diff?t.diff:null==t.args?"":"string"==typeof t.args?t.args:JSON.stringify(t.args);for(const e of wrapBlock(o,Math.max(8,r-2)))s.push(e?` ${n.gray}${e}${RESET}`:"");return s.push(""),s.push(` ${n.coral}${GLYPH.bullet}${RESET} ${n.white}y${RESET}es once ${n.dim}${GLYPH.bullet}${RESET} ${n.white}s${RESET}ession ${n.dim}${GLYPH.bullet}${RESET} ${n.white}n${RESET}o ${n.dim}(default)${RESET}`),s}const NOTICE={info:["gray",()=>GLYPH.bullet],warn:["coral",warnMark],error:["red",errMark],ok:["green",()=>GLYPH.check]};function renderNotice(e,t,r){const n=themeOf(e),[s,o]=NOTICE[t]||NOTICE.info;return`${n[s]}${o()} ${r}${RESET}`}module.exports={renderBanner:renderBanner,renderIdentityBox:renderIdentityBox,renderTurn:renderTurn,renderMeta:renderMeta,renderStatus:renderStatus,renderWorking:renderWorking,renderHeading:renderHeading,renderToolResult:renderToolResult,renderApproval:renderApproval,renderNotice:renderNotice,mdLines:mdLines,inline:inline,artRow:artRow,tintWhale:tintWhale,fg:fg,bg:bg,UNDER:UNDER,ITALIC:ITALIC,RESET_FG:RESET_FG,RESET_BG:RESET_BG,pad:pad,padStart:padStart};
3
+ "use strict";const{RGB:RGB,BG:BG,RESET:RESET,BOLD:BOLD,DIM:DIM,ITALIC:ITALIC,UNDER:UNDER,RESET_FG:RESET_FG,RESET_BG:RESET_BG,GLYPH:GLYPH,VERBS:VERBS,DONE_VERBS:DONE_VERBS,themeOf:themeOf}=require("./theme.js"),{WELCOME_TITLE:WELCOME_TITLE,WELCOME_BACK:WELCOME_BACK,TAGLINE:TAGLINE,STAR:STAR,stencilGlyph:stencilGlyph,welcomeArtParts:welcomeArtParts}=require("./art.js"),{w:w,pad:pad,padStart:padStart,wrapBlock:wrapBlock,clip:clip,span:span}=require("./screen.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,fmtElapsed:fmtElapsed,fmtUsageSplit:fmtUsageSplit,displayTokens:displayTokens,feeBillable:feeBillable}=require("./format.js"),{renderDiffBlock:renderDiffBlock}=require("./diffview.js");let markdown=null;try{markdown=require("./markdown.js")}catch{markdown=null}const errMark=()=>GLYPH.err,warnMark=()=>GLYPH.warn,fg=(e,t)=>`${t}`,bg=e=>BG(...e),spansToString=e=>e.map((e=>(e.s||"")+e.t)).join("")+RESET;function centerStyled(e,t,r){const n=clip(e,t),s=Math.max(0,Math.floor((t-w(n))/2));return" ".repeat(s)+r+n+RESET}function tintWhale(e,t){const r={"▓":t.blue,"▒":t.lavender,"░":t.dim,"█":t.white,[STAR]:t.gold,"·":t.dim},n={};for(const e of Object.keys(r))n[stencilGlyph(e)]=r[e];const s=[];let o=null,a="";for(const t of e){const e=null!=n[t]?n[t]:"";null!==o&&e===a?o+=t:(null!==o&&s.push(span(a,o)),o=t,a=e)}return null!==o&&s.push(span(a,o)),s}function artRow(e,t,r,n){const s=themeOf(e),o=t[0]||"",a=t[1]||"",l=[span(""," ".repeat(n))];return o&&a?(l.push(span(s.gold,o)),l.push(span(""," ".repeat(r.gutter))),l.push(...tintWhale(a,s))):o?(l.push(span(s.gold,o)),w(o)<r.width&&l.push(span(""," ".repeat(r.width-w(o))))):a?(l.push(...tintWhale(a,s)),w(a)<r.width&&l.push(span(""," ".repeat(r.width-w(a))))):l.push(span(""," ".repeat(r.width))),spansToString(l)}function renderBanner(e,t={}){const r=themeOf(e),n=Math.max(20,Number(t.width)||80),s=[];s.push(`${r.gold}${GLYPH.ruleHeavy}${GLYPH.rule.repeat(Math.max(0,n-2))}${GLYPH.ruleHeavy}${RESET}`),s.push("");const o=welcomeArtParts();if(n>=o.width+2){const t=Math.max(0,Math.floor((n-o.width)/2));for(const r of o.rows)s.push(artRow(e,r,o,t))}else s.push(centerStyled("AEGIS CODE",n,r.gold+BOLD));s.push("");const a=!1===t.firstRun?WELCOME_BACK:WELCOME_TITLE;s.push(centerStyled(a,n,r.coral+BOLD));const l=[t.version?`v${t.version}`:null,TAGLINE].filter(Boolean).join(` ${GLYPH.bullet} `);return s.push(centerStyled(l,n,r.gray)),s.push(""),s.push(...renderIdentityBox(e,t,n)),s}function renderIdentityBox(e,t={},r=80){const n=themeOf(e),s=[renderHeading(e,"aegiscode",r)],o=[["version",t.version?`v${t.version}`:null],["model",t.model||"server default"],["base",t.base||""],["key",t.key||"not set"],["render",!1===t.stream?"buffered":"streaming"]].filter((([,e])=>e));for(const[e,t]of o){const o=clip(String(t),Math.max(0,r-12));s.push(` ${n.gray}${e.padEnd(8)}${RESET}${n.white}${o}${RESET}`)}const a=clip(` type /help for commands ${GLYPH.bullet} /quit to exit`,r);return s.push(""),s.push(`${n.dim}${a}${RESET}`),s}function mdLines(e,t,r){const n=themeOf(r),s=[];let o=!1;const a=Math.max(20,t-4);for(const t of String(null==e?"":e).split("\n")){if(/^\s*```/.test(t)){o=!o;continue}if(o){for(const e of wrapBlock(t,a))s.push(`${n.gray} ${e}${RESET}`);continue}if(""===t.trim()){s.push("");continue}const e=/^(\s*)[-*]\s+(.*)$/.exec(t);if(e){const t=" ".repeat(Math.min(6,e[1].length));for(const o of wrapBlock(inline(e[2],r),a-2))s.push(`${t}${n.gray}${GLYPH.bullet}${RESET} ${o}`);continue}const l=/^(#{1,6})\s+(.*)$/.exec(t);if(l)s.push(`${n.gold}${BOLD}${inline(l[2],r)}${RESET}`);else for(const e of wrapBlock(inline(t,r),a,""))s.push(e)}return s}function inline(e,t){const r=themeOf(t);return String(null==e?"":e).replace(/`([^`]+)`/g,((e,t)=>`${r.green}${t}${RESET}`)).replace(/\*\*([^*]+)\*\*/g,((e,t)=>`${BOLD}${t}${RESET}`))}function assistantLines(e,t,r){return markdown&&"function"==typeof markdown.renderMarkdown?markdown.renderMarkdown(String(null==t?"":t),r,e).map(spansToString):mdLines(t,r,e)}function renderTurn(e,t,r=80){const n=themeOf(e),s=t.role||"assistant",o=String(null==t.text?"":t.text),a=[];if("user"===s)wrapBlock(o,Math.max(8,r-2)).forEach(((e,t)=>{0===t?a.push(`${n.gray}${GLYPH.cursor}${RESET} ${n.white}${e}${RESET}`):a.push(` ${n.white}${e}${RESET}`)}));else if("assistant"===s||"system"===s){const t=assistantLines(e,o,Math.max(8,r-2));t.length||t.push(""),t[0]=`${n.white}${GLYPH.block}${RESET} `+t[0],a.push(...t)}else if("tool"===s){const s=void 0===t.ok?"":t.ok?` ${n.green}${GLYPH.check}${RESET}`:` ${n.red}${errMark()}${RESET}`;a.push(`${n.gray}${t.label||"tool"}${RESET}${s}`);const o=null==t.args?"":"string"==typeof t.args?t.args:JSON.stringify(t.args);t.diff?a.push(...renderDiffBlock(t.diff,e,r,{open:!!t.diffOpen})):o&&a.push(` ${n.gray}${GLYPH.hook} $ ${clip(o,Math.max(0,r-6))}${RESET}`)}else if("error"===s)a.push(`${n.red}${errMark()} ${o}${RESET}`);else for(const e of wrapBlock(o,Math.max(8,r-2)))a.push(`${n.white}${e}${RESET}`);if(t.meta){const n=renderMeta(e,t.meta,r);n&&a.push(n)}return a}function renderMeta(e,t={},r=80){const n=themeOf(e),s=[];t.model&&s.push(`${n.blue}${t.model}${RESET}`);const o=t.usage&&"object"==typeof t.usage?t.usage:t,a=fmtUsageSplit(o);if(a)s.push(`${n.white}${a.output}${RESET}`);else{const e=displayTokens(o);null!=e&&s.push(`${n.white}${fmtTokens(e)} tokens${RESET}`)}if(null!=t.eur&&feeBillable()&&s.push(`${t.eur>0?n.coral:n.green}${fmtEur(t.eur)}${RESET}`),null!=t.ms&&s.push(`${n.gray}${fmtElapsed(t.ms)}${RESET}`),t.calls>1&&s.push(`${n.gray}${t.calls} calls${RESET}`),!s.length)return"";const l=`${n.dim} ${GLYPH.bullet} ${RESET}`;return`${n.dim}${GLYPH.hook} ${RESET}${s.join(l)}`}function renderStatus(e,t={},r=80){const n=themeOf(e),s=["aegis"];t.model&&s.push(t.model),null!=t.tokens&&s.push(`${fmtTokens(t.tokens)} tokens`),null!=t.spend&&s.push(fmtEur(t.spend)),t.mode&&s.push(t.mode);const o=t.hint||"ctrl+c quit",a=` ${s.join(` ${GLYPH.bullet} `)} `,l=r-w(a)-w(o)-1,i=l>0?a+" ".repeat(l)+o+" ":clip(a,r);return`${n.gray}${pad(i,r)}${RESET}`}function renderWorking(e,t={}){const r=themeOf(e);if(t.done){const e=t.verb||DONE_VERBS[t.tools?1:0]||DONE_VERBS[0],n=null!=t.secs?t.secs:Math.max(1,Math.round((t.elapsedMs||0)/1e3));return`${r.gray}${GLYPH.bloom} ${e} for ${n}s${RESET}`}const n=GLYPH.spin[Math.abs(Math.floor(t.tick||0))%GLYPH.spin.length],s=t.verb||VERBS[0],o=[];null!=t.elapsedMs&&o.push(fmtElapsed(t.elapsedMs)),null!=t.streamed&&o.push(`↓${t.streamedFloor?"≥":""}${fmtTokens(t.streamed)} tokens`);const a=o.length?` ${r.gray}(${o.join(` ${GLYPH.bullet} `)})${RESET}`:"";return`${r.coral}${n}${RESET} ${r.white}${s}${RESET}${r.white}…${RESET}${a}${r.dim} esc to interrupt${RESET}`}function renderHeading(e,t,r=80){const n=themeOf(e),s=` ${t} `,o=Math.max(0,r-w(s)),a=Math.floor(o/2),l=GLYPH.rule;return`${n.gray}${l.repeat(a)}${RESET}${n.gold}${BOLD}${s}${RESET}${n.gray}${l.repeat(Math.max(0,o-a))}${RESET}`}function renderToolResult(e,t,r,n=80){const s=themeOf(e),o=[renderHeading(e,t,n)];for(const e of wrapBlock(String(null==r?"":r),Math.max(8,n-2)))o.push(e?` ${s.white}${e}${RESET}`:"");return o}function renderApproval(e,t={},r=80){const n=themeOf(e),s=[renderHeading(e,`confirm ${t.tool||"tool"}`,r)],o=t.diff?t.diff:null==t.args?"":"string"==typeof t.args?t.args:JSON.stringify(t.args);for(const e of wrapBlock(o,Math.max(8,r-2)))s.push(e?` ${n.gray}${e}${RESET}`:"");return s.push(""),s.push(` ${n.coral}${GLYPH.bullet}${RESET} ${n.white}y${RESET}es once ${n.dim}${GLYPH.bullet}${RESET} ${n.white}s${RESET}ession ${n.dim}${GLYPH.bullet}${RESET} ${n.white}n${RESET}o ${n.dim}(default)${RESET}`),s}const NOTICE={info:["gray",()=>GLYPH.bullet],warn:["coral",warnMark],error:["red",errMark],ok:["green",()=>GLYPH.check]};function renderNotice(e,t,r){const n=themeOf(e),[s,o]=NOTICE[t]||NOTICE.info;return`${n[s]}${o()} ${r}${RESET}`}module.exports={renderBanner:renderBanner,renderIdentityBox:renderIdentityBox,renderTurn:renderTurn,renderMeta:renderMeta,renderStatus:renderStatus,renderWorking:renderWorking,renderHeading:renderHeading,renderToolResult:renderToolResult,renderApproval:renderApproval,renderNotice:renderNotice,mdLines:mdLines,inline:inline,artRow:artRow,tintWhale:tintWhale,fg:fg,bg:bg,UNDER:UNDER,ITALIC:ITALIC,RESET_FG:RESET_FG,RESET_BG:RESET_BG,pad:pad,padStart:padStart};
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
+ const{getSize:e,paint:t,span:r,lineWidth:n,clip:s,w:o}=require("./screen.js"),i=require("./events.js"),{nextKey:a,KEY:u}=i,{C:c,BOLD:h,BOLD_OFF:p,GLYPH:l,THEME_TABLE:m,themeOf:d,themeIsLight:f,terminalIsLight:y}=require("./theme.js"),{TAGLINE:g,TAGLINE_SHORT:k,welcomeArtParts:w}=require("./art.js"),{renderDiffPreview:x}=require("./markdown.js"),C=require("./render.js"),{updateConfig:T,configExists:E,loadConfig:I}=require("./config.js"),{updateNotice:S,updateLine:v,serverNotice:R,serverUpdateLine:L}=require("./update.js"),A=require("./credentials.js"),{signupUrl:N,signupDisplayUrl:b}=require("./signup.js"),{createSettingsStore:M,isReservedNamespace:P}=require("./deps.js"),_=require("../package.json").version,O="AEGIS Code",$=[" Run /init to create an AEGIS.md"," Use ↑↓ to recall past prompts"," Press / for commands"," Press Tab to complete a command"," Press ? for shortcuts"],j=[" 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"],K=["Your own provider key: /byok-key <provider> — works with your AEGIS key"],q=["AEGIS Cloud, one account key: /key — no provider signup"],D=["Your key, your bill: /byok-key <provider> — or AEGIS Cloud, /key"],G=[`AEGIS Desktop: same engine on your machine — ${b()}`];function U(){const e=[],t=re(),r=ne();return t&&r?e.push(...D):t?e.push(...K):r&&e.push(...q),e.length&&e.push(...G),e}function W(e,t,n){const i=s(String(e),Math.max(1,t)),a=Math.max(0,Math.floor((t-o(i))/2));return[r(""," ".repeat(a)),r(n,i)]}function Y(e,t,n,s=0){const i=String(e).split(" "),a=[];let u=[],c=0;for(const e of i)c+o(e)+1>t-4-s&&u.length?(a.push([r(""," ".repeat(s)),r(n,u.join(" "))]),u=[e],c=o(e)):(u.length&&c++,u.push(e),c+=o(e));return u.length&&a.push([r(""," ".repeat(s)),r(n,u.join(" "))]),a}function B(e,t,n=0,o=process.cwd()){const i=[];i.push([r(c.gold,"─".repeat(Math.max(1,t)))]),i.push([r(c.white+h,"Accessing workspace:")]),i.push([r(c.white+h,s(o,Math.max(1,t-1)))]),i.push([r("","")]);for(const e of Y("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))i.push(e);i.push([r("","")]),i.push([r(c.white,`${O} will be able to read, edit, and execute files here.`)]),i.push([r("","")]),i.push([r(c.white+h,"Security guide")]),i.push([r("","")]);for(let e=0;e<2;e++){const t=n===e,s=t?r(c.lavender,l.cursor):r(""," "),o=r(c.gray,` ${e+1}.`),a=0===e?"Yes, I trust this folder":"No, exit";i.push([s,o,r(t?c.lavender:c.white,a)])}return i.push([r("","")]),i.push([r(c.gray,`Enter to confirm ${l.bullet} Esc to cancel`)]),i}async function H(r){const{cols:n}=e();let s=0;const o=()=>t(B(0,n,s));for(o();;){const e=await a();if(e.name===u.UP||e.name===u.DOWN||e.name===u.TAB)s=1-s,o();else{if(e.name===u.ENTER)return 0===s;if(e.name===u.ESC||e.name===u.CTRL_C||e.name===u.CTRL_D)return!1;if("char"===e.name){const t=String(e.ch).trim();"1"===t&&(s=0,o()),"2"===t&&(s=1,o())}}}}function F(e,t){return m[t]||m[1],e.themeIndex=t,e.light=f(t),t}function z(e,t,n,s){const o=[];o.push([r(c.coral,`Welcome to ${O} v${_}`)]),o.push([r(c.white+h,"Let's get started.")]),o.push([r(c.white,"Choose the text style that looks best with your terminal")]),o.push([r(c.gray,"To change this later, run /theme")]),o.push([r("","")]);for(let e=0;e<m.length;e++){const t=m[e],n=s===e,i=n?r(c.lavender,l.cursor):r(""," "),a=r(c.gray,`${e+1}.`),u=n?r(c.green," "+l.check):r("","");o.push([i,a,r(n?c.lavender:c.white,t.name),...t.note?[r(c.gray," "+t.note)]:[],u])}for(const r of x(t,e))o.push(r);for(o.push([r(c.gray," Syntax theme: Monokai Extended (ctrl+t to disable)")]);o.length<n-1;)o.push([r("","")]);return o}async function Q(r,n=`Welcome to ${O}`){const{cols:s,rows:o}=e();let i="number"==typeof r.themeIndex?r.themeIndex:y()?2:1;const c=()=>t(z(r,s,o,i));for(c();;){const e=await a();if(e.name===u.UP)i=Math.max(0,i-1),c();else if(e.name===u.DOWN)i=Math.min(m.length-1,i+1),c();else{if(e.name===u.ENTER||e.name===u.ESC||e.name===u.CTRL_C||e.name===u.CTRL_D)return F(r,i);if(e.name===u.CTRL_T)r.light=!r.light,c();else if("char"===e.name){const t=parseInt(e.ch,10);t>=1&&t<=m.length&&(i=t-1,c())}}}}function J(e,t,n,s=!0){const i=d(e),a=[];a.push([r(i.gold,"━"+"─".repeat(Math.max(0,t-2))+"━")]),a.push([r("","")]);let u=null;try{const e=I(),t=S({current:_,cache:e.updateCheck,save:e=>{try{T({updateCheck:e})}catch{}}});u=v({current:_,...t});const r=R({current:_,cache:e.updateCheckServer,save:e=>{try{T({updateCheckServer:e})}catch{}}});u=L(r)||u}catch{}const c=w();if(t>=c.width+2){const r=Math.max(0,Math.floor((t-c.width)/2));for(const t of c.rows)a.push(Z(C.artRow(e,t,c,r)))}else a.push(W(`${O}`,t,i.gold+h));u&&(a.push([r("","")]),a.push(W(u,t,i.gold))),a.push([r("","")]);const p=s?`Welcome to ${O}`:"Welcome back!";a.push(W(p,t,i.coral+h));const m=t>=o(g)+4?g:k;a.push(W(m,t,i.gray)),a.push([r("","")]),a.push(...X(i,t,a.length)),a.push([r("","")]);for(const e of U())a.push(...Y(e,t,i.white,1));for(a.push([r(i.gray,l.hint),r(i.white,' Try "write a test for <filepath>"')]);a.length<n-1;)a.push([r("","")]);return a}function V(e,t,n,i){const a=Math.max(1,i-4),u=` ${s(t,Math.max(0,i-4))} `,c=[[r(e.gray,"╭─"),r(e.gray+h,u),r(e.gray,"─".repeat(Math.max(0,i-3-u.length))+"╮")]];for(const t of n){const n=s(String(t),a);c.push([r(e.gray,"│ "),r(e.white,n+" ".repeat(Math.max(0,a-o(n)))),r(e.gray," │")])}return c.push([r(e.gray,"╰"+"─".repeat(a+2)+"╯")]),c}function X(e,t,n){const s=Math.floor((t-2)/2),o=$.map((e=>`${l.pointer}${e}`)),i=j,a=`Models & keys · v${_}`;if(s>=30){let t=V(e,"Tips for getting started",o,s),n=V(e,a,i,s);const u=Math.max(t.length,n.length),c=t=>{if(t.length>=u)return t;const n=t.slice(0,t.length-1),o=[r(e.gray,"│ "),r(""," ".repeat(Math.max(0,s-4))),r(e.gray," │")];for(;n.length<u-1;)n.push(o);return n.push(t[t.length-1]),n};t=c(t),n=c(n);const h=[];for(let e=0;e<u;e++)h.push([...t[e],r(""," ".repeat(2)),...n[e]]);return h}const u=Math.max(20,t-1);return[...V(e,"Tips for getting started",o,u),...V(e,a,i,u)]}function Z(e){const t=[],r=/\x1b\[[0-9;]*m/g;let n,s=0,o="";for(;null!==(n=r.exec(e));)n.index>s&&t.push(ee(o,e.slice(s,n.index))),o=n[0],s=n.index+n[0].length;return s<e.length&&t.push(ee(o,e.slice(s))),t}function ee(e,t){const n=r(e,t);return e&&(n.s=e,n.w=o(t)),n}function te(){try{return M({dir:A.aegisHome()}).list().some((e=>{if(!e||!e.provider||P(e.provider))return!1;const t="string"==typeof e.baseURL?e.baseURL.trim():"";return Boolean(e.configured||t)}))}catch{return!1}}function re(){try{return!te()}catch{return!0}}function ne(){try{return!A.keyStatus().configured}catch{return!0}}async function se(r,n=!0){for((()=>{const{cols:s,rows:o}=e();t(J(r,s,o,n))})();;){const e=await a();if(e.name===u.ENTER||e.name===u.ESC)return{exit:!1};if(e.name===u.CTRL_C||e.name===u.CTRL_D)return{exit:!0}}}const oe=N("key_screen");function ie(e,t,{value:n="",error:s=null,verify:i=!1}={}){const a=d(e),u=[];u.push([r(a.gold,"─".repeat(Math.max(1,t)))]),u.push([r(a.white+h,"Connect your AEGIS account")]),u.push([r("","")]);for(const e of Y("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,a.white))u.push(e);u.push([r("","")]);const c=" No key yet? Free one at ";return o(c)+o(oe)+2<=t?u.push([r(a.white,c),r(a.cyan,oe)]):(u.push([r(a.white," No key yet? Free one:")]),u.push([r(a.cyan,` ${oe}`)])),u.push([r("","")]),u.push([r(a.lavender,l.cursor),r(a.gray," API key: "),r(a.white,"•".repeat(String(n).length)),r(i?a.cyan:a.gray,i?" verifying…":"")]),s&&u.push([r(a.coral,` ${s}`)]),u.push([r("","")]),u.push([r(a.gray,` ${l.check} `),r(a.gray,"Enter to save"),r(a.gray," · "),r(a.gray,"Esc to skip")]),u}async function ae(r,n={}){const s=n.submit||(async()=>({ok:!0})),{cols:o}=e();let i="",c=null,h=!1;const p=()=>t(ie(r,o,{value:i,error:c,verify:h}));for(p();;){const e=await a();if(e.name===u.ENTER){if(!i.trim())return{skipped:!0};let e;h=!0,c=null,p();try{e=await s(i)}catch(t){e={ok:!1,message:t&&t.message||String(t)}}if(h=!1,e&&!1===e.ok){c=e.message||"that key was refused",p();continue}return{key:i,result:e}}if(e.name===u.ESC)return{skipped:!0};if(e.name===u.CTRL_C||e.name===u.CTRL_D)return{exit:!0};if(e.name!==u.BACKSPACE)if("char"!==e.name)"paste"===e.name&&e.text&&(i=(i+String(e.text)).replace(/\s+/g,""),c=null,p());else{const t=e.ch;t&&t>=" "&&(i+=t,c=null,p())}else i=i.slice(0,-1),c=null,p()}}module.exports={PRODUCT:O,TIPS:$,KEY_HELP:j,CONNECT_BYOK:K,CONNECT_CLOUD:q,CONNECT_BOTH:D,CONNECT_DESKTOP:G,connectRows:U,connectNeeded:function(){try{return re()||ne()}catch{return!0}},byokRouteNeeded:re,cloudRouteNeeded:ne,providerRouteConfigured:te,trustLines:B,themePickerLines:z,keyLines:ie,applyTheme:F,welcomeLines:J,boxes:X,boxLines:V,centered:W,wrapped:Y,wrapPlain:Z,showTrustCheck:H,showThemePicker:Q,requestApiKey:ae,showWelcome:se,runOnboarding:async function(e,t={}){const r=t.seen||E,n=t.save||T,s={showTrustCheck:H,showThemePicker:Q,showWelcome:se,requestApiKey:(e,r)=>ae(e,{submit:t.submitKey||(async()=>({ok:!0})),...r}),...t.ui||{}},o=t.needsKey||(()=>!A.hasApiKey()),a=t.canPrompt||(()=>!(!process.stdin||!process.stdin.isTTY)),u={set:!1,skipped:!1};if(t.continue)return{ok:!0,firstRun:!1,themeIndex:e.themeIndex,key:{set:!1,skipped:!1}};const c=!i.isKeyStreamAttached()&&!(!process.stdin||!process.stdin.isTTY);c&&i.attachKeyStream(process.stdin);try{return await async function(){if(!r()){if(!await s.showTrustCheck(e))return{ok:!1,firstRun:!0,themeIndex:e.themeIndex,key:u};if(await s.showThemePicker(e),n({themeIndex:e.themeIndex,light:e.light}),await h())return{ok:!1,firstRun:!0,themeIndex:e.themeIndex,key:u};const t=await s.showWelcome(e,!0);return t&&t.exit?{ok:!1,firstRun:!0,themeIndex:e.themeIndex,key:u}:{ok:!0,firstRun:!0,themeIndex:e.themeIndex,key:u}}if(await h())return{ok:!1,firstRun:!1,themeIndex:e.themeIndex,key:u};const t=await s.showWelcome(e,!1);return t&&t.exit?{ok:!1,firstRun:!1,themeIndex:e.themeIndex,key:u}:{ok:!0,firstRun:!1,themeIndex:e.themeIndex,key:u}}()}finally{c&&i.detachKeyStream()}async function h(){if(!o()||!a())return!1;const t=await s.requestApiKey(e);return!(!t||!t.exit)||(t&&t.key?u.set=!0:u.skipped=!0,!1)}},KEY_URL:oe};
package/src/theme.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{caps:caps,detect:detect,onCapsChange:onCapsChange,rgb:rgb,bg:bg}=require("./caps.js"),{STAR:STAR,stencilGlyph:stencilGlyph}=require("./art.js"),RESET="",BOLD="",DIM="",ITALIC="",UNDER="",BOLD_OFF="",ITALIC_OFF="",UNDER_OFF="",RESET_FG="",RESET_BG="",RGB=(e,t,n)=>rgb(e,t,n),BG=(e,t,n)=>bg(e,t,n),C={},LIGHT={},CB_DARK={},CB_LIGHT={},ANSI_DARK={},ANSI_LIGHT={};function buildDark(){return{gold:RGB(255,193,7),coral:RGB(215,119,87),lavender:RGB(177,185,249),blue:RGB(120,160,250),green:RGB(78,186,101),red:RGB(220,90,90),gray:RGB(153,153,153),dim:RGB(80,80,80),white:RGB(255,255,255),black:RGB(30,30,30),darkBg:RGB(20,20,20)}}function buildLight(){return{gold:RGB(180,130,0),coral:RGB(190,100,70),lavender:RGB(120,130,220),blue:RGB(70,110,220),green:RGB(60,150,80),red:RGB(200,60,60),gray:RGB(110,110,110),dim:RGB(170,170,170),white:RGB(40,40,40),black:RGB(245,245,245),darkBg:RGB(255,255,255)}}function buildCbDark(){return{...buildDark(),green:RGB(86,182,194),red:RGB(255,146,43),gold:RGB(255,203,71)}}function buildCbLight(){return{...buildLight(),green:RGB(30,130,145),red:RGB(200,100,20),gold:RGB(150,110,0)}}const A=e=>caps().color?`[${e}m`:"";function buildAnsiDark(){return{gold:A(93),coral:A(91),lavender:A(94),blue:A(94),green:A(92),red:A(91),gray:A(90),dim:A(90),white:A(97),black:A(40),darkBg:caps().color?"":""}}function buildAnsiLight(){return{gold:A(33),coral:A(31),lavender:A(34),blue:A(34),green:A(32),red:A(31),gray:A(90),dim:A(37),white:A(30),black:A(47),darkBg:caps().color?"":""}}const DIFF={},DIFF_LIGHT={};function buildDiff(){return{delFg:RGB(220,90,90),delBg:BG(61,1,0),delHiFg:RGB(248,248,242),delHiBg:BG(92,2,0),addFg:RGB(80,200,80),addBg:BG(2,40,0),addHiFg:RGB(255,255,255),addHiBg:BG(4,71,0),codeFg:RGB(248,248,242),gutter:RGB(120,120,120),kw:RGB(102,217,239),fn:RGB(166,226,46),str:RGB(230,219,116),num:RGB(174,129,255),comment:RGB(117,113,94)}}function buildDiffLight(){return{delFg:RGB(160,40,40),delBg:BG(255,235,233),delHiFg:RGB(90,0,0),delHiBg:BG(255,205,200),addFg:RGB(30,130,40),addBg:BG(232,250,232),addHiFg:RGB(0,80,0),addHiBg:BG(195,240,195),codeFg:RGB(40,40,40),gutter:RGB(150,150,150),kw:RGB(0,120,160),fn:RGB(80,140,0),str:RGB(150,110,0),num:RGB(120,60,200),comment:RGB(140,140,130)}}const THEMES={dark:C,light:LIGHT},THEME_TABLE=[{name:"Auto",note:"(match terminal)",light:!1,palette:C},{name:"Dark mode",note:"",light:!1,palette:C},{name:"Light mode",note:"",light:!0,palette:LIGHT},{name:"Dark mode",note:"(colorblind-friendly)",light:!1,palette:CB_DARK},{name:"Light mode",note:"(colorblind-friendly)",light:!0,palette:CB_LIGHT},{name:"Dark mode",note:"(ANSI colors only)",light:!1,palette:ANSI_DARK},{name:"Light mode",note:"(ANSI colors only)",light:!0,palette:ANSI_LIGHT}],AUTO_THEME_INDEX=0;function terminalIsLight(e=caps()){return"light"===e.background}function themeIsLight(e,t=caps()){const n=THEME_TABLE[e];return!!n&&(e===AUTO_THEME_INDEX?terminalIsLight(t):!!n.light)}const SIBLING_THEME_INDEX=[0,2,1,4,3,6,5];function themeContradicts(e,t=caps()){const n=THEME_TABLE[e];return!(!n||e===AUTO_THEME_INDEX||!t||!t.backgroundKnown||!!n.light==("light"===t.background))}function reconcileThemeIndex(e,t=caps()){const n=THEME_TABLE[e];if(!themeContradicts(e,t))return{index:e,changed:!1,reason:"",from:n||null};const i=SIBLING_THEME_INDEX[e],r=THEME_TABLE[i],l=e=>`${e.name}${e.note?" "+e.note:""}`;return{index:i,changed:!0,from:n,reason:`saved theme "${l(n)}" is unreadable on this ${t.background} terminal (${t.reasons.background}) — using "${l(r)}" instead`}}function themeForIndex(e){const t=THEME_TABLE[e];return t?t.palette:C}function themeOf(e){return e&&"number"==typeof e.themeIndex&&e.themeIndex>=3&&e.themeIndex<=6?themeForIndex(e.themeIndex):e&&e.themeIndex===AUTO_THEME_INDEX?terminalIsLight()?LIGHT:C:e&&e.light?LIGHT:C}function diffOf(e){return(e&&"number"==typeof e.themeIndex&&e.themeIndex>=3&&e.themeIndex<=6?THEME_TABLE[e.themeIndex].light:e&&e.themeIndex===AUTO_THEME_INDEX?terminalIsLight():e&&e.light)?DIFF_LIGHT:DIFF}function glyphsFor(e=null){const t=e?"string"==typeof e?detect(process.env,process.stdout,e):e:caps(),n="ascii"===t.glyphs,i=n||"edges"===t.face;if(n)return{cursor:">",check:"+",divider:"-",bullet:".",hint:">",pause:"||",star:stencilGlyph(STAR,t),rightarrow:"->",pointer:">",hook:"_|",block:"*",bloom:"*",spin:["|","/","-","\\","*","-"],ellipse:"...",err:"x",warn:"!",rule:"-",ruleHeavy:"="};const r={cursor:"❯",check:"✔",divider:"╌",bullet:"·",hint:"❯",pause:i?"❚❚":"⏸",star:stencilGlyph(STAR,t),rightarrow:"→",pointer:"▸",hook:i?"_|":"⎿",block:"●",bloom:"✻",spin:["✢","·","✻","*","✽","✶"],ellipse:"…",err:"✗",warn:"⚠",rule:"─",ruleHeavy:"━"};return i?{...r,bloom:"*",spin:["|","/","-","\\","*","-"]}:r}const GLYPH=glyphsFor(),VERBS=["Incubating","Tempering","Determining","Beboppin'","Julienning","Inferring","Simmering","Twisting","Fermenting","Fiddle-faddling","Orbiting","Prestidigitating"],DONE_VERBS=["Churned","Worked"];function rematerialize(){Object.assign(C,buildDark()),Object.assign(LIGHT,buildLight()),Object.assign(CB_DARK,buildCbDark()),Object.assign(CB_LIGHT,buildCbLight()),Object.assign(ANSI_DARK,buildAnsiDark()),Object.assign(ANSI_LIGHT,buildAnsiLight()),Object.assign(DIFF,buildDiff()),Object.assign(DIFF_LIGHT,buildDiffLight()),Object.assign(GLYPH,glyphsFor())}rematerialize(),onCapsChange(rematerialize),module.exports={RGB:RGB,BG:BG,RESET:RESET,BOLD:BOLD,DIM:DIM,ITALIC:"",UNDER:UNDER,BOLD_OFF:"",ITALIC_OFF:"",UNDER_OFF:"",RESET_FG:"",RESET_BG:"",C:C,LIGHT:LIGHT,DIFF:DIFF,DIFF_LIGHT:DIFF_LIGHT,diffOf:diffOf,CB_DARK:CB_DARK,CB_LIGHT:CB_LIGHT,ANSI_DARK:ANSI_DARK,ANSI_LIGHT:ANSI_LIGHT,THEMES:THEMES,THEME_TABLE:THEME_TABLE,AUTO_THEME_INDEX:AUTO_THEME_INDEX,themeIsLight:themeIsLight,terminalIsLight:terminalIsLight,themeForIndex:themeForIndex,themeContradicts:themeContradicts,reconcileThemeIndex:reconcileThemeIndex,SIBLING_THEME_INDEX:SIBLING_THEME_INDEX,GLYPH:GLYPH,glyphsFor:glyphsFor,VERBS:VERBS,DONE_VERBS:DONE_VERBS,themeOf:themeOf,rematerialize:rematerialize};
3
+ const{caps:e,detect:n,onCapsChange:t,rgb:r,bg:i}=require("./caps.js"),{STAR:o,stencilGlyph:d}=require("./art.js"),l=(e,n,t)=>r(e,n,t),a=(e,n,t)=>i(e,n,t),g={},c={},s={},m={},u={},h={};function b(){return{gold:l(255,193,7),coral:l(215,119,87),lavender:l(177,185,249),blue:l(120,160,250),green:l(78,186,101),red:l(220,90,90),gray:l(153,153,153),dim:l(80,80,80),white:l(255,255,255),black:l(30,30,30),darkBg:l(20,20,20)}}function I(){return{gold:l(180,130,0),coral:l(190,100,70),lavender:l(120,130,220),blue:l(70,110,220),green:l(60,150,80),red:l(200,60,60),gray:l(110,110,110),dim:l(170,170,170),white:l(40,40,40),black:l(245,245,245),darkBg:l(255,255,255)}}const p=n=>e().color?`[${n}m`:"",f={},k={},F={dark:g,light:c},B=[{name:"Auto",note:"(match terminal)",light:!1,palette:g},{name:"Dark mode",note:"",light:!1,palette:g},{name:"Light mode",note:"",light:!0,palette:c},{name:"Dark mode",note:"(colorblind-friendly)",light:!1,palette:s},{name:"Light mode",note:"(colorblind-friendly)",light:!0,palette:m},{name:"Dark mode",note:"(ANSI colors only)",light:!1,palette:u},{name:"Light mode",note:"(ANSI colors only)",light:!0,palette:h}];function E(n=e()){return"light"===n.background}const H=[0,2,1,4,3,6,5];function O(n,t=e()){const r=B[n];return!(!r||0===n||!t||!t.backgroundKnown||!!r.light==("light"===t.background))}function T(e){const n=B[e];return n?n.palette:g}function _(t=null){const r=t?"string"==typeof t?n(process.env,process.stdout,t):t:e(),i="ascii"===r.glyphs,l=i||"edges"===r.face;if(i)return{cursor:">",check:"+",divider:"-",bullet:".",hint:">",pause:"||",star:d(o,r),rightarrow:"->",pointer:">",hook:"_|",block:"*",bloom:"*",spin:["|","/","-","\\","*","-"],ellipse:"...",err:"x",warn:"!",rule:"-",ruleHeavy:"="};const a={cursor:"❯",check:"✔",divider:"╌",bullet:"·",hint:"❯",pause:l?"❚❚":"⏸",star:d(o,r),rightarrow:"→",pointer:"▸",hook:l?"_|":"⎿",block:"●",bloom:"✻",spin:["✢","·","✻","*","✽","✶"],ellipse:"…",err:"✗",warn:"⚠",rule:"─",ruleHeavy:"━"};return l?{...a,bloom:"*",spin:["|","/","-","\\","*","-"]}:a}const x=_();function y(){Object.assign(g,b()),Object.assign(c,I()),Object.assign(s,{...b(),green:l(86,182,194),red:l(255,146,43),gold:l(255,203,71)}),Object.assign(m,{...I(),green:l(30,130,145),red:l(200,100,20),gold:l(150,110,0)}),Object.assign(u,{gold:p(93),coral:p(91),lavender:p(94),blue:p(94),green:p(92),red:p(91),gray:p(90),dim:p(90),white:p(97),black:p(40),darkBg:e().color?"":""}),Object.assign(h,{gold:p(33),coral:p(31),lavender:p(34),blue:p(34),green:p(32),red:p(31),gray:p(90),dim:p(37),white:p(30),black:p(47),darkBg:e().color?"":""}),Object.assign(f,{delFg:l(220,90,90),delBg:a(61,1,0),delHiFg:l(248,248,242),delHiBg:a(92,2,0),addFg:l(80,200,80),addBg:a(2,40,0),addHiFg:l(255,255,255),addHiBg:a(4,71,0),codeFg:l(248,248,242),gutter:l(120,120,120),kw:l(102,217,239),fn:l(166,226,46),str:l(230,219,116),num:l(174,129,255),comment:l(117,113,94)}),Object.assign(k,{delFg:l(160,40,40),delBg:a(255,235,233),delHiFg:l(90,0,0),delHiBg:a(255,205,200),addFg:l(30,130,40),addBg:a(232,250,232),addHiFg:l(0,80,0),addHiBg:a(195,240,195),codeFg:l(40,40,40),gutter:l(150,150,150),kw:l(0,120,160),fn:l(80,140,0),str:l(150,110,0),num:l(120,60,200),comment:l(140,140,130)}),Object.assign(x,_())}y(),t(y),module.exports={RGB:l,BG:a,RESET:"",BOLD:"",DIM:"",ITALIC:"",UNDER:"",BOLD_OFF:"",ITALIC_OFF:"",UNDER_OFF:"",RESET_FG:"",RESET_BG:"",C:g,LIGHT:c,DIFF:f,DIFF_LIGHT:k,diffOf:function(e){return(e&&"number"==typeof e.themeIndex&&e.themeIndex>=3&&e.themeIndex<=6?B[e.themeIndex].light:e&&0===e.themeIndex?E():e&&e.light)?k:f},CB_DARK:s,CB_LIGHT:m,ANSI_DARK:u,ANSI_LIGHT:h,THEMES:F,THEME_TABLE:B,AUTO_THEME_INDEX:0,themeIsLight:function(n,t=e()){const r=B[n];return!!r&&(0===n?E(t):!!r.light)},terminalIsLight:E,themeForIndex:T,themeContradicts:O,reconcileThemeIndex:function(n,t=e()){const r=B[n];if(!O(n,t))return{index:n,changed:!1,reason:"",from:r||null};const i=H[n],o=B[i],d=e=>`${e.name}${e.note?" "+e.note:""}`;return{index:i,changed:!0,from:r,reason:`saved theme "${d(r)}" is unreadable on this ${t.background} terminal (${t.reasons.background}) — using "${d(o)}" instead`}},SIBLING_THEME_INDEX:H,GLYPH:x,glyphsFor:_,VERBS:["Incubating","Tempering","Determining","Beboppin'","Julienning","Inferring","Simmering","Twisting","Fermenting","Fiddle-faddling","Orbiting","Prestidigitating"],DONE_VERBS:["Churned","Worked"],themeOf:function(e){return e&&"number"==typeof e.themeIndex&&e.themeIndex>=3&&e.themeIndex<=6?T(e.themeIndex):e&&0===e.themeIndex?E()?c:g:e&&e.light?c:g},rematerialize:y};
@@ -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 crypto=require("node:crypto"),fs=require("node:fs"),path=require("node:path"),fp=require("./fingerprint.js"),authorship=require("./authorship-key.js"),envFile=require("./env-file.js"),DEFAULT_HISTORY=()=>path.join(authorship.dataDir(),"history.jsonl"),DIR_KEYS=["cwd","dir","workspace","root"],DEMAND_KEYS=["demand","prompt","task","text","content"],OUTCOME_KEYS=["outcome","status","result"],SESSION_KEYS=["session","sessionId","session_id"],TIME_KEYS=["at","ts","time","createdAt"],REPLY_KEYS=["reply","answer","response"],MODEL_KEYS=["model","aiModel","modelId"],sha256hex=e=>crypto.createHash("sha256").update(String(e||""),"utf8").digest("hex"),AI_SECRET_ENV="AEGIS_AI_SECRET";function firstKey(e,t){for(const r of t){const t=e[r];if(null==t)continue;const o="string"==typeof t?t:String(t);if(""!==o.trim())return o}return null}function readHistory(e){if(!fs.existsSync(e))throw new Error(`attest: no session log at ${e}`);const t=[];let r=0;for(const o of fs.readFileSync(e,"utf8").split("\n")){const e=o.trim();if(e)try{const o=JSON.parse(e);o&&"object"==typeof o?t.push(o):r+=1}catch{r+=1}}return{entries:t,skipped:r}}function lastSessionId(e){for(let t=e.length-1;t>=0;t-=1){const r=firstKey(e[t],SESSION_KEYS);if(r)return r}return null}function selectTurns(e,{session:t=null,turns:r=null}={}){let o=e;if(t){const r=String(t);o=e.filter((e=>firstKey(e,SESSION_KEYS)===r))}return r&&Number.isFinite(Number(r))&&Number(r)>0&&(o=o.slice(-Math.floor(Number(r)))),o}function observationsFromTurns(e){const t=[];for(const r of Array.isArray(e)?e:[]){if(!r||"object"!=typeof r)continue;const e=firstKey(r,DIR_KEYS),o=firstKey(r,DEMAND_KEYS);t.push({tool:o||e?"turn":null,target:`${e?path.basename(e):"?"}#${sha256hex(o||"").slice(0,8)}`,outcome:firstKey(r,OUTCOME_KEYS)})}return t}function aiObservationsFromTurns(e){const t=[];for(const r of Array.isArray(e)?e:[]){if(!r||"object"!=typeof r)continue;const e=firstKey(r,REPLY_KEYS),o=firstKey(r,OUTCOME_KEYS),s=firstKey(r,MODEL_KEYS),n=Boolean(e||o||s);t.push({tool:n?"reply":null,target:n?`reply#${sha256hex(e||"").slice(0,8)}`:null,outcome:o||null,model:s})}return t}function resolveAiSecret(e={}){const t=e.argv||[],r=e.env||{},o=firstFlag(t,["--ai-secret","--ai-secret-file"]);if(o){const e=fs.readFileSync(o,"utf8").trim();if(!e)throw new Error(`attest: ${o} is empty — an empty AI credential is not one`);return{secret:e,source:o}}const s=r[AI_SECRET_ENV]&&String(r[AI_SECRET_ENV]).trim();if(s)return{secret:s,source:AI_SECRET_ENV};const n=String(e.aiModel||e.model||"").trim();if(n&&"function"==typeof envFile.providerForModelId){const t=envFile.providerForModelId(n,e.cls);if(t){const e=envFile.providerKeyFromEnv(t,r);if(e&&e.key)return{secret:e.key,source:e.env};const o=providerKeyFromFile(t,r);if(o)return o}}return{secret:null,source:"none"}}function providerKeyFromFile(e,t){const r="function"==typeof envFile.envVarFor?envFile.envVarFor(e):"";if(!r)return null;const o=t&&(t.AEGIS_HOME||t.AEGISCODE_HOME)?String(t.AEGIS_HOME||t.AEGISCODE_HOME):void 0;let s;try{s=envFile.parseEnvText(fs.readFileSync(envFile.envFileFor(o),"utf8"))}catch{return null}const n=s&&"string"==typeof s[r]?s[r].trim():"";return n&&("function"!=typeof envFile.credentialLooksUsable||envFile.credentialLooksUsable(n))?{secret:n,source:r}:null}function firstFlag(e,t){for(const r of t){const t=e.indexOf(r);if(-1!==t&&void 0!==e[t+1]&&!String(e[t+1]).startsWith("--"))return e[t+1]}return null}const SKIP_DIRS=new Set([".git","node_modules","dist","build","out","vendor",".venv","venv","__pycache__",".next",".cache","release","coverage"]),MAX_FILE_BYTES=2097152,MAX_FILES=4096;function collectCode({roots:e=[],files:t=[],skip:r=[]}={}){const o=new Set(r),s=[],n=(e,t)=>{const r=fs.statSync(t);if(!r.isFile())return;if(r.size>2097152)throw new Error(`attest: ${t} is ${r.size} bytes — too large to attest (max 2097152)`);if(s.length>=4096)throw new Error("attest: more than 4096 files — refusing to attest a partial walk");const o=fp.normaliseCodePath(e);o&&s.push({path:o,content:fs.readFileSync(t,"utf8")})};for(const t of e){const e=path.resolve(t),r=(e,t)=>{for(const s of fs.readdirSync(e).sort()){const i=path.join(e,s),c=t?`${t}/${s}`:s,l=fs.lstatSync(i);if(!l.isSymbolicLink())if(l.isDirectory()){if(SKIP_DIRS.has(s)||o.has(s))continue;r(i,c)}else n(c,i)}};r(e,"")}for(const e of t){const t=path.resolve(e);n(path.basename(t),t)}return s}function mintSession(e={}){const t=e.key||authorship.resolveKey(e);if(!t.secret)throw new Error(`attest: no authorship key — run \`aegiscode fingerprint keygen\`, set ${authorship.SECRET_ENV}, or pass --secret <file>`);const r=e.history||DEFAULT_HISTORY(),{entries:o,skipped:s}=readHistory(r),n=selectTurns(o,{session:e.session||lastSessionId(o),turns:e.turns}),i=observationsFromTurns(n),c=e.code||[],l=e.aiObservations||aiObservationsFromTurns(n),a=void 0!==e.aiModel&&null!==e.aiModel?e.aiModel:l.map((e=>e.model)).filter(Boolean).pop()||"",u=void 0===e.aiSecret?resolveAiSecret({...e,aiModel:a}):{secret:e.aiSecret,source:e.aiSecret?"caller":"none"},S=fp.mint({secret:t.secret,label:e.label,account:e.account,model:e.model,tools:e.tools,observations:i,code:c,codeDirty:void 0===e.codeDirty?null:e.codeDirty,aiSecret:u.secret,aiModel:a,aiObservations:l,createdAt:e.createdAt||void 0});return{record:S,keySource:t.source,public:t.public,samples:S.behaviourSamples,observations:i.length,aiKeySource:u.source,aiSamples:S.aiSamples,skippedLines:s}}module.exports={DEFAULT_HISTORY:DEFAULT_HISTORY,DIR_KEYS:DIR_KEYS,DEMAND_KEYS:DEMAND_KEYS,OUTCOME_KEYS:OUTCOME_KEYS,SESSION_KEYS:SESSION_KEYS,REPLY_KEYS:REPLY_KEYS,MODEL_KEYS:MODEL_KEYS,AI_SECRET_ENV:AI_SECRET_ENV,TIME_KEYS:TIME_KEYS,SKIP_DIRS:SKIP_DIRS,MAX_FILE_BYTES:2097152,MAX_FILES:4096,firstKey:firstKey,readHistory:readHistory,lastSessionId:lastSessionId,selectTurns:selectTurns,observationsFromTurns:observationsFromTurns,aiObservationsFromTurns:aiObservationsFromTurns,resolveAiSecret:resolveAiSecret,collectCode:collectCode,mintSession:mintSession};
3
+ const e=require("node:crypto"),t=require("node:fs"),o=require("node:path"),r=require("./fingerprint.js"),n=require("./authorship-key.js"),s=require("./env-file.js"),i=()=>o.join(n.dataDir(),"history.jsonl"),c=["cwd","dir","workspace","root"],l=["demand","prompt","task","text","content"],a=["outcome","status","result"],u=["session","sessionId","session_id"],f=["reply","answer","response"],d=["model","aiModel","modelId"],p=t=>e.createHash("sha256").update(String(t||""),"utf8").digest("hex"),S="AEGIS_AI_SECRET";function y(e,t){for(const o of t){const t=e[o];if(null==t)continue;const r="string"==typeof t?t:String(t);if(""!==r.trim())return r}return null}function m(e){if(!t.existsSync(e))throw new Error(`attest: no session log at ${e}`);const o=[];let r=0;for(const n of t.readFileSync(e,"utf8").split("\n")){const e=n.trim();if(e)try{const t=JSON.parse(e);t&&"object"==typeof t?o.push(t):r+=1}catch{r+=1}}return{entries:o,skipped:r}}function E(e){for(let t=e.length-1;t>=0;t-=1){const o=y(e[t],u);if(o)return o}return null}function v(e,{session:t=null,turns:o=null}={}){let r=e;if(t){const o=String(t);r=e.filter((e=>y(e,u)===o))}return o&&Number.isFinite(Number(o))&&Number(o)>0&&(r=r.slice(-Math.floor(Number(o)))),r}function h(e){const t=[];for(const r of Array.isArray(e)?e:[]){if(!r||"object"!=typeof r)continue;const e=y(r,c),n=y(r,l);t.push({tool:n||e?"turn":null,target:`${e?o.basename(e):"?"}#${p(n||"").slice(0,8)}`,outcome:y(r,a)})}return t}function _(e){const t=[];for(const o of Array.isArray(e)?e:[]){if(!o||"object"!=typeof o)continue;const e=y(o,f),r=y(o,a),n=y(o,d),s=Boolean(e||r||n);t.push({tool:s?"reply":null,target:s?`reply#${p(e||"").slice(0,8)}`:null,outcome:r||null,model:n})}return t}function b(e={}){const o=e.argv||[],r=e.env||{},n=function(e,t){for(const t of["--ai-secret","--ai-secret-file"]){const o=e.indexOf(t);if(-1!==o&&void 0!==e[o+1]&&!String(e[o+1]).startsWith("--"))return e[o+1]}return null}(o);if(n){const e=t.readFileSync(n,"utf8").trim();if(!e)throw new Error(`attest: ${n} is empty — an empty AI credential is not one`);return{secret:e,source:n}}const i=r[S]&&String(r[S]).trim();if(i)return{secret:i,source:S};const c=String(e.aiModel||e.model||"").trim();if(c&&"function"==typeof s.providerForModelId){const o=s.providerForModelId(c,e.cls);if(o){const e=s.providerKeyFromEnv(o,r);if(e&&e.key)return{secret:e.key,source:e.env};const n=function(e,o){const r="function"==typeof s.envVarFor?s.envVarFor(e):"";if(!r)return null;const n=o&&(o.AEGIS_HOME||o.AEGISCODE_HOME)?String(o.AEGIS_HOME||o.AEGISCODE_HOME):void 0;let i;try{i=s.parseEnvText(t.readFileSync(s.envFileFor(n),"utf8"))}catch{return null}const c=i&&"string"==typeof i[r]?i[r].trim():"";return c&&("function"!=typeof s.credentialLooksUsable||s.credentialLooksUsable(c))?{secret:c,source:r}:null}(o,r);if(n)return n}}return{secret:null,source:"none"}}const g=new Set([".git","node_modules","dist","build","out","vendor",".venv","venv","__pycache__",".next",".cache","release","coverage"]),I=2097152;module.exports={DEFAULT_HISTORY:i,DIR_KEYS:c,DEMAND_KEYS:l,OUTCOME_KEYS:a,SESSION_KEYS:u,REPLY_KEYS:f,MODEL_KEYS:d,AI_SECRET_ENV:S,TIME_KEYS:["at","ts","time","createdAt"],SKIP_DIRS:g,MAX_FILE_BYTES:I,MAX_FILES:4096,firstKey:y,readHistory:m,lastSessionId:E,selectTurns:v,observationsFromTurns:h,aiObservationsFromTurns:_,resolveAiSecret:b,collectCode:function({roots:e=[],files:n=[],skip:s=[]}={}){const i=new Set(s),c=[],l=(e,o)=>{const n=t.statSync(o);if(!n.isFile())return;if(n.size>I)throw new Error(`attest: ${o} is ${n.size} bytes — too large to attest (max 2097152)`);if(c.length>=4096)throw new Error("attest: more than 4096 files — refusing to attest a partial walk");const s=r.normaliseCodePath(e);s&&c.push({path:s,content:t.readFileSync(o,"utf8")})};for(const r of e){const e=o.resolve(r),n=(e,r)=>{for(const s of t.readdirSync(e).sort()){const c=o.join(e,s),a=r?`${r}/${s}`:s,u=t.lstatSync(c);if(!u.isSymbolicLink())if(u.isDirectory()){if(g.has(s)||i.has(s))continue;n(c,a)}else l(a,c)}};n(e,"")}for(const e of n){const t=o.resolve(e);l(o.basename(t),t)}return c},mintSession:function(e={}){const t=e.key||n.resolveKey(e);if(!t.secret)throw new Error(`attest: no authorship key — run \`aegiscode fingerprint keygen\`, set ${n.SECRET_ENV}, or pass --secret <file>`);const o=e.history||i(),{entries:s,skipped:c}=m(o),l=v(s,{session:e.session||E(s),turns:e.turns}),a=h(l),u=e.code||[],f=e.aiObservations||_(l),d=void 0!==e.aiModel&&null!==e.aiModel?e.aiModel:f.map((e=>e.model)).filter(Boolean).pop()||"",p=void 0===e.aiSecret?b({...e,aiModel:d}):{secret:e.aiSecret,source:e.aiSecret?"caller":"none"},S=r.mint({secret:t.secret,label:e.label,account:e.account,model:e.model,tools:e.tools,observations:a,code:u,codeDirty:void 0===e.codeDirty?null:e.codeDirty,aiSecret:p.secret,aiModel:d,aiObservations:f,createdAt:e.createdAt||void 0});return{record:S,keySource:t.source,public:t.public,samples:S.behaviourSamples,observations:a.length,aiKeySource:p.source,aiSamples:S.aiSamples,skippedLines:c}}};
@@ -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 SCOPE_CONVERSATION="conversation",SCOPE_MEMORY="memory",SCOPE_TEXT={conversation:"one conversation",memory:"the whole memory base"};function keyTag(e){const n="string"==typeof e?e.trim():"";return n?`φ_${n}`:null}function authorLine(e){return keyTag(e)||"no key — this copy is unsigned"}function safeFileName(e,n){return String(e||n||"aegis-export").normalize("NFKD").replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"aegis-export"}function stamp({scope:e,keyFingerprint:n=null,email:t=null,exportedAt:o=null,subject:r=null,count:i=null}={}){const a=keyTag(n),s=[];return r&&s.push(`**What this is:** ${r}`),s.push(`**Scope:** ${SCOPE_TEXT[e]||String(e||"unknown")} (${e||"unknown"})`),s.push(`**Author:** ${authorLine(n)}`),s.push(`**Account:** ${t||"not reported by the server"}`),null!=i&&s.push(`**Entries:** ${i}`),s.push(`**Exported:** ${o||"timestamp not recorded"}`),s.push(a?`**Sealed by:** ${a} — this is a key tag, not the key. It proves the same machine wrote it.`:"**Sealed by:** nothing — no authorship key is set on this machine, so this copy cannot prove it came from you."),`${s.join("\n")}\n\n`}function conversationMarkdown(e,n={}){return`# ${e&&(e.title||e.id)||"Untitled conversation"}\n\n${stamp({scope:"conversation",subject:null,keyFingerprint:n.keyFingerprint,email:n.email,exportedAt:n.exportedAt,count:void 0===n.count?null:n.count})}---\n\n${n.transcript||""}`}function memoryMarkdown(e,n={}){return`${stamp({scope:"memory",subject:null,keyFingerprint:n.keyFingerprint,email:n.email,exportedAt:n.exportedAt,count:void 0===n.count?null:n.count})}---\n\n${e||""}`}function conversationFileName(e,n){const t=String(n||"").replace(/[:.]/g,"-").replace(/[^\w-]+/g,""),o=safeFileName(e&&(e.title||e.id),"conversation");return t?`${o}-${t}.md`:`${o}.md`}module.exports={SCOPE_CONVERSATION:"conversation",SCOPE_MEMORY:"memory",SCOPE_TEXT:SCOPE_TEXT,keyTag:keyTag,authorLine:authorLine,safeFileName:safeFileName,stamp:stamp,conversationMarkdown:conversationMarkdown,memoryMarkdown:memoryMarkdown,conversationFileName:conversationFileName};
3
+ const e="conversation",n="memory",t={[e]:"one conversation",[n]:"the whole memory base"};function o(e){const n="string"==typeof e?e.trim():"";return n?`φ_${n}`:null}function r(e){return o(e)||"no key — this copy is unsigned"}function i(e,n){return String(e||n||"aegis-export").normalize("NFKD").replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"aegis-export"}function u({scope:e,keyFingerprint:n=null,email:i=null,exportedAt:u=null,subject:s=null,count:c=null}={}){const l=o(n),a=[];return s&&a.push(`**What this is:** ${s}`),a.push(`**Scope:** ${t[e]||String(e||"unknown")} (${e||"unknown"})`),a.push(`**Author:** ${r(n)}`),a.push(`**Account:** ${i||"not reported by the server"}`),null!=c&&a.push(`**Entries:** ${c}`),a.push(`**Exported:** ${u||"timestamp not recorded"}`),a.push(l?`**Sealed by:** ${l} — this is a key tag, not the key. It proves the same machine wrote it.`:"**Sealed by:** nothing — no authorship key is set on this machine, so this copy cannot prove it came from you."),`${a.join("\n")}\n\n`}module.exports={SCOPE_CONVERSATION:e,SCOPE_MEMORY:n,SCOPE_TEXT:t,keyTag:o,authorLine:r,safeFileName:i,stamp:u,conversationMarkdown:function(n,t={}){return`# ${n&&(n.title||n.id)||"Untitled conversation"}\n\n${u({scope:e,subject:null,keyFingerprint:t.keyFingerprint,email:t.email,exportedAt:t.exportedAt,count:void 0===t.count?null:t.count})}---\n\n${t.transcript||""}`},memoryMarkdown:function(e,t={}){return`${u({scope:n,subject:null,keyFingerprint:t.keyFingerprint,email:t.email,exportedAt:t.exportedAt,count:void 0===t.count?null:t.count})}---\n\n${e||""}`},conversationFileName:function(e,n){const t=String(n||"").replace(/[:.]/g,"-").replace(/[^\w-]+/g,""),o=i(e&&(e.title||e.id),"conversation");return t?`${o}-${t}.md`:`${o}.md`}};
@@ -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"),os=require("node:os"),path=require("node:path"),KEY_ENV="AEGIS_API_KEY",MEMORY_ENV="AEGIS_MEMORY_TOKEN",HOME_ENV="AEGISCODE_HOME",CREDENTIALS_FILE="credentials.json",CONFIG_FILE="config.json",FILE_MODE=384,DIR_MODE=448;function aegisHome(e){const r=e||process.env,n=r&&r[HOME_ENV];return n&&String(n).trim()?path.resolve(String(n).trim()):path.join(os.homedir(),".aegiscode")}function credentialsPath(e){return path.join(e||aegisHome(),CREDENTIALS_FILE)}function configPath(e){return path.join(e||aegisHome(),CONFIG_FILE)}function normalizeApiKey(e){let r=String(null==e?"":e).trim();if(!r)return"";r=r.replace(/^export\s+/i,"").trim();const n=/^[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.+)$/s.exec(r);return n&&(r=n[1].trim()),r=r.replace(/^["']|["']$/g,"").trim(),r=r.replace(/^Bearer\s+/i,"").trim(),r}function validateApiKey(e,r={}){const n=String(r.label||"AEGIS"),t=normalizeApiKey(e);return t?/\s/.test(t)?{ok:!1,key:t,reason:"whitespace",message:"that looks like more than one word — paste just the key"}:t.length<16?{ok:!1,key:t,reason:"too short",message:`that key is ${t.length} characters — ${n} keys are longer than that`}:{ok:!0,key:t,reason:null,message:null}:{ok:!1,key:t,reason:"empty",message:"no key given"}}function readCredentials(e){try{const r=JSON.parse(fs.readFileSync(credentialsPath(e),"utf8"));if(r&&"object"==typeof r)return r}catch{}return{}}function writeCredentials(e,r){const n=credentialsPath(r),t={...readCredentials(r),...e,version:1};try{fs.mkdirSync(path.dirname(n),{recursive:!0,mode:DIR_MODE});const e=n+".tmp";fs.writeFileSync(e,JSON.stringify(t,null,2)+"\n",{mode:FILE_MODE}),fs.renameSync(e,n);try{fs.chmodSync(n,FILE_MODE)}catch{}}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[credentials] write failed:",e),{ok:!1,error:e,credentials:t}}return{ok:!0,credentials:t}}function readLegacyConfig(e){try{const r=JSON.parse(fs.readFileSync(configPath(e),"utf8"));if(!r||"object"!=typeof r)return{};const n=r.aegiscloud&&"object"==typeof r.aegiscloud?r.aegiscloud:{},t=r.memory&&"object"==typeof r.memory?r.memory:{};return{apiKey:normalizeApiKey(n.api_key),memoryToken:String(t.token||"").trim(),syncConversations:!0===n.syncConversations||void 0,lastVerified:n.lastVerified||null,memorySubscribed:!0===t.subscribed||void 0}}catch{return{}}}function legacyKeyOnDisk(e){return!!readLegacyConfig(e).apiKey}function adoptLegacy(e){const r=readLegacyConfig(e),n=readCredentials(e),t={};return r.apiKey&&!n.aegisApiKey&&(t.aegisApiKey=r.apiKey),r.memoryToken&&!n.memoryToken&&(t.memoryToken=r.memoryToken),Object.keys(t).length&&writeCredentials({...t,adoptedFrom:configPath(e)},e).ok?{adopted:Object.keys(t)}:{adopted:[]}}function fromEnvFile(e,r,n){try{const t=require("./env-file.js");return"function"==typeof t.isFromEnvFile&&t.isFromEnvFile(e,r,n?{env:n}:void 0)}catch{return!1}}function resolveApiKey(e={}){const r=e.env||process.env,n=e.dir,t=normalizeApiKey(r&&r[KEY_ENV]);if(t&&!fromEnvFile(KEY_ENV,r&&r[KEY_ENV],r))return{key:t,source:"env",from:KEY_ENV};const o=normalizeApiKey(readCredentials(n).aegisApiKey);if(o)return{key:o,source:"credentials",from:credentialsPath(n)};if(t)return{key:t,source:"envfile",from:envFileLabel(r,n)};const i=readLegacyConfig(n).apiKey;return i?{key:i,source:"config",from:configPath(n)}:{key:"",source:"none",from:""}}function hasApiKey(e={}){return!!resolveApiKey(e).key}function saveApiKey(e,r){const n=validateApiKey(e);if(!n.ok)return{ok:!1,key:n.key,path:credentialsPath(r),message:n.message};const t=writeCredentials({aegisApiKey:n.key,savedAt:(new Date).toISOString()},r);return t.ok?{ok:!0,key:n.key,path:credentialsPath(r)}:{ok:!1,key:n.key,path:credentialsPath(r),error:t.error,message:`could not write ${credentialsPath(r)}`}}function clearApiKey(e){return{cleared:!!normalizeApiKey(readCredentials(e).aegisApiKey),ok:writeCredentials({aegisApiKey:"",adoptedFrom:""},e).ok,path:credentialsPath(e)}}function resolveMemoryToken(e={}){const r=e.env||process.env,n=e.dir,t=String(r&&r[MEMORY_ENV]||"").trim();if(t)return{token:t,source:"env"};const o=readCredentials(n),i=String(o.memoryToken||"").trim();if(i)return{token:i,source:"credentials"};const a=readLegacyConfig(n).memoryToken;return a?{token:a,source:"config"}:{token:"",source:"none"}}function saveMemoryToken(e,r={},n){return writeCredentials({memoryToken:String(e||"").trim(),...r},n)}function clearMemoryToken(e){return writeCredentials({memoryToken:"",memorySubscribed:!1},e)}function keyStatus(e={}){const r=e.dir,{key:n,source:t,from:o}=resolveApiKey(e),i=readCredentials(r);let a=null;try{a=511&fs.statSync(credentialsPath(r)).mode}catch{}return{configured:!!n,key:n,source:t,from:o,path:credentialsPath(r),fileMode:null==a?null:"0"+a.toString(8),stored:!!normalizeApiKey(i.aegisApiKey),legacyPlaintext:legacyKeyOnDisk(r),verifiedAt:i.verifiedAt||null,account:i.account||null,memoryToken:!!resolveMemoryToken(e).token,memorySource:resolveMemoryToken(e).source}}function clientOptions(e={}){const{key:r}=resolveApiKey(e),{token:n}=resolveMemoryToken(e),t={};return t.apiKey=r,t.memoryToken=n,e.channel&&(t.channel=e.channel),t}const SOURCE_LABEL={env:`${KEY_ENV}`,credentials:"saved key file",envfile:`~/.aegiscode/.env (${KEY_ENV})`,config:"config.json (aegis CLI)",none:"not set"};function envFileLabel(e,r){try{const e=require("./env-file.js");if("function"==typeof e.envFileFor)return e.envFileFor(r)}catch{}return envFileForFallback(r)}function envFileForFallback(e){return path.join(e||aegisHome(),".env")}function sourceLabel(e){return SOURCE_LABEL[e]||SOURCE_LABEL.none}function preferNewest(e,r,n={}){const t=normalizeApiKey(e),o=Date.parse(r||"")||0,i=readCredentials(n.dir),a=normalizeApiKey(i.aegisApiKey),s=Date.parse(i.savedAt||"")||0;return a?t?t===a?{key:t,source:"host",sharedAt:s,hostAt:o}:s>o?{key:a,source:"shared",sharedAt:s,hostAt:o}:{key:t,source:"host",sharedAt:s,hostAt:o}:{key:a,source:"shared",sharedAt:s,hostAt:o}:{key:t,source:t?"host":"none",sharedAt:s,hostAt:o}}const HOW_TO_SET="run `aegiscode login` (or /key inside a session) to save one";module.exports={KEY_ENV:KEY_ENV,MEMORY_ENV:MEMORY_ENV,HOME_ENV:HOME_ENV,CREDENTIALS_FILE:CREDENTIALS_FILE,CONFIG_FILE:CONFIG_FILE,aegisHome:aegisHome,credentialsPath:credentialsPath,configPath:configPath,normalizeApiKey:normalizeApiKey,validateApiKey:validateApiKey,readCredentials:readCredentials,writeCredentials:writeCredentials,readLegacyConfig:readLegacyConfig,legacyKeyOnDisk:legacyKeyOnDisk,adoptLegacy:adoptLegacy,resolveApiKey:resolveApiKey,hasApiKey:hasApiKey,fromEnvFile:fromEnvFile,envFileForFallback:envFileForFallback,saveApiKey:saveApiKey,clearApiKey:clearApiKey,resolveMemoryToken:resolveMemoryToken,saveMemoryToken:saveMemoryToken,clearMemoryToken:clearMemoryToken,keyStatus:keyStatus,clientOptions:clientOptions,preferNewest:preferNewest,sourceLabel:sourceLabel,HOW_TO_SET:HOW_TO_SET};
3
+ const e=require("node:fs"),n=require("node:os"),r=require("node:path"),o="AEGIS_API_KEY",t="AEGIS_MEMORY_TOKEN",i="AEGISCODE_HOME",s="credentials.json",c="config.json";function a(e){const o=e||process.env,t=o&&o[i];return t&&String(t).trim()?r.resolve(String(t).trim()):r.join(n.homedir(),".aegiscode")}function u(e){return r.join(e||a(),s)}function y(e){return r.join(e||a(),c)}function l(e){let n=String(null==e?"":e).trim();if(!n)return"";n=n.replace(/^export\s+/i,"").trim();const r=/^[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.+)$/s.exec(n);return r&&(n=r[1].trim()),n=n.replace(/^["']|["']$/g,"").trim(),n=n.replace(/^Bearer\s+/i,"").trim(),n}function m(e,n={}){const r=String(n.label||"AEGIS"),o=l(e);return o?/\s/.test(o)?{ok:!1,key:o,reason:"whitespace",message:"that looks like more than one word — paste just the key"}:o.length<16?{ok:!1,key:o,reason:"too short",message:`that key is ${o.length} characters — ${r} keys are longer than that`}:{ok:!0,key:o,reason:null,message:null}:{ok:!1,key:o,reason:"empty",message:"no key given"}}function k(n){try{const r=JSON.parse(e.readFileSync(u(n),"utf8"));if(r&&"object"==typeof r)return r}catch{}return{}}function f(n,o){const t=u(o),i={...k(o),...n,version:1};try{e.mkdirSync(r.dirname(t),{recursive:!0,mode:448});const n=t+".tmp";e.writeFileSync(n,JSON.stringify(i,null,2)+"\n",{mode:384}),e.renameSync(n,t);try{e.chmodSync(t,384)}catch{}}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[credentials] write failed:",e),{ok:!1,error:e,credentials:i}}return{ok:!0,credentials:i}}function d(n){try{const r=JSON.parse(e.readFileSync(y(n),"utf8"));if(!r||"object"!=typeof r)return{};const o=r.aegiscloud&&"object"==typeof r.aegiscloud?r.aegiscloud:{},t=r.memory&&"object"==typeof r.memory?r.memory:{};return{apiKey:l(o.api_key),memoryToken:String(t.token||"").trim(),syncConversations:!0===o.syncConversations||void 0,lastVerified:o.lastVerified||null,memorySubscribed:!0===t.subscribed||void 0}}catch{return{}}}function p(e){return!!d(e).apiKey}function g(e,n,r){try{const o=require("./env-file.js");return"function"==typeof o.isFromEnvFile&&o.isFromEnvFile(e,n,r?{env:r}:void 0)}catch{return!1}}function h(e={}){const n=e.env||process.env,r=e.dir,t=l(n&&n[o]);if(t&&!g(o,n&&n[o],n))return{key:t,source:"env",from:o};const i=l(k(r).aegisApiKey);if(i)return{key:i,source:"credentials",from:u(r)};if(t)return{key:t,source:"envfile",from:S(0,r)};const s=d(r).apiKey;return s?{key:s,source:"config",from:y(r)}:{key:"",source:"none",from:""}}function v(e={}){const n=e.env||process.env,r=e.dir,o=String(n&&n[t]||"").trim();if(o)return{token:o,source:"env"};const i=k(r),s=String(i.memoryToken||"").trim();if(s)return{token:s,source:"credentials"};const c=d(r).memoryToken;return c?{token:c,source:"config"}:{token:"",source:"none"}}const A={env:`${o}`,credentials:"saved key file",envfile:`~/.aegiscode/.env (${o})`,config:"config.json (aegis CLI)",none:"not set"};function S(e,n){try{const e=require("./env-file.js");if("function"==typeof e.envFileFor)return e.envFileFor(n)}catch{}return E(n)}function E(e){return r.join(e||a(),".env")}module.exports={KEY_ENV:o,MEMORY_ENV:t,HOME_ENV:i,CREDENTIALS_FILE:s,CONFIG_FILE:c,aegisHome:a,credentialsPath:u,configPath:y,normalizeApiKey:l,validateApiKey:m,readCredentials:k,writeCredentials:f,readLegacyConfig:d,legacyKeyOnDisk:p,adoptLegacy:function(e){const n=d(e),r=k(e),o={};return n.apiKey&&!r.aegisApiKey&&(o.aegisApiKey=n.apiKey),n.memoryToken&&!r.memoryToken&&(o.memoryToken=n.memoryToken),Object.keys(o).length&&f({...o,adoptedFrom:y(e)},e).ok?{adopted:Object.keys(o)}:{adopted:[]}},resolveApiKey:h,hasApiKey:function(e={}){return!!h(e).key},fromEnvFile:g,envFileForFallback:E,saveApiKey:function(e,n){const r=m(e);if(!r.ok)return{ok:!1,key:r.key,path:u(n),message:r.message};const o=f({aegisApiKey:r.key,savedAt:(new Date).toISOString()},n);return o.ok?{ok:!0,key:r.key,path:u(n)}:{ok:!1,key:r.key,path:u(n),error:o.error,message:`could not write ${u(n)}`}},clearApiKey:function(e){return{cleared:!!l(k(e).aegisApiKey),ok:f({aegisApiKey:"",adoptedFrom:""},e).ok,path:u(e)}},resolveMemoryToken:v,saveMemoryToken:function(e,n={},r){return f({memoryToken:String(e||"").trim(),...n},r)},clearMemoryToken:function(e){return f({memoryToken:"",memorySubscribed:!1},e)},keyStatus:function(n={}){const r=n.dir,{key:o,source:t,from:i}=h(n),s=k(r);let c=null;try{c=511&e.statSync(u(r)).mode}catch{}return{configured:!!o,key:o,source:t,from:i,path:u(r),fileMode:null==c?null:"0"+c.toString(8),stored:!!l(s.aegisApiKey),legacyPlaintext:p(r),verifiedAt:s.verifiedAt||null,account:s.account||null,memoryToken:!!v(n).token,memorySource:v(n).source}},clientOptions:function(e={}){const{key:n}=h(e),{token:r}=v(e),o={};return o.apiKey=n,o.memoryToken=r,e.channel&&(o.channel=e.channel),o},preferNewest:function(e,n,r={}){const o=l(e),t=Date.parse(n||"")||0,i=k(r.dir),s=l(i.aegisApiKey),c=Date.parse(i.savedAt||"")||0;return s?o?o===s?{key:o,source:"host",sharedAt:c,hostAt:t}:c>t?{key:s,source:"shared",sharedAt:c,hostAt:t}:{key:o,source:"host",sharedAt:c,hostAt:t}:{key:s,source:"shared",sharedAt:c,hostAt:t}:{key:o,source:o?"host":"none",sharedAt:c,hostAt:t}},sourceLabel:function(e){return A[e]||A.none},HOW_TO_SET:"run `aegiscode login` (or /key inside a session) to save one"};
@@ -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 DRIVE_FILES_URL="https://www.googleapis.com/drive/v3/files",DRIVE_UPLOAD_URL="https://www.googleapis.com/upload/drive/v3/files",FOLDER_MIME="application/vnd.google-apps.folder",BOUNDARY="aegiscode-drive-upload-boundary",DEFAULT_FOLDER="AEGIS Memory",DEFAULT_FILE="aegis-memory-backup.json",DEFAULT_CONVERSATIONS_FOLDER="conversations";function resolveFetch(e){const n=e||("function"==typeof fetch?fetch:null);if(!n)throw new Error("drive: this Node has no global fetch — upgrade to Node 22+");return n}function escapeQ(e){return String(e).replace(/\\/g,"\\\\").replace(/'/g,"\\'")}async function driveRequest(e,n,{method:t="GET",accessToken:o,body:r,headers:a}={}){const i=resolveFetch(e),d=await i(n,{method:t,headers:{Authorization:`Bearer ${o}`,...a||{}},body:r}),l=await d.text();let s=null;try{s=l?JSON.parse(l):null}catch{s=null}if(!d.ok){const e=s&&s.error&&(s.error.message||s.error)||l.slice(0,200)||`HTTP ${d.status}`,o=new Error(`drive: ${t} ${n.split("?")[0]} failed — ${"string"==typeof e?e:JSON.stringify(e)}`);throw o.status=d.status,o.data=s,o}return s||{}}async function findOne(e,n,t){const o=`${DRIVE_FILES_URL}?q=${encodeURIComponent(t)}&fields=${encodeURIComponent("files(id,name)")}&pageSize=1`,r=await driveRequest(e,o,{accessToken:n});return(Array.isArray(r.files)?r.files:[])[0]||null}async function findOrCreateFolder(e,n,{fetchImpl:t,parentId:o=null}={}){const r=`${o?`'${escapeQ(o)}' in parents and `:""}mimeType='${FOLDER_MIME}' and name='${escapeQ(n)}' and trashed=false`,a=await findOne(t,e,r);if(a)return a.id;const i={name:n,mimeType:FOLDER_MIME};return o&&(i.parents=[o]),(await driveRequest(t,DRIVE_FILES_URL,{method:"POST",accessToken:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})).id}async function findFileInFolder(e,n,t,{fetchImpl:o}={}){return findOne(o,e,`'${escapeQ(t)}' in parents and name='${escapeQ(n)}' and trashed=false`)}async function createFile(e,{name:n,folderId:t,content:o,mimeType:r},{fetchImpl:a}={}){const i=JSON.stringify({name:n,parents:[t]}),d=`--${BOUNDARY}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n${i}\r\n--${BOUNDARY}\r\nContent-Type: ${r}\r\n\r\n${o}\r\n--${BOUNDARY}--`;return driveRequest(a,`${DRIVE_UPLOAD_URL}?uploadType=multipart&fields=${encodeURIComponent("id,webViewLink")}`,{method:"POST",accessToken:e,headers:{"Content-Type":`multipart/related; boundary=${BOUNDARY}`},body:d})}async function updateFileContent(e,n,t,o,{fetchImpl:r}={}){return driveRequest(r,`${DRIVE_UPLOAD_URL}/${encodeURIComponent(n)}?uploadType=media&fields=${encodeURIComponent("id,webViewLink")}`,{method:"PATCH",accessToken:e,headers:{"Content-Type":o},body:t})}async function uploadMemoryBackup(e,n,t={}){const o=t.folderName||"AEGIS Memory",r=t.fileName||DEFAULT_FILE,a=t.mimeType||"application/json",i=t.fetchImpl,d=await findOrCreateFolder(e,o,{fetchImpl:i}),l=await findFileInFolder(e,r,d,{fetchImpl:i}),s=l?await updateFileContent(e,l.id,n,a,{fetchImpl:i}):await createFile(e,{name:r,folderId:d,content:n,mimeType:a},{fetchImpl:i});return{fileId:s.id||l&&l.id||null,webViewLink:s.webViewLink||null,updated:Boolean(l)}}async function uploadConversation(e,n={}){const t=n.name,o=n.content;if(!t)throw new Error("drive: uploadConversation needs a file name");if("string"!=typeof o)throw new Error("drive: uploadConversation needs the file content as a string");const r=n.folderName||"AEGIS Memory",a=void 0===n.subfolder?"conversations":n.subfolder,i=n.mimeType||"text/markdown",d=n.fetchImpl,l=await findOrCreateFolder(e,r,{fetchImpl:d}),s=a?await findOrCreateFolder(e,a,{fetchImpl:d,parentId:l}):l,c=await createFile(e,{name:t,folderId:s,content:o,mimeType:i},{fetchImpl:d});return{fileId:c.id||null,webViewLink:c.webViewLink||null,created:!0,folder:a?`${r}/${a}`:r,path:a?`${r}/${a}/${t}`:`${r}/${t}`}}module.exports={DEFAULT_FOLDER:"AEGIS Memory",DEFAULT_FILE:DEFAULT_FILE,DEFAULT_CONVERSATIONS_FOLDER:"conversations",findOrCreateFolder:findOrCreateFolder,findFileInFolder:findFileInFolder,createFile:createFile,updateFileContent:updateFileContent,uploadMemoryBackup:uploadMemoryBackup,uploadConversation:uploadConversation};
3
+ const e="https://www.googleapis.com/drive/v3/files",n="https://www.googleapis.com/upload/drive/v3/files",t="application/vnd.google-apps.folder",o="aegiscode-drive-upload-boundary",a="AEGIS Memory",r="aegis-memory-backup.json",i="conversations";function d(e){return String(e).replace(/\\/g,"\\\\").replace(/'/g,"\\'")}async function s(e,n,{method:t="GET",accessToken:o,body:a,headers:r}={}){const i=function(e){const n=e||("function"==typeof fetch?fetch:null);if(!n)throw new Error("drive: this Node has no global fetch — upgrade to Node 22+");return n}(e),d=await i(n,{method:t,headers:{Authorization:`Bearer ${o}`,...r||{}},body:a}),s=await d.text();let l=null;try{l=s?JSON.parse(s):null}catch{l=null}if(!d.ok){const e=l&&l.error&&(l.error.message||l.error)||s.slice(0,200)||`HTTP ${d.status}`,o=new Error(`drive: ${t} ${n.split("?")[0]} failed — ${"string"==typeof e?e:JSON.stringify(e)}`);throw o.status=d.status,o.data=l,o}return l||{}}async function l(n,t,o){const a=`${e}?q=${encodeURIComponent(o)}&fields=${encodeURIComponent("files(id,name)")}&pageSize=1`,r=await s(n,a,{accessToken:t});return(Array.isArray(r.files)?r.files:[])[0]||null}async function c(n,o,{fetchImpl:a,parentId:r=null}={}){const i=`${r?`'${d(r)}' in parents and `:""}mimeType='${t}' and name='${d(o)}' and trashed=false`,c=await l(a,n,i);if(c)return c.id;const p={name:o,mimeType:t};return r&&(p.parents=[r]),(await s(a,e,{method:"POST",accessToken:n,headers:{"Content-Type":"application/json"},body:JSON.stringify(p)})).id}async function p(e,n,t,{fetchImpl:o}={}){return l(o,e,`'${d(t)}' in parents and name='${d(n)}' and trashed=false`)}async function f(e,{name:t,folderId:a,content:r,mimeType:i},{fetchImpl:d}={}){const l=JSON.stringify({name:t,parents:[a]}),c=`--${o}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n${l}\r\n--${o}\r\nContent-Type: ${i}\r\n\r\n${r}\r\n--${o}--`;return s(d,`${n}?uploadType=multipart&fields=${encodeURIComponent("id,webViewLink")}`,{method:"POST",accessToken:e,headers:{"Content-Type":`multipart/related; boundary=${o}`},body:c})}async function m(e,t,o,a,{fetchImpl:r}={}){return s(r,`${n}/${encodeURIComponent(t)}?uploadType=media&fields=${encodeURIComponent("id,webViewLink")}`,{method:"PATCH",accessToken:e,headers:{"Content-Type":a},body:o})}module.exports={DEFAULT_FOLDER:a,DEFAULT_FILE:r,DEFAULT_CONVERSATIONS_FOLDER:i,findOrCreateFolder:c,findFileInFolder:p,createFile:f,updateFileContent:m,uploadMemoryBackup:async function(e,n,t={}){const o=t.folderName||a,i=t.fileName||r,d=t.mimeType||"application/json",s=t.fetchImpl,l=await c(e,o,{fetchImpl:s}),u=await p(e,i,l,{fetchImpl:s}),h=u?await m(e,u.id,n,d,{fetchImpl:s}):await f(e,{name:i,folderId:l,content:n,mimeType:d},{fetchImpl:s});return{fileId:h.id||u&&u.id||null,webViewLink:h.webViewLink||null,updated:Boolean(u)}},uploadConversation:async function(e,n={}){const t=n.name,o=n.content;if(!t)throw new Error("drive: uploadConversation needs a file name");if("string"!=typeof o)throw new Error("drive: uploadConversation needs the file content as a string");const r=n.folderName||a,d=void 0===n.subfolder?i:n.subfolder,s=n.mimeType||"text/markdown",l=n.fetchImpl,p=await c(e,r,{fetchImpl:l}),m=d?await c(e,d,{fetchImpl:l,parentId:p}):p,u=await f(e,{name:t,folderId:m,content:o,mimeType:s},{fetchImpl:l});return{fileId:u.id||null,webViewLink:u.webViewLink||null,created:!0,folder:d?`${r}/${d}`:r,path:d?`${r}/${d}/${t}`:`${r}/${t}`}}};