aegiscode 7.0.28 → 7.0.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -3
- package/src/app.js +1 -1
- package/src/art.js +1 -1
- package/src/chatflow.js +1 -1
- package/src/commands.js +1 -1
- package/src/credentials.js +1 -1
- package/src/diffview.js +1 -1
- package/src/export.js +1 -1
- package/src/init.js +1 -1
- package/src/models.js +1 -1
- package/src/panels.js +1 -1
- package/src/screens.js +1 -1
- package/src/theme.js +1 -1
- package/vendor/client/aegis.js +1 -1
- package/vendor/client/attest.js +1 -1
- package/vendor/client/catalog-client.js +1 -1
- package/vendor/client/conversation-export.js +1 -1
- package/vendor/client/credentials.js +1 -1
- package/vendor/client/drive-upload.js +1 -1
- package/vendor/client/env-file.js +1 -1
- package/vendor/client/hooks.js +1 -1
- package/vendor/client/model-discovery.js +1 -1
- package/vendor/client/naming.js +1 -1
- package/vendor/client/platform.js +1 -1
- package/vendor/client/record-vault.js +2 -2
- package/vendor/client/session-store.js +1 -1
- package/vendor/client/user-models.js +1 -1
- package/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/lib/local/exec-plan.js +269 -1
- package/vendor/desktop/lib/local/integrity.js +163 -1
- package/vendor/desktop/lib/local/shell.js +712 -1
- package/vendor/desktop/lib/local/tools.js +1328 -1
- package/vendor/desktop/main.js +4956 -1
- package/vendor/hosts/install.js +1 -1
- package/vendor/hosts/openai-shim.js +1 -1
- package/vendor/mcp/server.js +1 -1
- package/vendor/mcp/tools.js +1 -1
- package/vendor/one/src/selfhost.js +3 -0
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
|
-
const
|
|
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};
|
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
|
-
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};
|
|
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};
|
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
|
-
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};
|
|
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};
|
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
|
-
const{caps:
|
|
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="[0m",BOLD="[1m",DIM="[2m",ITALIC="[3m",UNDER="[4m",BOLD_OFF="[22m",ITALIC_OFF="[23m",UNDER_OFF="[24m",RESET_FG="[39m",RESET_BG="[49m",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?"[48;5;236m":""}}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?"[48;5;254m":""}}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:"[3m",UNDER:UNDER,BOLD_OFF:"[22m",ITALIC_OFF:"[23m",UNDER_OFF:"[24m",RESET_FG:"[39m",RESET_BG:"[49m",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};
|
package/vendor/client/aegis.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
3
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
4
|
-
"use strict";function envVar(e){if("undefined"==typeof process||!process.env)return"";const t=process.env[e];return t&&!/^\$\{[A-Z_]+\}$/.test(t)?t:""}function envIdleMs(e){const t=envVar(e);if(!t)return 0;const n=Number(t);return Number.isFinite(n)&&n>0?n:0}const DSML_RE_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*>/g,DSML_RE_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/g,DSML_RE_LEADER=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:(?:tool|function)[_▁ ]*calls?|reasoning)[_▁ ]*(?:begin|end)?\s*>/gi,DSML_RE_ANY_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_SKELETON=/<\s*\/?\s*(?:tool_calls|function_calls|invoke|parameter|param|reasoning)\b[^>]{0,120}>/gi,DSML_RE_JSON_CALLS=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|([\s\S]*?)|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_JSON_CALLS_OPEN=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|/gi,DSML_RE_JSON_CALLS_CLOSE=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_ENVELOPE_TOKEN=/|[ \t]?[A-Za-z0-9_▁]*[ \t]?|/g,DSML_RE_DRIFT_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>/gi,DSML_RE_DRIFT_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>/gi,DSML_RE_PARAM_CLOSE=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/gi,DSML_RE_ATTR=/([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,DSML_RE_STRUCT_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_STRUCT_CLOSER=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_WRAPPER_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?!(?:invoke|call|tool_call|parameter|param|arg)\b)[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_TRAILING_LT=/<\s*\/?\s*$/,DSML_RE_OPEN_TOKEN=/^|[ \t]?[A-Za-z0-9_▁]*[ \t]?$/,DSML_HOLD_MAX=4194304;function dsmlAttrs(e){const t={};if(!e)return t;let n;for(DSML_RE_ATTR.lastIndex=0;n=DSML_RE_ATTR.exec(e);)t[n[1].toLowerCase()]=null!=n[2]?n[2]:n[3];return t}function dsmlJson(e){const t=String(null==e?"":e).trim();try{const e=JSON.parse(t);return void 0===e?t:e}catch{return t}}function dsmlArgs(e){const t={};let n;for(DSML_RE_PARAM.lastIndex=0;n=DSML_RE_PARAM.exec(e);){const e=dsmlAttrs(n[1]),r=e.name||e.key||`arg${Object.keys(t).length}`,o="false"===String(e.string||"").toLowerCase()||"true"===String(e.json||"").toLowerCase();t[r]=o?dsmlJson(n[2]):n[2]}return t}function decodeDeepSeekDSML(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n=e;DSML_RE_INVOKE.lastIndex=0;const r=[];let o;for(;o=DSML_RE_INVOKE.exec(n);){const e=dsmlAttrs(o[1]),n=e.name||e.function||e.tool||"";n&&t.push({name:n,args:dsmlArgs(o[2])}),r.push([o.index,o.index+o[0].length])}for(let e=r.length-1;e>=0;e--)n=n.slice(0,r[e][0])+n.slice(r[e][1]);return n=n.replace(DSML_RE_JSON_CALLS,((e,n)=>{const r=dsmlJson(n),o=Array.isArray(r)?r:r&&Array.isArray(r.tool_calls)?r.tool_calls:[];for(const e of o){const n=e&&e.function||e||{},r=n.name||e&&e.name||"";if(!r)continue;let o=null!=n.arguments?n.arguments:e&&e.arguments;"string"==typeof o&&(o=dsmlJson(o)),t.push({name:r,args:o&&"object"==typeof o?o:{}})}return""})),n=n.replace(DSML_RE_LEADER,""),{text:n,calls:t}}function decodeDeepSeekDSMLDrift(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n;for(DSML_RE_DRIFT_INVOKE.lastIndex=0;n=DSML_RE_DRIFT_INVOKE.exec(e);)t.push({at:n.index,attrs:n[1],body:DSML_RE_DRIFT_INVOKE.lastIndex});if(!t.length)return{text:e,calls:[]};const r=[];let o="",s=0;for(let n=0;n<t.length;n++){const a=n+1<t.length?t[n+1].at:e.length,i=e.slice(t[n].body,a),c=dsmlAttrs(t[n].attrs),l=c.name||c.function||c.tool||"",u={},d=[];let m;for(DSML_RE_DRIFT_PARAM.lastIndex=0;m=DSML_RE_DRIFT_PARAM.exec(i);)d.push({at:m.index,attrs:m[1],from:DSML_RE_DRIFT_PARAM.lastIndex});for(let e=0;e<d.length;e++){const t=e+1<d.length?d[e+1].at:i.length,n=i.slice(d[e].from,t).replace(DSML_RE_PARAM_CLOSE,""),r=dsmlAttrs(d[e].attrs),o=r.name||r.key||`arg${Object.keys(u).length}`,s="false"===String(r.string||"").toLowerCase();u[o]=s?dsmlJson(n):n}o+=e.slice(s,t[n].at),s=a,l&&r.push({name:l,args:u})}return o+=e.slice(s),{text:o,calls:r}}function dsmlResidue(e){return e?-1===e.indexOf("|")?e.replace(DSML_RE_SKELETON,""):e.replace(DSML_RE_ANY_TAG,"").replace(DSML_RE_SKELETON,"").replace(DSML_RE_ENVELOPE_TOKEN,""):e}function dsmlUnterminated(e){return!!DSML_RE_OPEN_TOKEN.test(e)||(e.match(DSML_RE_STRUCT_TAG)||[]).length>(e.match(DSML_RE_STRUCT_CLOSER)||[]).length}function dsmlHoldFrom(e){const t=e.search(/<\s*\/?\s*|/);if(-1!==t)return t;const n=e.search(DSML_RE_JSON_CALLS_OPEN);if(-1!==n&&-1===e.slice(n).search(DSML_RE_JSON_CALLS_CLOSE))return n;const r=DSML_RE_TRAILING_LT.exec(e);if(r)return r.index;const o=e.indexOf("|");return-1!==o&&dsmlUnterminated(e.slice(o))?o:-1}function makeDeepSeekEnvelopeStripper(){let e="";const t=[],n=n=>{e+="string"==typeof n?n:"";const r=decodeDeepSeekDSML(e);e=r.text;for(const e of r.calls)t.push(e);e=e.replace(DSML_RE_WRAPPER_TAG,"");const o=dsmlHoldFrom(e);let s;return-1!==o&&e.length-o<=DSML_HOLD_MAX?(s=e.slice(0,o),e=e.slice(o)):(s=e,e=""),dsmlResidue(s)};return n.flush=()=>{const n=decodeDeepSeekDSML(e);e="";for(const e of n.calls)t.push(e);const r=decodeDeepSeekDSMLDrift(n.text);for(const e of r.calls)t.push(e);return dsmlResidue(r.text)},n.calls=()=>t.slice(),n}function randomUUID(){const e="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||null,t=e&&e.crypto;if(t&&"function"==typeof t.randomUUID)try{return t.randomUUID()}catch(e){}if(t&&"function"==typeof t.getRandomValues)try{const e=new Uint8Array(16);t.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128;const n=Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}catch(e){}if("function"==typeof require)try{const e=require("crypto");if(e&&"function"==typeof e.randomUUID)return e.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}const DEFAULT_API_BASE="https://aegiscloud.org",CLIENT_VERSION="3.2.0",DEFAULT_TIMEOUT_MS=6e4,MAX_BODY_BYTES=8388608,RATE_LIMIT_RETRIES=4,RATE_LIMIT_MAX_WAIT_MS=3e4,RATE_LIMIT_BASE_WAIT_MS=1e3,TRANSIENT_STREAM_ERROR_PATTERN=/connection reset by peer|broken pipe|connection aborted|errno 104|errno 32|errno 54|econnreset|epipe/i,TRANSIENT_STREAM_RETRIES=2,TRANSIENT_STREAM_BASE_WAIT_MS=500,TRANSIENT_SOCKET_CODE_PATTERN=/^(ECONNRESET|EPIPE|ECONNABORTED|UND_ERR_SOCKET|UND_ERR_CLOSED)$/,TRANSIENT_SOCKET_RETRIES=2,SSE_UPSTREAM_TIMEOUT_PATTERN=/request timed out|timed out waiting|upstream timeout/i;function upstreamTimeoutMessage(e,t){const n=Number(t);return`${e} — the upstream provider gave up before answering${null!=t&&Number.isFinite(n)?n>=1e3?` after ${(n/1e3).toFixed(1)}s`:` after ${Math.max(0,Math.round(n))}ms`:""}. That is the provider's own deadline, not this client's stream budget, so raising AEGIS_SSE_IDLE_TIMEOUT_MS cannot help`}function createClient(e={}){const t=(e.apiBase||envVar("AEGIS_API_BASE")||DEFAULT_API_BASE).replace(/\/+$/,"");let n=void 0!==e.apiKey?e.apiKey:envVar("AEGIS_API_KEY");const r=void 0!==e.memoryToken?e.memoryToken:envVar("AEGIS_MEMORY_TOKEN"),o=e.clientVersion||"3.2.0",s="cli"===e.channel?"cli":"desktop";function a(e){return n&&"string"==typeof e?e.split(n).join("[redacted]"):e}const i={ECONNRESET:"connection reset by the backend",ECONNREFUSED:"connection refused — is the backend running?",EPIPE:"connection closed while sending the request",ETIMEDOUT:"connection timed out",ENOTFOUND:"host not found — check the endpoint URL",EAI_AGAIN:"DNS lookup failed temporarily",EHOSTUNREACH:"host unreachable",ENETUNREACH:"network unreachable",CERT_HAS_EXPIRED:"TLS certificate has expired",DEPTH_ZERO_SELF_SIGNED_CERT:"TLS certificate is self-signed",UND_ERR_SOCKET:"the socket closed before the response finished",UND_ERR_CLOSED:"the connection was closed",UND_ERR_CONNECT_TIMEOUT:"timed out connecting to the backend",UND_ERR_HEADERS_TIMEOUT:"the backend accepted the connection but never sent a response",UND_ERR_BODY_TIMEOUT:"the backend stalled mid-response",UND_ERR_ABORTED:"the request was aborted"};function c(e,t){const n=e instanceof Error?e:new Error(String(e)),r=n&&n.name;if("AbortError"===r||"TimeoutError"===r)return e;const o=l(n),s=t||"the backend",a=new Error(o?`Could not reach ${s} (${o}).`:`Could not reach ${s}: ${n.message||"network failure"}.`);return a.status=0,a.code="network",a.networkCode=o||null,a.data=null,a.cause=n,a}function l(e,t=0){if(!e||t>4)return null;const n=e.code||e.cause&&e.cause.code,r=e.cause,o=r?l(r,t+1):null;return i[n]?i[n]:o||(r&&r.message&&r.message!==e.message?r.message:n||null)}async function u(e,n){const r=n&&n.signal,o="function"==typeof AbortController?new AbortController:null;let s=null;o&&(s=setTimeout((()=>o.abort()),S),s&&"function"==typeof s.unref&&s.unref(),r&&(r.aborted?o.abort():"function"==typeof r.addEventListener&&r.addEventListener("abort",(()=>{o&&o.abort()}),{once:!0})));try{return await fetch(e,{...n||{},signal:o?o.signal:r})}catch(e){if(o&&o.signal.aborted&&(!r||!r.aborted)){const e=new Error(`Timed out after ${S/1e3}s waiting for ${t}.`);throw e.status=0,e.code="timeout",e.data=null,e}throw c(e,t)}finally{s&&clearTimeout(s)}}function d(e,t){const n=e&&e.headers&&"function"==typeof e.headers.get?e.headers.get("retry-after"):null;let r=0;if(n){const e=Number(n);if(Number.isFinite(e)&&e>=0)r=1e3*e;else{const e=Date.parse(n);Number.isFinite(e)&&(r=e-Date.now())}}return r||(r=R*Math.pow(2,t)),Math.min(r,A)}function m(e,t){return new Promise((n=>{const r=setTimeout(n,e);if(r&&"function"==typeof r.unref&&r.unref(),t&&"function"==typeof t.addEventListener)return t.aborted?(clearTimeout(r),void n()):void t.addEventListener("abort",(()=>{clearTimeout(r),n()}),{once:!0})}))}function _(e,t=0){if(!e||t>4)return null;const n=e.code;return"string"==typeof n&&"network"!==n?n:_(e.cause,t+1)}async function f(e,t){let n=0;for(;;)try{return await u(e,t)}catch(e){const r=e&&"network"===e.code?String(_(e)||""):"";if(n>=2||!TRANSIENT_SOCKET_CODE_PATTERN.test(r))throw e;if(t&&t.signal&&t.signal.aborted)throw e;if(await m(500*Math.pow(2,n),t&&t.signal),t&&t.signal&&t.signal.aborted)throw e;n++}}async function E(e,t){let n=await f(e,t);for(let r=0;n&&429===n.status&&r<T;r++){const o=d(n,r);try{n.body&&await n.body.cancel()}catch{}await m(o,t&&t.signal),n=await f(e,t)}for(let r=0;n&&n.status>=500&&n.status<600&&r<2;r++){let o="";try{o=await g(n.clone())}catch{break}if(!TRANSIENT_STREAM_ERROR_PATTERN.test(o))break;await m(500*Math.pow(2,r),t&&t.signal),n=await f(e,t)}return n}function p(e){if(!e)return e;if("AbortError"===e.name||"TimeoutError"===e.name)return e;if("network"===e.code||"timeout"===e.code||"ABORT_ERR"===e.code)return e;if(/^stream stalled - /.test(String(e.message||"")))return e;if(!_(e))return e;const n=c(e,t);return n.bodyPhase=!0,n}async function g(e){if(!e||!e.body||"function"!=typeof e.body.getReader){let t;try{t=await e.text()}catch(e){const t=p(e);throw t&&"network"===t.code&&(t.bytesRead=0),t||e}return t.length>h?t.slice(0,h):t}const n=e.body.getReader(),r=new TextDecoder;let o="",s=0;try{for(;;){let a;try{a=await n.read()}catch(e){const t=p(e);throw t&&"network"===t.code&&(t.bytesRead=s),t||e}const{done:i,value:c}=a;if(i)break;if(s+=c?c.byteLength:0,s>h){const n=new Error(`Response from ${t} exceeded the ${h/1048576}MB cap.`);throw n.status=e.status,n.code="body_too_large",n.data=null,n}o+=r.decode(c,{stream:!0})}return o+=r.decode(),o}finally{try{await n.cancel()}catch{}}}let y=null;const S=Number(e.timeoutMs)>0?Number(e.timeoutMs):Number(envVar("AEGIS_HTTP_TIMEOUT_MS"))>0?Number(envVar("AEGIS_HTTP_TIMEOUT_MS")):6e4,h=Number(e.maxBodyBytes)>0?Number(e.maxBodyBytes):8388608,T=Number(e.rateLimitRetries)>=0?Number(e.rateLimitRetries):4,R=Number(e.rateLimitBaseWaitMs)>=0?Number(e.rateLimitBaseWaitMs):1e3,A=Number(e.rateLimitMaxWaitMs)>0?Number(e.rateLimitMaxWaitMs):3e4;function M(e,n){try{const r=new URL(`/go/${String(e||"upgrade").replace(/^\/+|\/+$/g,"")}`,t);r.searchParams.set("s",s);const o=String(n||"").trim().toLowerCase();return/^[a-z0-9][a-z0-9_-]{0,63}$/.test(o)&&r.searchParams.set("c",o),r.toString()}catch(e){return""}}function D(e){const t={"Content-Type":"application/json","X-AEGIS-Version":o,...e};return n&&(t["X-API-Key"]=n,t.Authorization=`Bearer ${n}`),t}async function L(e,n){return O(await E(`${t}${e}`,n))}async function I(e,t){let n=0;for(;;)try{return await L(e,t)}catch(e){if(!e||"network"!==e.code||!0!==e.bodyPhase||0!==e.bytesRead||n>=2)throw e;if(t&&t.signal&&t.signal.aborted)throw e;if(await m(500*Math.pow(2,n),t&&t.signal),t&&t.signal&&t.signal.aborted)throw e;n++}}async function w(e,t,n,r){return I(e,{method:"POST",headers:n||D(),body:JSON.stringify(t||{}),signal:r&&r.signal})}async function b(e,t,n){return I(e,{method:"GET",headers:t||D(),signal:n&&n.signal})}function N(e,t){const n=e||{},r=n.latest_cli||"",s=n.latest_desktop||"",a=r||s||n.required||"",i=new Error(a?`This client (v${o}) is out of date — upgrade to v${a}.`:`This client (v${o}) is out of date.`);return i.status=t,i.code="version_mismatch",i.data=n,i.upgrade={required:n.required||"",latestCli:r,latestDesktop:s,url:M("upgrade","version_gate")||n.update_url||""},i}async function O(e){const t=await g(e);let n;try{n=t?JSON.parse(t):{}}catch{n={raw:a(t)}}if(!e.ok){if(function(e,t){return 426===e||t&&"version_mismatch"===t.code}(e.status,n))throw N(n,e.status);const t=n&&(n.error?.message||n.error||n.message)||`HTTP ${e.status}`,r=new Error(a("string"==typeof t?t:JSON.stringify(t)));throw e.status>=500&&e.status<600&&SSE_UPSTREAM_TIMEOUT_PATTERN.test(r.message)?(r.serverStatus=e.status,r.status=0,r.code="timeout",r.message=upstreamTimeoutMessage(r.message)):r.status=e.status,r.data=n,r}if(n&&"version_mismatch"===n.code)throw N(n,e.status);return n}function v(e){if(!e)return"";const t=e.error;return"string"==typeof t?t:t&&"string"==typeof t.message?t.message:t&&"string"==typeof t.error?t.error:"string"==typeof e.message?e.message:"string"==typeof e.error_message?e.error_message:""}async function k(){if(r)return r;if(y)return y;const e=await w("/api/verify-api-key",{api_key:n});if(!e||!e.memory_token){const e=M("upgrade","memory_quota");throw new Error("This AEGIS account has no memory token. "+(e?`Enable cloud memory at ${e}`:"Enable cloud memory in your AEGIS account settings."))}return y=e.memory_token,y}function x(e){return{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`}}function U(e){if(null==e)return"";if("string"==typeof e)return e;if(!Array.isArray(e))return String(e);let t="";for(let n=0;n<e.length;n+=1){const r=e[n];r&&"object"==typeof r&&("string"==typeof r.text?t+=(t?"\n":"")+r.text:"image_url"===r.type&&(t+=(t?"\n":"")+"[image]"))}return t}function C(e,t,n){const r=Array.isArray(e)?e.filter(Boolean):[],o=[];if(t&&!r.some((e=>e&&"system"===e.role))&&o.push({role:"system",content:t}),o.push(...r),null!=n&&("string"==typeof n?""!==n:Array.isArray(n)&&n.length>0)){const e=o[o.length-1];(Array.isArray(n)&&e&&"user"===e.role?U(e.content)===U(n):e&&"user"===e.role&&e.content===n)||o.push({role:"user",content:n})}return o}function P(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;return"string"==typeof n?n:""}function $(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;if("string"!=typeof n||-1===n.indexOf("|"))return e;const r=decodeDeepSeekDSML(n),o=decodeDeepSeekDSMLDrift(r.text);t.message.content=dsmlResidue(o.text);const s=[...r.calls,...o.calls];return s.length&&(e.toolCalls=[...Array.isArray(e.toolCalls)?e.toolCalls:[],...s.map((e=>({id:"",name:e.name,args:e.args||{}})))]),e}async function B(e,n,r,o,s,i){const{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:u,_transientStreamAttempt:d=0}=i||{},_=n=>E(`${t}${e}`,{method:"POST",headers:r,body:JSON.stringify({...n,stream:!0}),signal:s});let f;try{f=await _(n)}catch(e){throw e}if(!f.ok&&426===f.status){let e={};try{const t=await g(f);e=t?JSON.parse(t):{}}catch{e={}}throw N(e,f.status)}if(!f.ok&&u&&n.stream_options){try{f.body&&await f.body.cancel()}catch{}const t={...n};delete t.stream_options,n=t;try{f=await _(n)}catch(e){throw e}}if(!f.ok){const t={...n};delete t.stream_options;const a=$(await w(e,{...t,stream:!1},r,{signal:s})),i=P(a);return i&&o({delta:i}),a}if(!(f.headers.get("content-type")||"").includes("text/event-stream")){const e=$(await O(f)),t=P(e);return t?o({delta:t}):function(e,t){if(e&&"version_mismatch"===e.code)throw N(e,t||426);const n=a(v(e));if(!n)return;const r=new Error(n);throw r.status=t||500,r.data=e,r}(e,f.status),e}const y=f.body.getReader(),S=new TextDecoder;let h="",T="",R="",A=n.model,M=null,D="";const L=new Map;let I=null,b="";const k=makeDeepSeekEnvelopeStripper(),x=idleBudgetFor(f,l);let U=Date.now();const C=U;let K=0;async function G(){let e,t=null;const n=Math.max(0,x-(Date.now()-U)),r=new Promise(((t,r)=>{e=setTimeout((()=>{r(new Error(K>0?`stream stalled - only keep-alives for ${x/1e3}s`:`stream stalled - no data for ${x/1e3}s`))}),n)})),o=s&&"function"==typeof s.addEventListener?new Promise(((e,n)=>{t=()=>{const e=new Error("The turn was stopped.");e.name="AbortError",e.code="ABORT_ERR",n(e)},s.aborted?t():s.addEventListener("abort",t,{once:!0})})):null;try{return await(o?Promise.race([y.read(),r,o]):Promise.race([y.read(),r]))}finally{clearTimeout(e),s&&t&&"function"==typeof s.removeEventListener&&s.removeEventListener("abort",t)}}for(;;){let t,l;try{({done:t,value:l}=await G())}catch(t){y.cancel().catch((()=>{}));const a=p(t);if(a&&"network"===a.code&&(a.bytesRead=b?1:0,0===a.bytesRead&&d<2&&(!s||!s.aborted))){if(await m(500*Math.pow(2,d),s),s&&s.aborted)throw a;return B(e,n,r,o,s,{...i,_transientStreamAttempt:d+1})}throw a||t}if(t)break;h+=S.decode(l,{stream:!0});const u=h.split("\n");h=u.pop();for(const e of u){const t=e.trim();if(!t.startsWith("data:")){t.startsWith(":")&&K++;continue}U=Date.now();const n=t.slice(5).trim();if(!n||"[DONE]"===n)continue;let r;try{r=JSON.parse(n)}catch{continue}if(r.error){if(!D){const e=r.error;D="string"==typeof e?e:v({error:e})||"stream error",D=a(D)}continue}r.model&&(A=r.model),r.usage&&(M=r.usage);const s=r.choices&&r.choices[0];s&&s.finish_reason&&(I=s.finish_reason);const i=(e,t,n,r)=>{if("string"==typeof e&&e)return r(e),n+e;if("string"==typeof t&&t){if(!n)return r(t),t;if(t.startsWith(n)){const e=t.slice(n.length);return e&&r(e),t}return n}return n};R=i(s&&s.delta&&s.delta.reasoning_content,s&&s.message&&s.message.reasoning_content,R,(e=>{"function"==typeof c?c(e):o({reasoning:e})})),T=i(s&&s.delta&&s.delta.content,s&&s.message&&s.message.content,T,(e=>{const t=k(e);t&&(b+=t,o({delta:t}))}));const l=s&&s.delta&&s.delta.tool_calls||s&&s.message&&s.message.tool_calls;if(Array.isArray(l))for(const e of l){const t=null==e.index?0:e.index,n=L.get(t)||{id:"",type:"function",function:{name:"",arguments:""}};e.id&&(n.id=e.id),e.type&&(n.type=e.type);const r=e.function||{};r.name&&(n.function.name=r.name),"string"==typeof r.arguments&&(n.function.arguments+=r.arguments),L.set(t,n)}}}if(!T&&D){if(d<2&&TRANSIENT_STREAM_ERROR_PATTERN.test(D))return await m(500*Math.pow(2,d),s),B(e,n,r,o,s,{...i,_transientStreamAttempt:d+1});const t=SSE_UPSTREAM_TIMEOUT_PATTERN.test(D),a=new Error(t?upstreamTimeoutMessage(D,Date.now()-C):D);throw a.status=t?0:f.status,t&&(a.code="timeout"),a}const V=k.flush();V&&(b+=V,o({delta:V}));const F=[...L.entries()].sort(((e,t)=>e[0]-t[0])).map((([e,t])=>({...t,id:t.id||`call_${e}`}))),J={content:b};R&&(J.reasoning_content=R),F.length&&(J.tool_calls=F);const W={model:A,choices:[{message:J,...I?{finish_reason:I}:{}}]};M&&(W.usage=M);const X=k.calls();return(F.length||X.length)&&(W.toolCalls=[...F.map((e=>({id:e.id,name:e.function.name,args:e.function.arguments}))),...X.map((e=>({id:"",name:e.name,args:e.args||{}})))]),W}return{apiBase:t,get apiKey(){return n},setApiKey:function(e){return n="string"==typeof e?e.trim():"",y=null,n},get clientVersion(){return o},get channel(){return s},promptUrl:M,verifyApiKey:async function(){return w("/api/verify-api-key",{api_key:n})},registerDevice:async function(e,t){return w("/api/v1/auth/register-device",{fingerprint:e,app:t&&t.app},void 0,t)},chatCompletion:async function({prompt:e,system:t,messages:n,model:r,mode:o,maxTokens:s,stream:a=!1,onStream:i,onReasoning:c,idleTimeoutMs:l,includeUsage:u,signal:d,extra:m,agentKey:_}={}){const f={messages:C(n,t,e),...s?{max_tokens:s}:{},...m||{}};r?f.model=r:o&&(f.mode=o);const E=D(_?{"X-AEGIS-Agent-Key":_}:void 0);return a&&"function"==typeof i?(u&&(f.stream_options={include_usage:!0}),B("/api/v1/chat/completions",f,E,i,d,{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:Boolean(u)})):$(await w("/api/v1/chat/completions",{...f,stream:!1},E,{signal:d}))},byokChatCompletion:async function({provider:t="openai",model:r,messages:s,prompt:a,system:i,maxTokens:c,effort:l,reasoningEffort:u,tools:d,toolChoice:m,stream:_=!1,onStream:f,signal:E,providerKey:p,baseURL:g}={}){const y=void 0!==p?p:e.providerKey;if("custom"===t&&!g){const e=new Error('the "custom" provider dials the endpoint you name, and this call names none — save the address first: /model-add custom <https-base-url> <api-key> <model-id>, or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const S={provider:t,messages:C(s,i,a),...c?{max_tokens:c}:{},...l?{effort:l}:{},...u?{reasoning_effort:u}:{},...Array.isArray(d)&&d.length?{tools:d}:{},...m?{tool_choice:m}:{},...g?{base_url:g}:{}};r&&(S.model=r);const h={"Content-Type":"application/json","X-AEGIS-Version":o,"X-Provider-Key":y};return n&&(h["X-AEGIS-Key"]=n),_&&"function"==typeof f?B("/api/v1/byok/chat/completions",S,h,f,E):$(await w("/api/v1/byok/chat/completions",{...S,stream:!1},h))},listModels:async function(e){return b("/api/v1/models",null,e)},tokenBankBalance:async function(e){return b("/api/token-bank/balance",null,e)},tokenBankTopup:async function(e){return w("/api/token-bank/topup",{amount_eur:e})},billingCheckout:async function(){return w("/api/billing/checkout",{})},byokStatus:async function(e){return b("/api/user/api-keys",null,e)},byokProviders:async function(e){return b("/api/v1/byok/providers",null,e)},catalog:async function(e,t,n){const r=(e||"models").replace(/^\/+/,""),o=new URLSearchParams;for(const[e,n]of Object.entries(t||{}))null!=n&&""!==n&&o.set(e,String(n));const s=o.toString();return b(`/api/v1/catalog/${r}${s?`?${s}`:""}`,n&&n.etag?{...D(),"If-None-Match":n.etag}:D(),n)},byokSet:async function(e,t){return w("/api/user/api-keys",{provider:e,api_key:t||""})},getMemoryToken:k,memorySearch:async function(e,t){return w("/api/memory/search",{query:e||"",limit:t||5},x(await k()))},memorySave:async function(e){return w("/api/memory/save",{entry:e},x(await k()))},memoryList:async function(e){return w("/api/memory/search",{query:"",limit:e||10},x(await k()))},verifyToken:async function(e){return w("/api/verify-token",{token:e||""},{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`})},memoryActivate:async function(e){return w("/api/memory/activate",{},x(e||await k()))},memoryPull:async function(e){return w("/api/memory/pull",{since:e||0},x(await k()))},memorySaveBatch:async function(e){return w("/api/memory/save",{entries:e||[]},x(await k()))},conversationSyncPush:async function(e){const t=await k();return w("/api/conversations/sync",{session_id:e&&e.session_id,title:e&&e.title||"",messages:e&&e.messages||[],source:e&&e.source||"aegis-desktop"},x(t))},conversationSyncPull:async function(){return w("/api/conversations/sync",{},x(await k()))},importConversation:async function({messages:e,url:t,title:n,source:r}={}){return w("/api/import",{messages:e||[],url:t||"",title:n||"",source:r||"aegiscode-plugin"})},driveToken:async function(){try{return await b("/api/drive/token")}catch(e){if(e&&404===e.status)return{connected:!1,access_token:null,email:null};throw e}},randomUUID:randomUUID}}const SSE_IDLE_TIMEOUT_MS=6e4,BRAIN_IDLE_TIMEOUT_MS=9e5;function idleBudgetFor(e,t){const n=Number(t),r=envIdleMs("AEGIS_SSE_IDLE_TIMEOUT_MS"),o=n>0?n:r>0?r:SSE_IDLE_TIMEOUT_MS;let s="";try{const t=e&&e.headers&&"function"==typeof e.headers.get?e.headers.get.bind(e.headers):null;s=t&&t("X-AEGIS-Brain")||""}catch{s=""}const a=envIdleMs("AEGIS_BRAIN_IDLE_TIMEOUT_MS")||BRAIN_IDLE_TIMEOUT_MS;return s&&String(s).trim()?Math.max(o,a):o}function isVersionGateError(e){return!(!e||"version_mismatch"!==e.code)}const api={createClient:createClient,envVar:envVar,randomUUID:randomUUID,DEFAULT_API_BASE:DEFAULT_API_BASE,CLIENT_VERSION:"3.2.0",isVersionGateError:isVersionGateError,idleBudgetFor:idleBudgetFor,SSE_IDLE_TIMEOUT_MS:SSE_IDLE_TIMEOUT_MS,BRAIN_IDLE_TIMEOUT_MS:BRAIN_IDLE_TIMEOUT_MS};"undefined"!=typeof module&&module.exports&&(module.exports=api),"undefined"!=typeof window&&(window.AegisClient=api);
|
|
4
|
+
"use strict";function envVar(e){if("undefined"==typeof process||!process.env)return"";const t=process.env[e];return t&&!/^\$\{[A-Z_]+\}$/.test(t)?t:""}function envIdleMs(e){const t=envVar(e);if(!t)return 0;const n=Number(t);return Number.isFinite(n)&&n>0?n:0}const DSML_RE_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*>/g,DSML_RE_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/g,DSML_RE_LEADER=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:(?:tool|function)[_▁ ]*calls?|reasoning)[_▁ ]*(?:begin|end)?\s*>/gi,DSML_RE_ANY_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_SKELETON=/<\s*\/?\s*(?:tool_calls|function_calls|invoke|parameter|param|reasoning)\b[^>]{0,120}>/gi,DSML_RE_JSON_CALLS=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|([\s\S]*?)|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_JSON_CALLS_OPEN=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|/gi,DSML_RE_JSON_CALLS_CLOSE=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_ENVELOPE_TOKEN=/|[ \t]?[A-Za-z0-9_▁]*[ \t]?|/g,DSML_RE_DRIFT_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>/gi,DSML_RE_DRIFT_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>/gi,DSML_RE_PARAM_CLOSE=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/gi,DSML_RE_ATTR=/([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,DSML_RE_STRUCT_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_STRUCT_CLOSER=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_WRAPPER_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?!(?:invoke|call|tool_call|parameter|param|arg)\b)[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_TRAILING_LT=/<\s*\/?\s*$/,DSML_RE_OPEN_TOKEN=/^|[ \t]?[A-Za-z0-9_▁]*[ \t]?$/,DSML_HOLD_MAX=4194304;function dsmlAttrs(e){const t={};if(!e)return t;let n;for(DSML_RE_ATTR.lastIndex=0;n=DSML_RE_ATTR.exec(e);)t[n[1].toLowerCase()]=null!=n[2]?n[2]:n[3];return t}function dsmlJson(e){const t=String(null==e?"":e).trim();try{const e=JSON.parse(t);return void 0===e?t:e}catch{return t}}function dsmlArgs(e){const t={};let n;for(DSML_RE_PARAM.lastIndex=0;n=DSML_RE_PARAM.exec(e);){const e=dsmlAttrs(n[1]),r=e.name||e.key||`arg${Object.keys(t).length}`,o="false"===String(e.string||"").toLowerCase()||"true"===String(e.json||"").toLowerCase();t[r]=o?dsmlJson(n[2]):n[2]}return t}function decodeDeepSeekDSML(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n=e;DSML_RE_INVOKE.lastIndex=0;const r=[];let o;for(;o=DSML_RE_INVOKE.exec(n);){const e=dsmlAttrs(o[1]),n=e.name||e.function||e.tool||"";n&&t.push({name:n,args:dsmlArgs(o[2])}),r.push([o.index,o.index+o[0].length])}for(let e=r.length-1;e>=0;e--)n=n.slice(0,r[e][0])+n.slice(r[e][1]);return n=n.replace(DSML_RE_JSON_CALLS,((e,n)=>{const r=dsmlJson(n),o=Array.isArray(r)?r:r&&Array.isArray(r.tool_calls)?r.tool_calls:[];for(const e of o){const n=e&&e.function||e||{},r=n.name||e&&e.name||"";if(!r)continue;let o=null!=n.arguments?n.arguments:e&&e.arguments;"string"==typeof o&&(o=dsmlJson(o)),t.push({name:r,args:o&&"object"==typeof o?o:{}})}return""})),n=n.replace(DSML_RE_LEADER,""),{text:n,calls:t}}function decodeDeepSeekDSMLDrift(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n;for(DSML_RE_DRIFT_INVOKE.lastIndex=0;n=DSML_RE_DRIFT_INVOKE.exec(e);)t.push({at:n.index,attrs:n[1],body:DSML_RE_DRIFT_INVOKE.lastIndex});if(!t.length)return{text:e,calls:[]};const r=[];let o="",s=0;for(let n=0;n<t.length;n++){const a=n+1<t.length?t[n+1].at:e.length,i=e.slice(t[n].body,a),c=dsmlAttrs(t[n].attrs),l=c.name||c.function||c.tool||"",u={},d=[];let m;for(DSML_RE_DRIFT_PARAM.lastIndex=0;m=DSML_RE_DRIFT_PARAM.exec(i);)d.push({at:m.index,attrs:m[1],from:DSML_RE_DRIFT_PARAM.lastIndex});for(let e=0;e<d.length;e++){const t=e+1<d.length?d[e+1].at:i.length,n=i.slice(d[e].from,t).replace(DSML_RE_PARAM_CLOSE,""),r=dsmlAttrs(d[e].attrs),o=r.name||r.key||`arg${Object.keys(u).length}`,s="false"===String(r.string||"").toLowerCase();u[o]=s?dsmlJson(n):n}o+=e.slice(s,t[n].at),s=a,l&&r.push({name:l,args:u})}return o+=e.slice(s),{text:o,calls:r}}function dsmlResidue(e){return e?-1===e.indexOf("|")?e.replace(DSML_RE_SKELETON,""):e.replace(DSML_RE_ANY_TAG,"").replace(DSML_RE_SKELETON,"").replace(DSML_RE_ENVELOPE_TOKEN,""):e}function dsmlUnterminated(e){return!!DSML_RE_OPEN_TOKEN.test(e)||(e.match(DSML_RE_STRUCT_TAG)||[]).length>(e.match(DSML_RE_STRUCT_CLOSER)||[]).length}function dsmlHoldFrom(e){const t=e.search(/<\s*\/?\s*|/);if(-1!==t)return t;const n=e.search(DSML_RE_JSON_CALLS_OPEN);if(-1!==n&&-1===e.slice(n).search(DSML_RE_JSON_CALLS_CLOSE))return n;const r=DSML_RE_TRAILING_LT.exec(e);if(r)return r.index;const o=e.indexOf("|");return-1!==o&&dsmlUnterminated(e.slice(o))?o:-1}function makeDeepSeekEnvelopeStripper(){let e="";const t=[],n=n=>{e+="string"==typeof n?n:"";const r=decodeDeepSeekDSML(e);e=r.text;for(const e of r.calls)t.push(e);e=e.replace(DSML_RE_WRAPPER_TAG,"");const o=dsmlHoldFrom(e);let s;return-1!==o&&e.length-o<=DSML_HOLD_MAX?(s=e.slice(0,o),e=e.slice(o)):(s=e,e=""),dsmlResidue(s)};return n.flush=()=>{const n=decodeDeepSeekDSML(e);e="";for(const e of n.calls)t.push(e);const r=decodeDeepSeekDSMLDrift(n.text);for(const e of r.calls)t.push(e);return dsmlResidue(r.text)},n.calls=()=>t.slice(),n}function randomUUID(){const e="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||null,t=e&&e.crypto;if(t&&"function"==typeof t.randomUUID)try{return t.randomUUID()}catch(e){}if(t&&"function"==typeof t.getRandomValues)try{const e=new Uint8Array(16);t.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128;const n=Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}catch(e){}if("function"==typeof require)try{const e=require("crypto");if(e&&"function"==typeof e.randomUUID)return e.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}const DEFAULT_API_BASE="https://aegiscloud.org",CLIENT_VERSION="3.2.0",DEFAULT_TIMEOUT_MS=6e4,MAX_BODY_BYTES=8388608,RATE_LIMIT_RETRIES=4,RATE_LIMIT_MAX_WAIT_MS=3e4,RATE_LIMIT_BASE_WAIT_MS=1e3,TRANSIENT_STREAM_ERROR_PATTERN=/connection reset by peer|broken pipe|connection aborted|errno 104|errno 32|errno 54|econnreset|epipe/i,TRANSIENT_STREAM_RETRIES=2,TRANSIENT_STREAM_BASE_WAIT_MS=500,TRANSIENT_SOCKET_CODE_PATTERN=/^(ECONNRESET|EPIPE|ECONNABORTED|UND_ERR_SOCKET|UND_ERR_CLOSED)$/,TRANSIENT_SOCKET_RETRIES=2,SSE_UPSTREAM_TIMEOUT_PATTERN=/request timed out|timed out waiting|upstream timeout/i;function upstreamTimeoutMessage(e,t){const n=Number(t);return`${e} — the upstream provider gave up before answering${null!=t&&Number.isFinite(n)?n>=1e3?` after ${(n/1e3).toFixed(1)}s`:` after ${Math.max(0,Math.round(n))}ms`:""}. That is the provider's own deadline, not this client's stream budget, so raising AEGIS_SSE_IDLE_TIMEOUT_MS cannot help`}function createClient(e={}){const t=(e.apiBase||envVar("AEGIS_API_BASE")||DEFAULT_API_BASE).replace(/\/+$/,"");let n=void 0!==e.apiKey?e.apiKey:envVar("AEGIS_API_KEY");const r=void 0!==e.memoryToken?e.memoryToken:envVar("AEGIS_MEMORY_TOKEN"),o=e.clientVersion||"3.2.0",s="cli"===e.channel?"cli":"desktop";function a(e){return n&&"string"==typeof e?e.split(n).join("[redacted]"):e}const i={ECONNRESET:"connection reset by the backend",ECONNREFUSED:"connection refused — is the backend running?",EPIPE:"connection closed while sending the request",ETIMEDOUT:"connection timed out",ENOTFOUND:"host not found — check the endpoint URL",EAI_AGAIN:"DNS lookup failed temporarily",EHOSTUNREACH:"host unreachable",ENETUNREACH:"network unreachable",CERT_HAS_EXPIRED:"TLS certificate has expired",DEPTH_ZERO_SELF_SIGNED_CERT:"TLS certificate is self-signed",UND_ERR_SOCKET:"the socket closed before the response finished",UND_ERR_CLOSED:"the connection was closed",UND_ERR_CONNECT_TIMEOUT:"timed out connecting to the backend",UND_ERR_HEADERS_TIMEOUT:"the backend accepted the connection but never sent a response",UND_ERR_BODY_TIMEOUT:"the backend stalled mid-response",UND_ERR_ABORTED:"the request was aborted"};function c(e,t){const n=e instanceof Error?e:new Error(String(e)),r=n&&n.name;if("AbortError"===r||"TimeoutError"===r)return e;const o=l(n),s=t||"the backend",a=new Error(o?`Could not reach ${s} (${o}).`:`Could not reach ${s}: ${n.message||"network failure"}.`);return a.status=0,a.code="network",a.networkCode=o||null,a.data=null,a.cause=n,a}function l(e,t=0){if(!e||t>4)return null;const n=e.code||e.cause&&e.cause.code,r=e.cause,o=r?l(r,t+1):null;return i[n]?i[n]:o||(r&&r.message&&r.message!==e.message?r.message:n||null)}async function u(e,n){const r=n&&n.signal,o="function"==typeof AbortController?new AbortController:null;let s=null;o&&(s=setTimeout((()=>o.abort()),S),s&&"function"==typeof s.unref&&s.unref(),r&&(r.aborted?o.abort():"function"==typeof r.addEventListener&&r.addEventListener("abort",(()=>{o&&o.abort()}),{once:!0})));try{return await fetch(e,{...n||{},signal:o?o.signal:r})}catch(e){if(o&&o.signal.aborted&&(!r||!r.aborted)){const e=new Error(`Timed out after ${S/1e3}s waiting for ${t}.`);throw e.status=0,e.code="timeout",e.data=null,e}throw c(e,t)}finally{s&&clearTimeout(s)}}function d(e,t){const n=e&&e.headers&&"function"==typeof e.headers.get?e.headers.get("retry-after"):null;let r=0;if(n){const e=Number(n);if(Number.isFinite(e)&&e>=0)r=1e3*e;else{const e=Date.parse(n);Number.isFinite(e)&&(r=e-Date.now())}}return r||(r=R*Math.pow(2,t)),Math.min(r,A)}function m(e,t){return new Promise((n=>{const r=setTimeout(n,e);if(r&&"function"==typeof r.unref&&r.unref(),t&&"function"==typeof t.addEventListener)return t.aborted?(clearTimeout(r),void n()):void t.addEventListener("abort",(()=>{clearTimeout(r),n()}),{once:!0})}))}function _(e,t=0){if(!e||t>4)return null;const n=e.code;return"string"==typeof n&&"network"!==n?n:_(e.cause,t+1)}async function f(e,t){let n=0;for(;;)try{return await u(e,t)}catch(e){const r=e&&"network"===e.code?String(_(e)||""):"";if(n>=2||!TRANSIENT_SOCKET_CODE_PATTERN.test(r))throw e;if(t&&t.signal&&t.signal.aborted)throw e;if(await m(500*Math.pow(2,n),t&&t.signal),t&&t.signal&&t.signal.aborted)throw e;n++}}async function E(e,t){let n=await f(e,t);for(let r=0;n&&429===n.status&&r<T;r++){const o=d(n,r);try{n.body&&await n.body.cancel()}catch{}await m(o,t&&t.signal),n=await f(e,t)}for(let r=0;n&&n.status>=500&&n.status<600&&r<2;r++){let o="";try{o=await g(n.clone())}catch{break}if(!TRANSIENT_STREAM_ERROR_PATTERN.test(o))break;await m(500*Math.pow(2,r),t&&t.signal),n=await f(e,t)}return n}function p(e){if(!e)return e;if("AbortError"===e.name||"TimeoutError"===e.name)return e;if("network"===e.code||"timeout"===e.code||"ABORT_ERR"===e.code)return e;if(/^stream stalled - /.test(String(e.message||"")))return e;if(!_(e))return e;const n=c(e,t);return n.bodyPhase=!0,n}async function g(e){if(!e||!e.body||"function"!=typeof e.body.getReader){let t;try{t=await e.text()}catch(e){const t=p(e);throw t&&"network"===t.code&&(t.bytesRead=0),t||e}return t.length>h?t.slice(0,h):t}const n=e.body.getReader(),r=new TextDecoder;let o="",s=0;try{for(;;){let a;try{a=await n.read()}catch(e){const t=p(e);throw t&&"network"===t.code&&(t.bytesRead=s),t||e}const{done:i,value:c}=a;if(i)break;if(s+=c?c.byteLength:0,s>h){const n=new Error(`Response from ${t} exceeded the ${h/1048576}MB cap.`);throw n.status=e.status,n.code="body_too_large",n.data=null,n}o+=r.decode(c,{stream:!0})}return o+=r.decode(),o}finally{try{await n.cancel()}catch{}}}let y=null;const S=Number(e.timeoutMs)>0?Number(e.timeoutMs):Number(envVar("AEGIS_HTTP_TIMEOUT_MS"))>0?Number(envVar("AEGIS_HTTP_TIMEOUT_MS")):6e4,h=Number(e.maxBodyBytes)>0?Number(e.maxBodyBytes):8388608,T=Number(e.rateLimitRetries)>=0?Number(e.rateLimitRetries):4,R=Number(e.rateLimitBaseWaitMs)>=0?Number(e.rateLimitBaseWaitMs):1e3,A=Number(e.rateLimitMaxWaitMs)>0?Number(e.rateLimitMaxWaitMs):3e4;function M(e,n){try{const r=new URL(`/go/${String(e||"upgrade").replace(/^\/+|\/+$/g,"")}`,t);r.searchParams.set("s",s);const o=String(n||"").trim().toLowerCase();return/^[a-z0-9][a-z0-9_-]{0,63}$/.test(o)&&r.searchParams.set("c",o),r.toString()}catch(e){return""}}function D(e){const t={"Content-Type":"application/json","X-AEGIS-Version":o,...e};return n&&(t["X-API-Key"]=n,t.Authorization=`Bearer ${n}`),t}async function L(e,n){return O(await E(`${t}${e}`,n))}async function I(e,t){let n=0;for(;;)try{return await L(e,t)}catch(e){if(!e||"network"!==e.code||!0!==e.bodyPhase||0!==e.bytesRead||n>=2)throw e;if(t&&t.signal&&t.signal.aborted)throw e;if(await m(500*Math.pow(2,n),t&&t.signal),t&&t.signal&&t.signal.aborted)throw e;n++}}async function w(e,t,n,r){return I(e,{method:"POST",headers:n||D(),body:JSON.stringify(t||{}),signal:r&&r.signal})}async function b(e,t,n){return I(e,{method:"GET",headers:t||D(),signal:n&&n.signal})}function N(e,t){const n=e||{},r=n.latest_cli||"",s=n.latest_desktop||"",a=r||s||n.required||"",i=new Error(a?`This client (v${o}) is out of date — upgrade to v${a}.`:`This client (v${o}) is out of date.`);return i.status=t,i.code="version_mismatch",i.data=n,i.upgrade={required:n.required||"",latestCli:r,latestDesktop:s,url:M("upgrade","version_gate")||n.update_url||""},i}async function O(e){const t=await g(e);let n;try{n=t?JSON.parse(t):{}}catch{n={raw:a(t)}}if(!e.ok){if(function(e,t){return 426===e||t&&"version_mismatch"===t.code}(e.status,n))throw N(n,e.status);const t=n&&(n.error?.message||n.error||n.message)||`HTTP ${e.status}`,r=new Error(a("string"==typeof t?t:JSON.stringify(t)));throw e.status>=500&&e.status<600&&SSE_UPSTREAM_TIMEOUT_PATTERN.test(r.message)?(r.serverStatus=e.status,r.status=0,r.code="timeout",r.message=upstreamTimeoutMessage(r.message)):r.status=e.status,r.data=n,r}if(n&&"version_mismatch"===n.code)throw N(n,e.status);return n}function v(e){if(!e)return"";const t=e.error;return"string"==typeof t?t:t&&"string"==typeof t.message?t.message:t&&"string"==typeof t.error?t.error:"string"==typeof e.message?e.message:"string"==typeof e.error_message?e.error_message:""}async function k(){if(r)return r;if(y)return y;const e=await w("/api/verify-api-key",{api_key:n});if(!e||!e.memory_token){const e=M("upgrade","memory_quota");throw new Error("This AEGIS account has no memory token. "+(e?`Enable cloud memory at ${e}`:"Enable cloud memory in your AEGIS account settings."))}return y=e.memory_token,y}function x(e){return{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`}}function U(e){if(null==e)return"";if("string"==typeof e)return e;if(!Array.isArray(e))return String(e);let t="";for(let n=0;n<e.length;n+=1){const r=e[n];r&&"object"==typeof r&&("string"==typeof r.text?t+=(t?"\n":"")+r.text:"image_url"===r.type&&(t+=(t?"\n":"")+"[image]"))}return t}function C(e,t,n){const r=Array.isArray(e)?e.filter(Boolean):[],o=[];if(t&&!r.some((e=>e&&"system"===e.role))&&o.push({role:"system",content:t}),o.push(...r),null!=n&&("string"==typeof n?""!==n:Array.isArray(n)&&n.length>0)){const e=o[o.length-1];(Array.isArray(n)&&e&&"user"===e.role?U(e.content)===U(n):e&&"user"===e.role&&e.content===n)||o.push({role:"user",content:n})}return o}function P(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;return"string"==typeof n?n:""}function $(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;if("string"!=typeof n||-1===n.indexOf("|"))return e;const r=decodeDeepSeekDSML(n),o=decodeDeepSeekDSMLDrift(r.text);t.message.content=dsmlResidue(o.text);const s=[...r.calls,...o.calls];return s.length&&(e.toolCalls=[...Array.isArray(e.toolCalls)?e.toolCalls:[],...s.map((e=>({id:"",name:e.name,args:e.args||{}})))]),e}async function B(e,n,r,o,s,i){const{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:u,_transientStreamAttempt:d=0}=i||{},_=n=>E(`${t}${e}`,{method:"POST",headers:r,body:JSON.stringify({...n,stream:!0}),signal:s});let f;try{f=await _(n)}catch(e){throw e}if(!f.ok&&426===f.status){let e={};try{const t=await g(f);e=t?JSON.parse(t):{}}catch{e={}}throw N(e,f.status)}if(!f.ok&&u&&n.stream_options){try{f.body&&await f.body.cancel()}catch{}const e={...n};delete e.stream_options,n=e;try{f=await _(n)}catch(e){throw e}}if(!f.ok){const t={...n};delete t.stream_options;const a=$(await w(e,{...t,stream:!1},r,{signal:s})),i=P(a);return i&&o({delta:i}),a}if(!(f.headers.get("content-type")||"").includes("text/event-stream")){const e=$(await O(f)),t=P(e);return t?o({delta:t}):function(e,t){if(e&&"version_mismatch"===e.code)throw N(e,t||426);const n=a(v(e));if(!n)return;const r=new Error(n);throw r.status=t||500,r.data=e,r}(e,f.status),e}const y=f.body.getReader(),S=new TextDecoder;let h="",T="",R="",A=n.model,M=null,D="";const L=new Map;let I=null,b="";const k=makeDeepSeekEnvelopeStripper(),x=idleBudgetFor(f,l);let U=Date.now();const C=U;let K=0;async function G(){let e,t=null;const n=Math.max(0,x-(Date.now()-U)),r=new Promise(((t,r)=>{e=setTimeout((()=>{r(new Error(K>0?`stream stalled - only keep-alives for ${x/1e3}s`:`stream stalled - no data for ${x/1e3}s`))}),n)})),o=s&&"function"==typeof s.addEventListener?new Promise(((e,n)=>{t=()=>{const e=new Error("The turn was stopped.");e.name="AbortError",e.code="ABORT_ERR",n(e)},s.aborted?t():s.addEventListener("abort",t,{once:!0})})):null;try{return await(o?Promise.race([y.read(),r,o]):Promise.race([y.read(),r]))}finally{clearTimeout(e),s&&t&&"function"==typeof s.removeEventListener&&s.removeEventListener("abort",t)}}for(;;){let t,l;try{({done:t,value:l}=await G())}catch(t){y.cancel().catch((()=>{}));const a=p(t);if(a&&"network"===a.code&&(a.bytesRead=b?1:0,0===a.bytesRead&&d<2&&(!s||!s.aborted))){if(await m(500*Math.pow(2,d),s),s&&s.aborted)throw a;return B(e,n,r,o,s,{...i,_transientStreamAttempt:d+1})}throw a||t}if(t)break;h+=S.decode(l,{stream:!0});const u=h.split("\n");h=u.pop();for(const e of u){const t=e.trim();if(!t.startsWith("data:")){t.startsWith(":")&&K++;continue}U=Date.now();const n=t.slice(5).trim();if(!n||"[DONE]"===n)continue;let r;try{r=JSON.parse(n)}catch{continue}if(r.error){if(!D){const e=r.error;D="string"==typeof e?e:v({error:e})||"stream error",D=a(D)}continue}r.model&&(A=r.model),r.usage&&(M=r.usage);const s=r.choices&&r.choices[0];s&&s.finish_reason&&(I=s.finish_reason);const i=(e,t,n,r)=>{if("string"==typeof e&&e)return r(e),n+e;if("string"==typeof t&&t){if(!n)return r(t),t;if(t.startsWith(n)){const e=t.slice(n.length);return e&&r(e),t}return n}return n};R=i(s&&s.delta&&s.delta.reasoning_content,s&&s.message&&s.message.reasoning_content,R,(e=>{"function"==typeof c?c(e):o({reasoning:e})})),T=i(s&&s.delta&&s.delta.content,s&&s.message&&s.message.content,T,(e=>{const t=k(e);t&&(b+=t,o({delta:t}))}));const l=s&&s.delta&&s.delta.tool_calls||s&&s.message&&s.message.tool_calls;if(Array.isArray(l))for(const e of l){const t=null==e.index?0:e.index,n=L.get(t)||{id:"",type:"function",function:{name:"",arguments:""}};e.id&&(n.id=e.id),e.type&&(n.type=e.type);const r=e.function||{};r.name&&(n.function.name=r.name),"string"==typeof r.arguments&&(n.function.arguments+=r.arguments),L.set(t,n)}}}if(!T&&D){if(d<2&&TRANSIENT_STREAM_ERROR_PATTERN.test(D))return await m(500*Math.pow(2,d),s),B(e,n,r,o,s,{...i,_transientStreamAttempt:d+1});const t=SSE_UPSTREAM_TIMEOUT_PATTERN.test(D),a=new Error(t?upstreamTimeoutMessage(D,Date.now()-C):D);throw a.status=t?0:f.status,t&&(a.code="timeout"),a}const V=k.flush();V&&(b+=V,o({delta:V}));const F=[...L.entries()].sort(((e,t)=>e[0]-t[0])).map((([e,t])=>({...t,id:t.id||`call_${e}`}))),J={content:b};R&&(J.reasoning_content=R),F.length&&(J.tool_calls=F);const W={model:A,choices:[{message:J,...I?{finish_reason:I}:{}}]};M&&(W.usage=M);const X=k.calls();return(F.length||X.length)&&(W.toolCalls=[...F.map((e=>({id:e.id,name:e.function.name,args:e.function.arguments}))),...X.map((e=>({id:"",name:e.name,args:e.args||{}})))]),W}return{apiBase:t,get apiKey(){return n},setApiKey:function(e){return n="string"==typeof e?e.trim():"",y=null,n},get clientVersion(){return o},get channel(){return s},promptUrl:M,verifyApiKey:async function(){return w("/api/verify-api-key",{api_key:n})},registerDevice:async function(e,t){return w("/api/v1/auth/register-device",{fingerprint:e,app:t&&t.app},void 0,t)},chatCompletion:async function({prompt:e,system:t,messages:n,model:r,mode:o,maxTokens:s,stream:a=!1,onStream:i,onReasoning:c,idleTimeoutMs:l,includeUsage:u,signal:d,extra:m,agentKey:_}={}){const f={messages:C(n,t,e),...s?{max_tokens:s}:{},...m||{}};r?f.model=r:o&&(f.mode=o);const E=D(_?{"X-AEGIS-Agent-Key":_}:void 0);return a&&"function"==typeof i?(u&&(f.stream_options={include_usage:!0}),B("/api/v1/chat/completions",f,E,i,d,{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:Boolean(u)})):$(await w("/api/v1/chat/completions",{...f,stream:!1},E,{signal:d}))},byokChatCompletion:async function({provider:t="openai",model:r,messages:s,prompt:a,system:i,maxTokens:c,effort:l,reasoningEffort:u,tools:d,toolChoice:m,stream:_=!1,onStream:f,signal:E,providerKey:p,baseURL:g}={}){const y=void 0!==p?p:e.providerKey;if("custom"===t&&!g){const e=new Error('the "custom" provider dials the endpoint you name, and this call names none — save the address first: /model-add custom <https-base-url> <api-key> <model-id>, or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const S={provider:t,messages:C(s,i,a),...c?{max_tokens:c}:{},...l?{effort:l}:{},...u?{reasoning_effort:u}:{},...Array.isArray(d)&&d.length?{tools:d}:{},...m?{tool_choice:m}:{},...g?{base_url:g}:{}};r&&(S.model=r);const h={"Content-Type":"application/json","X-AEGIS-Version":o,"X-Provider-Key":y};return n&&(h["X-AEGIS-Key"]=n),_&&"function"==typeof f?B("/api/v1/byok/chat/completions",S,h,f,E):$(await w("/api/v1/byok/chat/completions",{...S,stream:!1},h))},listModels:async function(e){return b("/api/v1/models",null,e)},tokenBankBalance:async function(e){return b("/api/token-bank/balance",null,e)},tokenBankTopup:async function(e){return w("/api/token-bank/topup",{amount_eur:e})},billingCheckout:async function(){return w("/api/billing/checkout",{})},byokStatus:async function(e){return b("/api/user/api-keys",null,e)},byokProviders:async function(e){return b("/api/v1/byok/providers",null,e)},catalog:async function(e,t,n){const r=(e||"models").replace(/^\/+/,""),o=new URLSearchParams;for(const[e,n]of Object.entries(t||{}))null!=n&&""!==n&&o.set(e,String(n));const s=o.toString();return b(`/api/v1/catalog/${r}${s?`?${s}`:""}`,n&&n.etag?{...D(),"If-None-Match":n.etag}:D(),n)},byokSet:async function(e,t){return w("/api/user/api-keys",{provider:e,api_key:t||""})},getMemoryToken:k,memorySearch:async function(e,t){return w("/api/memory/search",{query:e||"",limit:t||5},x(await k()))},memorySave:async function(e){return w("/api/memory/save",{entry:e},x(await k()))},memoryList:async function(e){return w("/api/memory/search",{query:"",limit:e||10},x(await k()))},verifyToken:async function(e){return w("/api/verify-token",{token:e||""},{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`})},memoryActivate:async function(e){return w("/api/memory/activate",{},x(e||await k()))},memoryPull:async function(e){return w("/api/memory/pull",{since:e||0},x(await k()))},memorySaveBatch:async function(e){return w("/api/memory/save",{entries:e||[]},x(await k()))},conversationSyncPush:async function(e){const t=await k();return w("/api/conversations/sync",{session_id:e&&e.session_id,title:e&&e.title||"",messages:e&&e.messages||[],source:e&&e.source||"aegis-desktop"},x(t))},conversationSyncPull:async function(){return w("/api/conversations/sync",{},x(await k()))},importConversation:async function({messages:e,url:t,title:n,source:r}={}){return w("/api/import",{messages:e||[],url:t||"",title:n||"",source:r||"aegiscode-plugin"})},driveToken:async function(){try{return await b("/api/drive/token")}catch(e){if(e&&404===e.status)return{connected:!1,access_token:null,email:null};throw e}},randomUUID:randomUUID}}const SSE_IDLE_TIMEOUT_MS=6e4,BRAIN_IDLE_TIMEOUT_MS=9e5;function idleBudgetFor(e,t){const n=Number(t),r=envIdleMs("AEGIS_SSE_IDLE_TIMEOUT_MS"),o=n>0?n:r>0?r:SSE_IDLE_TIMEOUT_MS;let s="";try{const t=e&&e.headers&&"function"==typeof e.headers.get?e.headers.get.bind(e.headers):null;s=t&&t("X-AEGIS-Brain")||""}catch{s=""}const a=envIdleMs("AEGIS_BRAIN_IDLE_TIMEOUT_MS")||BRAIN_IDLE_TIMEOUT_MS;return s&&String(s).trim()?Math.max(o,a):o}function isVersionGateError(e){return!(!e||"version_mismatch"!==e.code)}const api={createClient:createClient,envVar:envVar,randomUUID:randomUUID,DEFAULT_API_BASE:DEFAULT_API_BASE,CLIENT_VERSION:"3.2.0",isVersionGateError:isVersionGateError,idleBudgetFor:idleBudgetFor,SSE_IDLE_TIMEOUT_MS:SSE_IDLE_TIMEOUT_MS,BRAIN_IDLE_TIMEOUT_MS:BRAIN_IDLE_TIMEOUT_MS};"undefined"!=typeof module&&module.exports&&(module.exports=api),"undefined"!=typeof window&&(window.AegisClient=api);
|
package/vendor/client/attest.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
const
|
|
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};
|
|
@@ -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("fs"),path=require("path"),credentials=require("./credentials.js"),CATALOG_FILE="catalog.json",STALE_AFTER_MS=864e5;function catalogDir(e){return e&&e.dir||credentials.aegisHome(e&&e.env)}function catalogPath(e){return path.join(catalogDir(e),CATALOG_FILE)}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map((e=>"string"==typeof e?e:e&&e.id)).map((e=>"string"==typeof e?e.trim():"")).filter(Boolean)}function providerArray(e){return Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null}function indexCatalog(e){const t=Object.create(null),r=Array.isArray(e&&e.models)?e.models:[];for(const e of r){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.provider_id?e.provider_id.trim():"",o="string"==typeof e.model_id?e.model_id.trim():"";r&&o&&"active"===("string"==typeof e.status?e.status.toLowerCase():"active")&&(t[r]||(t[r]=[])).push(o)}return t}function read(e){const t=catalogPath(e);let r,o;try{r=fs.readFileSync(t,"utf8")}catch(e){return null}try{o=JSON.parse(r)}catch(e){return null}if(!o||"object"!=typeof o||!Array.isArray(o.providers))return null;let n=null;const a=o.snapshot&&(o.snapshot.fetched_at||o.snapshot.fetchedAt);if("string"==typeof a&&a){const e=Date.parse(a);Number.isNaN(e)||(n=e)}if(null===n)try{n=fs.statSync(t).mtimeMs}catch(e){n=null}const s=null===n?null:Math.max(0,Date.now()-n);let i=null;const l=o.snapshot&&o.snapshot.revalidated_at;if("string"==typeof l&&l){const e=Date.parse(l);Number.isNaN(e)||(i=e)}const d=null!==i&&(null===n||i>n)?i:n;return{data:o,fetchedAt:n,revalidatedAt:i,ageMs:s,stale:null===d||Date.now()-d>STALE_AFTER_MS,path:t}}function write(e,t){const r=catalogPath(t);fs.mkdirSync(path.dirname(r),{recursive:!0});const o=`${r}.${process.pid}.tmp`;return fs.writeFileSync(o,JSON.stringify(e),"utf8"),fs.renameSync(o,r),r}function withCatalog(e,t,r){const o=providerArray(e);if(!o)return[];let n=t;if(void 0===n){const e=read(r);n=e?e.data:null}const a=indexCatalog(n);if(!Object.keys(a).length)return o.slice();const s=[];for(const e of o){if(!e||"object"!=typeof e)continue;const t="string"==typeof e.id?e.id.trim():"",r=t?a[t]:null;if(!r||!r.length){s.push(e);continue}const o=new Set(modelIdsOf(e)),n=r.filter((e=>!o.has(e)));if(!n.length){s.push(e);continue}const i=Array.isArray(e.models)?e.models:[];s.push({...e,models:[...i,...n]})}return s}function addedModelsFor(e,t,r,o){const n="string"==typeof e?e.trim():"";if(!n)return[];let a=r;if(void 0===a){const e=read(o);a=e?e.data:null}const s=indexCatalog(a)[n]||[],i=(providerArray(t)||[]).find((e=>e&&"string"==typeof e.id&&e.id.trim()===n)),l=new Set(modelIdsOf(i));return s.filter((e=>!l.has(e)))}const MAX_PAGES=200;async function refresh(e,t){const r=t||{},o=r.limit||500,n=r.maxPages||200,a=read(r),s=a&&a.data||null,i=[];let l=null,d=0,c=r.etag||null,u=null,f=!1;try{for(;;){const t=await e({cursor:l,limit:o,etag:c});if(!t||t.notModified){f=!0;break}0===d&&t.etag&&(u=t.etag);const r=Array.isArray(t.models)?t.models:[];for(const e of r)e&&"object"==typeof e&&i.push(e);if(d+=1,!t.has_more||!t.next_cursor)break;if(d>=n)return _refreshResult({ok:!1,changed:!1,pages:d,models:i.length,providers:0,staleKept:Boolean(s),reason:`stopped after ${d} pages; cache left untouched`});l=t.next_cursor,c=null}}catch(e){return _refreshResult({ok:!1,changed:!1,pages:d,models:0,providers:0,staleKept:Boolean(s),reason:e&&e.message||String(e)})}if(f){let e=null;if(s)try{const t="function"==typeof r.now?r.now():Date.now();e=write({...s,snapshot:{...s.snapshot||{},revalidated_at:new Date(t).toISOString(),...u?{etag:u}:{}}},r)}catch{e=null}return _refreshResult({ok:!0,changed:!1,pages:0,models:0,providers:0,staleKept:!e,written:e,reason:"not-modified"})}if(!i.length)return _refreshResult({ok:!1,changed:!1,pages:d,models:0,providers:0,staleKept:Boolean(s),reason:"empty catalog; cache left untouched"});const p=s&&Array.isArray(s.providers)?s.providers:[],h="function"==typeof r.now?r.now():Date.now(),g={schema_version:s&&s.schema_version||1,providers:p,models:i,snapshot:{fetched_at:new Date(h).toISOString(),models_seen:i.length,providers_seen:p.length,source:"catalog-api",...u?{etag:u}:{}}};let m=null;try{m=write(g,r)}catch(e){return _refreshResult({ok:!1,changed:!1,pages:d,models:i.length,providers:p.length,staleKept:Boolean(s),reason:e&&e.message||String(e)})}return _refreshResult({ok:!0,changed:!0,pages:d,models:i.length,providers:p.length,staleKept:!1,written:m})}function _refreshResult(e){return{ok:Boolean(e.ok),changed:Boolean(e.changed),written:e.written||null,pages:e.pages||0,models:e.models||0,providers:e.providers||0,staleKept:Boolean(e.staleKept),...e.reason?{reason:e.reason}:{}}}module.exports={CATALOG_FILE:CATALOG_FILE,STALE_AFTER_MS:STALE_AFTER_MS,MAX_PAGES:200,catalogDir:catalogDir,catalogPath:catalogPath,indexCatalog:indexCatalog,read:read,write:write,refresh:refresh,withCatalog:withCatalog,addedModelsFor:addedModelsFor};
|
|
3
|
+
"use strict";const fs=require("fs"),path=require("path"),credentials=require("./credentials.js"),CATALOG_FILE="catalog.json",STALE_AFTER_MS=864e5;function catalogDir(e){return e&&e.dir||credentials.aegisHome(e&&e.env)}function catalogPath(e){return path.join(catalogDir(e),CATALOG_FILE)}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map((e=>"string"==typeof e?e:e&&e.id)).map((e=>"string"==typeof e?e.trim():"")).filter(Boolean)}function providerArray(e){return Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null}function indexCatalog(e){const t=Object.create(null),r=Array.isArray(e&&e.models)?e.models:[];for(const e of r){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.provider_id?e.provider_id.trim():"",o="string"==typeof e.model_id?e.model_id.trim():"";r&&o&&("active"===("string"==typeof e.status?e.status.toLowerCase():"active")&&(t[r]||(t[r]=[])).push(o))}return t}function read(e){const t=catalogPath(e);let r,o;try{r=fs.readFileSync(t,"utf8")}catch(e){return null}try{o=JSON.parse(r)}catch(e){return null}if(!o||"object"!=typeof o||!Array.isArray(o.providers))return null;let n=null;const a=o.snapshot&&(o.snapshot.fetched_at||o.snapshot.fetchedAt);if("string"==typeof a&&a){const e=Date.parse(a);Number.isNaN(e)||(n=e)}if(null===n)try{n=fs.statSync(t).mtimeMs}catch(e){n=null}const s=null===n?null:Math.max(0,Date.now()-n);let i=null;const l=o.snapshot&&o.snapshot.revalidated_at;if("string"==typeof l&&l){const e=Date.parse(l);Number.isNaN(e)||(i=e)}const d=null!==i&&(null===n||i>n)?i:n;return{data:o,fetchedAt:n,revalidatedAt:i,ageMs:s,stale:null===d||Date.now()-d>STALE_AFTER_MS,path:t}}function write(e,t){const r=catalogPath(t);fs.mkdirSync(path.dirname(r),{recursive:!0});const o=`${r}.${process.pid}.tmp`;return fs.writeFileSync(o,JSON.stringify(e),"utf8"),fs.renameSync(o,r),r}function withCatalog(e,t,r){const o=providerArray(e);if(!o)return[];let n=t;if(void 0===n){const e=read(r);n=e?e.data:null}const a=indexCatalog(n);if(!Object.keys(a).length)return o.slice();const s=[];for(const e of o){if(!e||"object"!=typeof e)continue;const t="string"==typeof e.id?e.id.trim():"",r=t?a[t]:null;if(!r||!r.length){s.push(e);continue}const o=new Set(modelIdsOf(e)),n=r.filter((e=>!o.has(e)));if(!n.length){s.push(e);continue}const i=Array.isArray(e.models)?e.models:[];s.push({...e,models:[...i,...n]})}return s}function addedModelsFor(e,t,r,o){const n="string"==typeof e?e.trim():"";if(!n)return[];let a=r;if(void 0===a){const e=read(o);a=e?e.data:null}const s=indexCatalog(a)[n]||[],i=(providerArray(t)||[]).find((e=>e&&"string"==typeof e.id&&e.id.trim()===n)),l=new Set(modelIdsOf(i));return s.filter((e=>!l.has(e)))}const MAX_PAGES=200;async function refresh(e,t){const r=t||{},o=r.limit||500,n=r.maxPages||200,a=read(r),s=a&&a.data||null,i=[];let l=null,d=0,c=r.etag||null,u=null,f=!1;try{for(;;){const t=await e({cursor:l,limit:o,etag:c});if(!t||t.notModified){f=!0;break}0===d&&t.etag&&(u=t.etag);const r=Array.isArray(t.models)?t.models:[];for(const e of r)e&&"object"==typeof e&&i.push(e);if(d+=1,!t.has_more||!t.next_cursor)break;if(d>=n)return _refreshResult({ok:!1,changed:!1,pages:d,models:i.length,providers:0,staleKept:Boolean(s),reason:`stopped after ${d} pages; cache left untouched`});l=t.next_cursor,c=null}}catch(e){return _refreshResult({ok:!1,changed:!1,pages:d,models:0,providers:0,staleKept:Boolean(s),reason:e&&e.message||String(e)})}if(f){let e=null;if(s)try{const t="function"==typeof r.now?r.now():Date.now();e=write({...s,snapshot:{...s.snapshot||{},revalidated_at:new Date(t).toISOString(),...u?{etag:u}:{}}},r)}catch{e=null}return _refreshResult({ok:!0,changed:!1,pages:0,models:0,providers:0,staleKept:!e,written:e,reason:"not-modified"})}if(!i.length)return _refreshResult({ok:!1,changed:!1,pages:d,models:0,providers:0,staleKept:Boolean(s),reason:"empty catalog; cache left untouched"});const p=s&&Array.isArray(s.providers)?s.providers:[],h="function"==typeof r.now?r.now():Date.now(),g={schema_version:s&&s.schema_version||1,providers:p,models:i,snapshot:{fetched_at:new Date(h).toISOString(),models_seen:i.length,providers_seen:p.length,source:"catalog-api",...u?{etag:u}:{}}};let m=null;try{m=write(g,r)}catch(e){return _refreshResult({ok:!1,changed:!1,pages:d,models:i.length,providers:p.length,staleKept:Boolean(s),reason:e&&e.message||String(e)})}return _refreshResult({ok:!0,changed:!0,pages:d,models:i.length,providers:p.length,staleKept:!1,written:m})}function _refreshResult(e){return{ok:Boolean(e.ok),changed:Boolean(e.changed),written:e.written||null,pages:e.pages||0,models:e.models||0,providers:e.providers||0,staleKept:Boolean(e.staleKept),...e.reason?{reason:e.reason}:{}}}module.exports={CATALOG_FILE:CATALOG_FILE,STALE_AFTER_MS:STALE_AFTER_MS,MAX_PAGES:200,catalogDir:catalogDir,catalogPath:catalogPath,indexCatalog:indexCatalog,read:read,write:write,refresh:refresh,withCatalog:withCatalog,addedModelsFor:addedModelsFor};
|