aegiscode 7.0.31 → 7.0.32
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/LICENSING.md +186 -0
- package/package.json +4 -2
- package/src/app.js +1 -1
- package/src/chatflow.js +1 -1
- package/src/commands.js +3 -1
- package/src/config.js +1 -1
- package/src/engine.js +1 -1
- package/src/history.js +1 -1
- package/src/models.js +1 -1
- package/src/overlays.js +1 -1
- package/src/panels.js +1 -1
- package/vendor/client/brain-catalog.js +1 -1
- package/vendor/client/byok-catalog.js +1 -1
- package/vendor/client/credits.js +45 -0
- package/vendor/client/foreign-sessions.js +3 -0
- package/vendor/client/naming.js +1 -1
- package/vendor/client/prefs.js +1 -1
- package/vendor/client/session-search.js +3 -0
- package/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/lib/local/integrity.js +42 -2
- package/vendor/desktop/lib/local/perm-rules.js +206 -0
- package/vendor/desktop/lib/local/perm-store.js +298 -0
- package/vendor/desktop/lib/local/perm-write.js +199 -0
- package/vendor/desktop/lib/local/pro-sessions.js +3 -0
- package/vendor/desktop/lib/local/sandbox-appcontainer.js +242 -0
- package/vendor/desktop/lib/local/sandbox-bwrap.js +316 -0
- package/vendor/desktop/lib/local/sandbox-seatbelt.js +380 -0
- package/vendor/desktop/lib/local/sandbox.js +493 -0
- package/vendor/desktop/lib/local/shell.js +155 -20
- package/vendor/desktop/lib/local/tools.js +29 -4
- package/vendor/desktop/lib/settings.js +1 -1
- package/vendor/desktop/main.js +774 -37
- package/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/mcp/admission.js +3 -0
- package/vendor/mcp/server.js +1 -1
- package/vendor/one/src/child.js +1 -1
- package/vendor/one/src/permissions.js +1 -1
package/src/history.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{ensurePrivateDir:ensurePrivateDir,writePrivateFile:writePrivateFile}=require("./securefs.js"),{sessionStore:sessionStore}=require("./shared.js"),{cwdName:cwdName}=require("./format.js"),{estimateTokens:estimateTokens}=require("./tokens.js"),HISTORY_LIMIT=500,SOURCE="aegiscode-cli";function historyPath(){return path.join(aegisDir(),"history.jsonl")}function ensureHistoryDir(){ensurePrivateDir(path.dirname(historyPath()))}function appendHistory({sessionId:e,prompt:t,reply:s,status:r,usage:i,title:n,model:o,provider:a}){try{const c={ts:(new Date).toISOString(),sessionId:e,cwd:process.cwd(),prompt:t,reply:s,status:r,tokens:i?{input:i.input||0,output:i.output||0,cacheRead:i.cacheRead||0,cacheWrite:i.cacheWrite||0,real:!0}:{input:estimateTokens(t),output:estimateTokens(s||""),real:!1}};i&&"number"==typeof i.costUsd&&(c.costUsd=i.costUsd);const d=String(n||"").trim();d&&(c.title=d);const u="string"==typeof o?o.trim():"";u&&(c.model=u);const l="string"==typeof a?a.trim():"";return l&&(c.provider=l),appendHistoryEntries([c])}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[history] write failed:",e),0}}function appendHistoryEntries(e){const t=(Array.isArray(e)?e:[]).filter(Boolean);if(!t.length)return 0;try{ensureHistoryDir();const e=historyPath(),s=[...fs.existsSync(e)?fs.readFileSync(e,"utf8").split("\n").filter(Boolean):[],...t.map((e=>JSON.stringify(e)))],r=s.slice(Math.max(0,s.length-HISTORY_LIMIT));return writePrivateFile(e,r.join("\n")+"\n"),mirrorToSharedStore(t),t.length}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[history] write failed:",e),0}}function mirrorToSharedStore(e){for(const t of e)try{sessionStore.recordExchange(aegisDir(),{sessionId:t.sessionId,prompt:t.prompt,reply:t.reply,status:t.status,cwd:t.cwd,ts:t.ts,tokens:t.tokens,costUsd:t.costUsd,model:t.model,provider:t.provider,origin:SOURCE})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[history] mirror failed:",e)}}function readEntries(){try{return fs.readFileSync(historyPath(),"utf8").split("\n").map((e=>e.trim())).filter(Boolean).map((e=>{try{return JSON.parse(e)}catch{return null}})).filter(Boolean)}catch{return[]}}function readHistoryEntries(){return readEntries()}function readOwnSessions(e=8){const t=readEntries(),s=new Map;for(const e of t){const t=s.get(e.sessionId);t?(!t.title&&e.title||!t.title==!e.title&&String(e.ts)>String(t.ts))&&s.set(e.sessionId,e):s.set(e.sessionId,e)}return[...s.values()].sort(((e,t)=>e.ts<t.ts?1:-1)).slice(0,e).map((e=>({id:e.sessionId,cwd:cwdName(e.cwd),summary:(e.title||e.prompt||"").slice(0,60),time:e.ts,own:!0})))}function readSessionTranscript(e){const t=readEntries().filter((t=>t.sessionId===e)).flatMap((e=>[{role:"user",text:e.prompt},{role:"assistant",text:e.reply||"(no response)"}]));if(t.length)return t;try{return sessionStore.readTranscript(aegisDir(),e)}catch{return[]}}function readSharedStoreSessions(e=8){try{return sessionStore.listSummaries(aegisDir(),e)}catch{return[]}}function sessionHistoryEntries(e){return readEntries().filter((t=>t.sessionId===e))}function setSessionTitle(e,t){const s=String(t||"").trim();if(!s)return 0;try{sessionStore.setTitle(aegisDir(),e,s)}catch{}try{const t=historyPath();if(!fs.existsSync(t))return 0;let r=0;const i=fs.readFileSync(t,"utf8").split("\n").map((e=>e.trim())).filter(Boolean).map((t=>{try{const i=JSON.parse(t);return i.sessionId!==e||i.title===s?t:(i.title=s,r++,JSON.stringify(i))}catch{return t}}));return r?(writePrivateFile(t,i.join("\n")+"\n"),r):0}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[history] title write failed:",e),0}}function readSessionTitle(e){const t=readEntries().find((t=>t.sessionId===e&&t.title));return t?String(t.title):""}function pruneSessionHistory(e){try{const t=historyPath();if(!fs.existsSync(t))return;const s=fs.readFileSync(t,"utf8").split("\n").map((e=>e.trim())).filter(Boolean).filter((t=>{try{return JSON.parse(t).sessionId!==e}catch{return!0}}));writePrivateFile(t,s.length?s.join("\n")+"\n":"")}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[history] prune failed:",e)}}function aggregateSessionUsage(e){const t=sessionHistoryEntries(e),s={input:0,output:0,cacheRead:0,cacheWrite:0};let r=t.length>0,i=0;for(const e of t){const t=e.tokens||{};t.real||(r=!1),s.input+=t.input||0,s.output+=t.output||0,s.cacheRead+=t.cacheRead||0,s.cacheWrite+=t.cacheWrite||0,"number"==typeof e.costUsd&&(i+=e.costUsd)}return{entries:t.length,usage:s,real:r,costUsd:i}}function readResumeList(e=8,t=5,s=8){const r=readOwnSessions(t),i=new Set(r.map((e=>e.id))),n=readSharedStoreSessions(t).filter((e=>!i.has(e.id)&&(i.add(e.id),!0))),o=[],a=`${os.homedir()}/.claude/history.jsonl`;try{const e=fs.readFileSync(a,"utf8").trim().split("\n").reverse().slice(0,s);for(const t of e)try{const e=JSON.parse(t),s=e.extra&&JSON.parse(e.extra);if(s&&s.sessionId&&!i.has(s.sessionId)){i.add(s.sessionId);const t=cwdName(e.cwd),r=(e.summary||"").slice(0,60);o.push({id:s.sessionId,cwd:t,summary:r,time:e.timestamp,own:!1})}}catch{}}catch{}return[...r,...n,...o].sort(((e,t)=>String(e.time||"")<String(t.time||"")?1:-1)).slice(0,e)}module.exports={HISTORY_LIMIT:HISTORY_LIMIT,SOURCE:SOURCE,historyPath:historyPath,ensureHistoryDir:ensureHistoryDir,appendHistory:appendHistory,appendHistoryEntries:appendHistoryEntries,readHistoryEntries:readHistoryEntries,readOwnSessions:readOwnSessions,readSessionTranscript:readSessionTranscript,readSharedStoreSessions:readSharedStoreSessions,sessionHistoryEntries:sessionHistoryEntries,pruneSessionHistory:pruneSessionHistory,aggregateSessionUsage:aggregateSessionUsage,readResumeList:readResumeList,setSessionTitle:setSessionTitle,readSessionTitle:readSessionTitle};
|
|
3
|
+
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{ensurePrivateDir:ensurePrivateDir,writePrivateFile:writePrivateFile}=require("./securefs.js"),{sessionStore:sessionStore}=require("./shared.js"),{cwdName:cwdName}=require("./format.js"),{estimateTokens:estimateTokens}=require("./tokens.js"),HISTORY_LIMIT=500,SOURCE="aegiscode-cli";function historyPath(){return path.join(aegisDir(),"history.jsonl")}function ensureHistoryDir(){ensurePrivateDir(path.dirname(historyPath()))}function appendHistory({sessionId:e,prompt:t,reply:s,status:r,usage:i,title:n,model:o,provider:a}){try{const c={ts:(new Date).toISOString(),sessionId:e,cwd:process.cwd(),prompt:t,reply:s,status:r,tokens:i?{input:i.input||0,output:i.output||0,cacheRead:i.cacheRead||0,cacheWrite:i.cacheWrite||0,real:!0}:{input:estimateTokens(t),output:estimateTokens(s||""),real:!1}};i&&"number"==typeof i.costUsd&&(c.costUsd=i.costUsd);const d=String(n||"").trim();d&&(c.title=d);const u="string"==typeof o?o.trim():"";u&&(c.model=u);const l="string"==typeof a?a.trim():"";return l&&(c.provider=l),appendHistoryEntries([c])}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[history] write failed:",e),0}}function appendHistoryEntries(e){const t=(Array.isArray(e)?e:[]).filter(Boolean);if(!t.length)return 0;try{ensureHistoryDir();const e=historyPath(),s=[...fs.existsSync(e)?fs.readFileSync(e,"utf8").split("\n").filter(Boolean):[],...t.map((e=>JSON.stringify(e)))],r=s.slice(Math.max(0,s.length-HISTORY_LIMIT));return writePrivateFile(e,r.join("\n")+"\n"),mirrorToSharedStore(t),t.length}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[history] write failed:",e),0}}function mirrorToSharedStore(e){for(const t of e)try{sessionStore.recordExchange(aegisDir(),{sessionId:t.sessionId,prompt:t.prompt,reply:t.reply,status:t.status,cwd:t.cwd,ts:t.ts,tokens:t.tokens,costUsd:t.costUsd,model:t.model,provider:t.provider,origin:SOURCE})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[history] mirror failed:",e)}}function readEntries(){try{return fs.readFileSync(historyPath(),"utf8").split("\n").map((e=>e.trim())).filter(Boolean).map((e=>{try{return JSON.parse(e)}catch{return null}})).filter(Boolean)}catch{return[]}}function readHistoryEntries(){return readEntries()}function readOwnSessions(e=8){const t=readEntries(),s=new Map;for(const e of t){const t=s.get(e.sessionId);t?(!t.title&&e.title||!t.title==!e.title&&String(e.ts)>String(t.ts))&&s.set(e.sessionId,e):s.set(e.sessionId,e)}return[...s.values()].sort(((e,t)=>e.ts<t.ts?1:-1)).slice(0,e).map((e=>({id:e.sessionId,cwd:cwdName(e.cwd),summary:(e.title||e.prompt||"").slice(0,60),time:e.ts,own:!0})))}function readSessionTranscript(e){const t=readEntries().filter((t=>t.sessionId===e)).flatMap((e=>[{role:"user",text:e.prompt},{role:"assistant",text:e.reply||"(no response)"}]));if(t.length)return t;try{return sessionStore.readTranscript(aegisDir(),e)}catch{return[]}}function readSharedStoreSessions(e=8){try{return sessionStore.listSummaries(aegisDir(),e)}catch{return[]}}function sessionHistoryEntries(e){return readEntries().filter((t=>t.sessionId===e))}function setSessionTitle(e,t){const s=String(t||"").trim();if(!s)return 0;try{sessionStore.setTitle(aegisDir(),e,s,{named:!0})}catch{}try{const t=historyPath();if(!fs.existsSync(t))return 0;let r=0;const i=fs.readFileSync(t,"utf8").split("\n").map((e=>e.trim())).filter(Boolean).map((t=>{try{const i=JSON.parse(t);return i.sessionId!==e||i.title===s?t:(i.title=s,r++,JSON.stringify(i))}catch{return t}}));return r?(writePrivateFile(t,i.join("\n")+"\n"),r):0}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[history] title write failed:",e),0}}function readSessionTitle(e){const t=readEntries().find((t=>t.sessionId===e&&t.title));return t?String(t.title):""}function pruneSessionHistory(e){try{const t=historyPath();if(!fs.existsSync(t))return;const s=fs.readFileSync(t,"utf8").split("\n").map((e=>e.trim())).filter(Boolean).filter((t=>{try{return JSON.parse(t).sessionId!==e}catch{return!0}}));writePrivateFile(t,s.length?s.join("\n")+"\n":"")}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[history] prune failed:",e)}}function aggregateSessionUsage(e){const t=sessionHistoryEntries(e),s={input:0,output:0,cacheRead:0,cacheWrite:0};let r=t.length>0,i=0;for(const e of t){const t=e.tokens||{};t.real||(r=!1),s.input+=t.input||0,s.output+=t.output||0,s.cacheRead+=t.cacheRead||0,s.cacheWrite+=t.cacheWrite||0,"number"==typeof e.costUsd&&(i+=e.costUsd)}return{entries:t.length,usage:s,real:r,costUsd:i}}function readResumeList(e=8,t=5,s=8){const r=readOwnSessions(t),i=new Set(r.map((e=>e.id))),n=readSharedStoreSessions(t).filter((e=>!i.has(e.id)&&(i.add(e.id),!0))),o=[],a=`${os.homedir()}/.claude/history.jsonl`;try{const e=fs.readFileSync(a,"utf8").trim().split("\n").reverse().slice(0,s);for(const t of e)try{const e=JSON.parse(t),s=e.extra&&JSON.parse(e.extra);if(s&&s.sessionId&&!i.has(s.sessionId)){i.add(s.sessionId);const t=cwdName(e.cwd),r=(e.summary||"").slice(0,60);o.push({id:s.sessionId,cwd:t,summary:r,time:e.timestamp,own:!1})}}catch{}}catch{}return[...r,...n,...o].sort(((e,t)=>String(e.time||"")<String(t.time||"")?1:-1)).slice(0,e)}module.exports={HISTORY_LIMIT:HISTORY_LIMIT,SOURCE:SOURCE,historyPath:historyPath,ensureHistoryDir:ensureHistoryDir,appendHistory:appendHistory,appendHistoryEntries:appendHistoryEntries,readHistoryEntries:readHistoryEntries,readOwnSessions:readOwnSessions,readSessionTranscript:readSessionTranscript,readSharedStoreSessions:readSharedStoreSessions,sessionHistoryEntries:sessionHistoryEntries,pruneSessionHistory:pruneSessionHistory,aggregateSessionUsage:aggregateSessionUsage,readResumeList:readResumeList,setSessionTitle:setSessionTitle,readSessionTitle:readSessionTitle};
|
package/src/models.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const path=require("node:path"),{resolveShared:resolveShared}=require("./sharedpaths.js"),{offerableCatalog:offerableCatalog}=require(resolveShared(path.join("client","brain-catalog.js"))),envFile=require(resolveShared(path.join("client","env-file.js"))),claudePro=require(resolveShared(path.join("desktop","lib","local","claude-pro.js")));function claudeProLoggedIn(){try{return!!claudePro.claudeProStatus({env:process.env}).loggedIn}catch{return!1}}const NO_PIN=null,ID_NOTES=Object.freeze({"openai-gpt4o-mini":"OpenAI gpt-4o-mini, pooled","anthropic-haiku":"Anthropic Haiku, pooled","nexus-brain":"pooled brain · multi-call fan-out, sized by /effort"});function normalizeModel(e){const o="string"==typeof e?{id:e}:e;if(!o||"object"!=typeof o)return null;const r="string"==typeof o.id?o.id.trim():"";if(!r)return null;const n="string"==typeof o.alias_of&&o.alias_of.trim()?o.alias_of.trim():null,i=Array.isArray(o.capabilities)?o.capabilities.filter((e=>"string"==typeof e&&e)):[],t={id:r,label:"string"==typeof o.label&&o.label.trim()||"string"==typeof o.name&&o.name.trim()||r,note:("string"==typeof o.note&&o.note.trim()?o.note.trim():"")||(n?`alias of ${n}`:ID_NOTES[r]||i.join(", ")),hidden:!0===o.hidden,aliasOf:n,capabilities:i};return"string"==typeof o.provider&&o.provider.trim()&&(t.provider=o.provider.trim()),!0===o.configured&&(t.configured=!0),"string"==typeof o.cls&&o.cls.trim()&&(t.cls=o.cls.trim()),t}function normalizeModelCatalog(e){const o=Array.isArray(e)?e:Array.isArray(e&&e.models)?e.models:[],r=[],n=new Set;for(const e of o){const o=normalizeModel(e);o&&!n.has(o.id)&&(n.add(o.id),r.push(o))}return r}function pickerEntries(e){const o=Array.isArray(e)?e.filter(Boolean):[],r=offerableCatalog(o).map(normalizeModel).filter(Boolean);if(r.length)return r;const n=o.filter((e=>!e.aliasOf));return n.length?n:o}function findModel(e,o){const r="string"==typeof o?o.trim():"";return r&&(Array.isArray(e)?e:[]).find((e=>e&&e.id===r))||null}function catalogIds(e){return new Set((Array.isArray(e)?e:[]).map((e=>String(e&&e.id||"").toLowerCase())).filter(Boolean))}function modelKeyPlan(e,o={}){const r=e&&e.id||"",n=envFile.keyForModelId(r,e&&e.cls);if(!n.env)return{needed:!1,env:"",provider:"",pooled:n.pooled,status:null,why:"this id has no key variable"};if(n.foreign){const e=!!envFile.resolveForeignSecret(n.env)||claudeProLoggedIn();return{needed:!e,env:n.env,provider:"",pooled:!1,status:{present:e,inFile:e,source:e?"file":"none"},why:e?`${n.env} is already set aside for Claude Code Pro`:`no ${n.env} is set aside for Claude Code Pro`}}const i=envFile.keyStatus(n.env);if(n.pooled){const e=!i.present&&!o.accountConfigured;return{needed:e,env:n.env,provider:"",pooled:!0,status:i,why:e?`no ${n.env} is set on this machine`:`account key present (${o.accountConfigured&&!i.present?"credentials.json":i.source})`}}const t=!i.inFile&&!o.hasStored;return{needed:t,env:n.env,provider:n.provider,pooled:!1,status:i,why:t?`no ${n.env} is stored for provider "${n.provider}"`:`${n.env} is already stored (${i.inFile?i.source:"provider store"})`}}function modelKeyQueue(e,o={}){const r=e&&e.id||"";if(!String(r).trim())return[];const n=envFile.keyForModelId(r,e&&e.cls);if(!n.env)return[];if(n.foreign)return envFile.resolveForeignSecret(n.env)||claudeProLoggedIn()?[]:[{env:n.env,provider:"",vendor:"",role:"claude-pro",needed:!0,status:{present:!1},why:`no ${n.env} is set aside for Claude Code Pro`}];const i=[],t=envFile.keyStatus(envFile.ACCOUNT_ENV_VAR);t.present||o.accountConfigured||i.push({env:envFile.ACCOUNT_ENV_VAR,provider:"",vendor:"",role:"account",needed:!0,status:t,why:`no ${envFile.ACCOUNT_ENV_VAR} is set on this machine`});const l=n.vendor||"",d=l?envFile.envVarFor(l):"",s=!(!l||"function"!=typeof o.hasStoredFor||!o.hasStoredFor(l));if(d){const e=envFile.keyStatus(d);e.inFile||s||i.push({env:d,provider:l,vendor:l,role:"provider",needed:!0,status:e,why:e.present?`${d} is exported in this shell only — the desktop cannot see it`:`no ${d} is stored for provider "${l}"`})}return i}function storeModelKey(e,o,r={}){const n=envFile.keyForModelId(e&&e.id,e&&e.cls),i=String(r.env||"").trim()||n.env;if(!i)return{ok:!1,file:"",changed:!1,error:`cannot name a key variable for "${e&&e.id||""}"`,env:"",provider:"",pooled:n.pooled};const t={...r};delete t.env;const l=n.foreign?envFile.setForeignSecret(i,o,t):envFile.setEnvValue(i,o,t),d=!n.foreign&&i===envFile.ACCOUNT_ENV_VAR;return{...l,env:i,provider:i===n.env?n.provider:"",pooled:d,foreign:!!n.foreign}}function keyVarForModel(e){return envFile.keyForModelId(e&&e.id,e&&e.cls).env}function providerForModel(e){const o=String(e&&e.id||"").trim();return o&&(envFile.keyForModelId(o,e&&e.cls).provider||envFile.providerForModelId(o,e&&e.cls))||""}module.exports={NO_PIN:null,ID_NOTES:ID_NOTES,normalizeModel:normalizeModel,normalizeModelCatalog:normalizeModelCatalog,pickerEntries:pickerEntries,findModel:findModel,catalogIds:catalogIds,modelKeyPlan:modelKeyPlan,modelKeyQueue:modelKeyQueue,storeModelKey:storeModelKey,keyVarForModel:keyVarForModel,providerForModel:providerForModel,claudeProLoggedIn:claudeProLoggedIn};
|
|
3
|
+
"use strict";const path=require("node:path"),{resolveShared:resolveShared}=require("./sharedpaths.js"),{offerableCatalog:offerableCatalog,NEXUS_BRAIN_IDS:NEXUS_BRAIN_IDS,AUTO_MODEL_ID:AUTO_MODEL_ID,AUTO_LABEL:AUTO_LABEL,AUTO_NOTE:AUTO_NOTE}=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 withAutoRow(e){const o=Array.isArray(e)?e:[];if(!o.length)return o;if(o.some((e=>e&&e.id===AUTO_MODEL_ID)))return o;const r={id:AUTO_MODEL_ID,label:AUTO_LABEL,note:AUTO_NOTE},n=o.findIndex((e=>e&&e.id===NEXUS_BRAIN_IDS[0])),i=n>=0?n+1:0;return[...o.slice(0,i),r,...o.slice(i)]}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,withAutoRow:withAutoRow,AUTO_MODEL_ID:AUTO_MODEL_ID,findModel:findModel,catalogIds:catalogIds,modelKeyPlan:modelKeyPlan,modelKeyQueue:modelKeyQueue,storeModelKey:storeModelKey,keyVarForModel:keyVarForModel,providerForModel:providerForModel,claudeProLoggedIn:claudeProLoggedIn};
|
package/src/overlays.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const{span:span,padLine:padLine}=require("./screen.js"),{C:C,BOLD:BOLD,BOLD_OFF:BOLD_OFF,GLYPH:GLYPH}=require("./theme.js");let fuzzy=null;try{fuzzy=require("./fuzzy.js")}catch{fuzzy=null}function rankCommands(e,
|
|
3
|
+
"use strict";const{span:span,padLine:padLine,w:w}=require("./screen.js"),{C:C,BOLD:BOLD,BOLD_OFF:BOLD_OFF,GLYPH:GLYPH}=require("./theme.js");let fuzzy=null;try{fuzzy=require("./fuzzy.js")}catch{fuzzy=null}function rankCommands(e,n){if(fuzzy&&"function"==typeof fuzzy.fuzzyRankWithAliases)return fuzzy.fuzzyRankWithAliases(e,n,(e=>e.name),(e=>e.aliases||[]));const a=String(e||"").toLowerCase();return a?n.filter((e=>`${e.name} ${(e.aliases||[]).join(" ")}`.toLowerCase().includes(a))):n}const descOf=e=>null!=e.help?e.help:null!=e.desc?e.desc:"",hintOf=e=>null!=e.hint?e.hint:null!=e.args?e.args:"";function fit(e,n){return e.map((e=>padLine(e,n)))}const blank=e=>[span(""," ".repeat(Math.max(0,e)))];function boldMatched(e,n,a){const s=fuzzy&&"function"==typeof fuzzy.fuzzyMatchPositions?fuzzy.fuzzyMatchPositions(e,n):[];if(!s||!s.length)return[span(a,n)];const t=[];let r=0;for(const e of s)e>r&&t.push(span(a,n.slice(r,e))),t.push(span(a+BOLD,n[e])),r=e+1;return r<n.length&&t.push(span(a,n.slice(r))),t}function renderPalette(e,n={},a=80,s=24){!Array.isArray(e)&&e&&"object"==typeof e&&(n=e,e=Array.isArray(e.commands)?e.commands:[]);const t=rankCommands(n.query||"",e||[]),r=Number.isInteger(n.sel)?n.sel:0,p=t.length,l=Math.max(1,Math.min(12,s-8)),o=Math.max(0,Math.min(r-Math.floor(l/2),Math.max(0,p-l))),u=t.slice(o,o+l),h=[];h.push(blank(a)),h.push([span(C.gray," "+"─".repeat(Math.max(10,a-4)))]);for(let e=0;e<u.length;e++){const a=u[e],s=o+e===r,t=s?span(C.lavender,GLYPH.cursor):span(""," "),p=s?C.blue:C.white,l=[span(p,"/"),...boldMatched(n.query||"",a.name,p)],i=" ".repeat(Math.max(1,22-[...a.name].length));h.push([span(""," "),t,span(""," "),...l,span(a.unavailable?C.dim:C.gray,i+descOf(a))]),s&&hintOf(a)&&h.push([span(""," "),span(C.gray,`${GLYPH.hook} Usage: /${a.name} ${hintOf(a)}`)])}for(;h.length<4+2*l;)h.push(blank(a));return h.push([span(C.gray," "+"─".repeat(Math.max(10,a-4)))]),h.push([span(C.gray,` type to filter ${GLYPH.bullet} shift+enter runs the top row ${GLYPH.bullet} enter runs ${GLYPH.bullet} esc closes`)]),fit(h,a)}const PICKER_HINT=`↑↓ or tab move ${GLYPH.bullet} enter pins ${GLYPH.bullet} shift+↑↓ pins at once ${GLYPH.bullet} esc cancels`;function renderModelPicker(e,n=0,a=80,s=24,t=null,r=null,p=null){const l=[],o="function"==typeof p&&r?p(r):null;l.push(blank(a)),l.push([span(""," "),span(C.white+BOLD,"Select model"),span(BOLD_OFF,""),...o?[span(C.gray,` — running on ${o}`)]:[]]),l.push([span(""," "),span(C.gray,"Switch between models. Your pick becomes the default for new sessions.")]),l.push([span(""," "),span(C.gray,"Nexus is pooled; any other row prompts for its provider key on pick.")]),l.push(blank(a));const u=Math.max(1,(s||24)-8),h=e.length,i=h>u?Math.min(Math.max(0,n-Math.floor(u/2)),h-u):0,c=Math.min(h,i+u);i>0&&l.push([span(""," "),span(C.gray,`↑ ${i} more above`)]);for(let a=i;a<c;a++){const s=e[a]||{},r=s.label||s.name||s.id||"",p=a===n,o=null!=t&&s.id===t,u=p?span(C.lavender,GLYPH.cursor):span(""," "),h=span(C.gray,`${a+1}.`),i=span(p?C.lavender:C.white,r),c=o?span(C.green," "+GLYPH.check):span("",""),d=" ".repeat(Math.max(1,22-[...r].length)),g="byok"!==s.cls||s.configured?"":"[key needed] ";l.push([span(""," "),u,span(""," "),h,span(""," "),i,c,span(C.gray,d+g+(s.note||s.model||""))])}return c<h&&l.push([span(""," "),span(C.gray,`↓ ${h-c} more below`)]),l.push(blank(a)),l.push([span(""," "),span(C.gray,PICKER_HINT)]),fit(l,a)}const EFFORT_LEVELS=[{label:"Low",note:"Fastest, cheapest budget"},{label:"Medium",note:"Balanced"},{label:"High",note:"Highest budget, slowest (default)"},{label:"Max",note:"Deepest reasoning where the model defines it; same budget as high"}],EFFORT_VALUES=EFFORT_LEVELS.map((e=>void 0===e.value?e.label.toLowerCase():e.value));function renderEffortPicker(e=0,n=80,a=null,s=EFFORT_LEVELS){const t=[];t.push(blank(n)),t.push([span(""," "),span(C.white+BOLD,"Select effort"),span(BOLD_OFF,"")]),t.push([span(""," "),span(C.gray,"Sets the token budget the pool sizes each turn from.")]),t.push(blank(n));for(let n=0;n<s.length;n++){const r=s[n],p=n===e,l=String(a||"high").toLowerCase()===String(r.label).toLowerCase(),o=p?span(C.lavender,GLYPH.cursor):span(""," "),u=span(p?C.lavender:C.white,r.label),h=l?span(C.green," "+GLYPH.check):span("",""),i=" ".repeat(Math.max(1,12-[...r.label].length));t.push([span(""," "),o,span(""," "),u,h,span(C.gray,i+r.note)])}return t.push(blank(n)),t.push([span(""," "),span(C.gray,PICKER_HINT)]),fit(t,n)}function renderClassPicker(e,n=0,a=80,s=null,t=null){const r=Array.isArray(e)?e:[],p=e=>("function"==typeof t?t(e):e)||e,l=[];l.push(blank(a)),l.push([span(""," "),span(C.white+BOLD,"Select class"),span(BOLD_OFF,"")]),l.push([span(""," "),span(C.gray,"Which route the next turn takes — who pays, and with which credential.")]),l.push(blank(a));for(let e=0;e<r.length;e++){const a=r[e]||{},t=a.class,o=e===n,u=null!=s&&t===s,h=o?span(C.lavender,GLYPH.cursor):span(""," "),i=p(t),c=span(o?C.lavender:C.white,i),d=u?span(C.green," "+GLYPH.check):span("",""),g=" ".repeat(Math.max(1,14-[...i].length)),f="byok"===t?a.configured?"your key, relayed by AEGIS — billed a handling fee":"needs a provider key: /byok-key <provider>":"the pool — your AEGIS account key pays for it";l.push([span(""," "),h,span(""," "),c,d,span(C.gray,g+f)])}return l.push(blank(a)),l.push([span(""," "),span(C.gray,PICKER_HINT)]),fit(l,a)}function renderResumeList(e,n=0,a=80,s=24,t=""){const r=Array.isArray(e)?e:[],p=String(null==t?"":t),l=[];l.push(blank(a)),l.push([span(""," "),span(C.gray,"─".repeat(Math.max(10,a-4)))]),l.push([span(""," "),span(C.white+BOLD,"Resume session"),span(C.gray,` (${r.length?n+1:0} of ${r.length})`),span(BOLD_OFF,"")]);const o=Math.max(10,a-4),u=p||"⌕ Search…",h=p?C.white:C.dim,i=Math.max(4,o-5),c=u.length>i?"…"+u.slice(u.length-(i-1)):u;l.push([span(""," "),span(C.gray,"╭"+"─".repeat(Math.max(0,o-2))+"╮")]),l.push([span(""," "),span(C.gray,"│"),span(h," "+c),span(p?C.lavender:""," "),span(""," ".repeat(Math.max(0,o-3-w(c)-(p?1:0)))),span(C.gray,"│")]),l.push([span(""," "),span(C.gray,"╰"+"─".repeat(Math.max(0,o-2))+"╯")]),l.push(blank(a));const d=Math.max(2,Math.min(6,s-16));r.length||l.push([span(""," "),span(C.gray,p?`no session matches “${p}”`:"No previous sessions found.")]);const g=Math.max(0,Math.min(n-Math.floor(d/2),Math.max(0,r.length-d))),f=r.slice(g,g+d);for(let e=0;e<f.length;e++){const a=f[e]||{},s=g+e===n,t=s?span(C.lavender,GLYPH.cursor):span(""," "),r=a.own?span(C.green,GLYPH.star+" "):span(C.gray,GLYPH.bullet+" "),p=span(s?C.white+BOLD:C.white,a.summary||"(untitled)");l.push([span(""," "),t,span(""," "),r,p]),l.push([span(""," "),span(C.gray,`${a.cwd||"~"} ${GLYPH.bullet} ${ago(a.time)}`)])}for(;l.length<6+2*d;)l.push(blank(a));return l.push([span(""," "),span(C.gray,"─".repeat(Math.max(10,a-4)))]),l.push([span(""," "),span(C.gray,`Ctrl+A all projects ${GLYPH.bullet} Space to preview ${GLYPH.bullet} Type to search ${GLYPH.bullet} Esc to cancel`)]),fit(l,a)}function ago(e){if(!e)return"";const n=Date.now()-new Date(String(e)).getTime();return n>=0&&!Number.isNaN(n)?n<6e4?`${Math.max(1,Math.round(n/1e3))}s ago`:n<36e5?`${Math.round(n/6e4)}m ago`:n<864e5?`${Math.round(n/36e5)}h ago`:`${Math.round(n/864e5)}d ago`:""}function renderProviderPicker(e,n=0,a=80,s=null,t=null){const r=Array.isArray(e)?e:[],p=[];p.push(blank(a)),p.push([span(""," "),span(C.white+BOLD,"Select provider"),span(BOLD_OFF,"")]),p.push([span(""," "),span(C.gray,"Which vendor the key you are about to paste belongs to.")]),p.push(blank(a));for(let e=0;e<r.length;e++){const a=r[e]||{},t=String(a.id||"");if(!t)continue;const l=e===n,o=null!=s&&t===s,u=l?span(C.lavender,GLYPH.cursor):span(""," "),h=span(l?C.lavender:C.white,t),i=o?span(C.green," "+GLYPH.check):span("",""),c=String(a.label||""),d=" ".repeat(Math.max(1,16-[...t].length)),g=a.configured?span(C.green,"set"+(a.masked?` (${a.masked})`:"")):span(C.gray,"not set");p.push([span(""," "),u,span(""," "),h,i,span(C.gray,d+(c?`${c} · `:"")),g])}return p.push(blank(a)),p.push([span(""," "),span(C.gray,t||`↑↓ or tab move ${GLYPH.bullet} enter picks ${GLYPH.bullet} esc cancels`)]),fit(p,a)}module.exports={boldMatched:boldMatched,renderPalette:renderPalette,renderModelPicker:renderModelPicker,renderEffortPicker:renderEffortPicker,renderClassPicker:renderClassPicker,renderProviderPicker:renderProviderPicker,renderResumeList:renderResumeList,EFFORT_LEVELS:EFFORT_LEVELS,EFFORT_VALUES:EFFORT_VALUES,PICKER_HINT:PICKER_HINT};
|
package/src/panels.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const{span:span,getSize:getSize,lineWidth:lineWidth}=require("./screen.js"),{themeOf:themeOf,BOLD:BOLD,BOLD_OFF:BOLD_OFF,GLYPH:GLYPH}=require("./theme.js"),{goUrl:goUrl}=require("./signup.js"),{cwdName:cwdName,pathName:pathName}=require("./format.js"),VERSION=require("../package.json").version;function num(s){const e=Number(s);return Number.isFinite(e)?e:0}function str(s){return null==s?"":String(s)}function wrapRows(s,e,n,a){const t=Math.max(20,(Number(a)||80)-2-e),o=" ".repeat(e),r=str(s).split(/\s+/).filter(Boolean),p=[];let i="";for(const s of r){const e=i?`${i} ${s}`:s;i&&e.length>t?(p.push([span("",o),span(n,i)]),i=s):i=e}return i&&p.push([span("",o),span(n,i)]),p.length?p:[[span("",o),span(n,"")]]}function tokenBuckets(s){const e=num(s.input),n=num(s.output),a=num(s.cacheRead),t=num(s.cacheWrite),o=e+a+t;return{input:e,output:n,cacheRead:a,cacheWrite:t,prompt:o,total:num(s.total)||o+n}}function fmtTokens(s){const e=Number(s);return!Number.isFinite(e)||e<=0?"0":Math.round(e).toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}function fmtEur(s){const e=Number(s);if(!Number.isFinite(e))return"€?";const n=Math.abs(e);return`€${n<.01?n.toFixed(4):n.toFixed(2)}`}function ago(s){if(!s)return"";const e=Date.now()-new Date(String(s)).getTime();return e>=0&&!Number.isNaN(e)?e<6e4?`${Math.max(1,Math.round(e/1e3))}s ago`:e<36e5?`${Math.round(e/6e4)}m ago`:e<864e5?`${Math.round(e/36e5)}h ago`:`${Math.round(e/864e5)}d ago`:""}function contextBar(s,e,n,a=50){const t=Math.max(0,Math.min(1,e>0?num(s)/e:0)),o=Math.round(t*a);return[span(""," "),span(n.green,"█".repeat(o)),span(n.dim,"█".repeat(Math.max(0,a-o))),span(n.gray,` ${Math.round(100*t)}% used`)]}function kv(s,e,{indent:n=" ",keyStyle:a=null,valStyle:t=null}={}){const o=e.reduce(((s,e)=>Math.max(s,[...e[0]].length)),0);return e.map((([e,r])=>[span(null!=a?a:s.gray,n+e+" ".repeat(o-[...e].length)+" : "),span(null!=t?t:s.white,str(r))]))}function obj(s){return s&&"object"==typeof s?s:{}}function statsFrom(s){const e=obj(s);return e.stats&&"object"==typeof e.stats?e.stats:e.memory&&"object"==typeof e.memory&&(null!=e.memory.total||e.memory.tiers||null!=e.memory.sessions||e.memory.roles)?e.memory:null!=e.total||e.tiers||e.roles?e:null}const CATEGORY_LABELS={session:"Session & context",workspace:"Workspace",model:"Model & behavior",data:"Data",auth:"Auth",support:"Support",fun:"Fun",aegis:"Aegis plugin",custom:"Custom"};function categoryLabel(s){if(s&&s.categoryLabel)return String(s.categoryLabel);const e=str(s&&s.category);return CATEGORY_LABELS[e]?CATEGORY_LABELS[e]:e?e.charAt(0).toUpperCase()+e.slice(1):"Commands"}function buildHelp(s,e={}){const n=themeOf(e),a=Array.isArray(s)?s:Array.isArray(obj(s).commands)?s.commands:[],t=[];t.push([span(n.gold+BOLD,"Commands"),span(BOLD_OFF,"")]),t.push([span(n.gray,"─".repeat(30))]);let o=null;for(const s of a){if(!s||!s.name)continue;const e=str(s.category);e!==o&&(t.push([span("","")]),t.push([span(n.gray+BOLD,categoryLabel(s)),span(BOLD_OFF,"")]),o=e);const a=String(s.name),r=" ".repeat(Math.max(1,16-[...a].length)),p=str(null!=s.desc?s.desc:s.help),i=s.unavailable?n.gray:n.white,u=s.unavailable?n.dim:n.gray,l=s.unavailable?" (unavailable)":"";t.push([span(i,"/"+a),span(u,r+p+l)])}return a.length||(t.push([span("","")]),t.push([span(n.gray,"No commands registered.")])),t.push([span("","")]),t.push([span(n.gray,"Shortcuts: "),span(n.white,"?"),span(n.gray," · "),span(n.white,"/help"),span(n.gray," commands · "),span(n.white,"↑↓"),span(n.gray," history · "),span(n.white,"Ctrl-L"),span(n.gray," clear · "),span(n.white,"Ctrl-D"),span(n.gray," exit")]),t}function buildStatus(s,e={}){const n=themeOf(e),a=obj(s),t=[];t.push([span(n.gold+BOLD,"Status"),span(BOLD_OFF,"")]);const o=[],r=(s,e)=>{const n=str(e);""!==n&&o.push([s,n])};r("Session ID",a.sessionId),r("Working directory",a.cwd),r("Home",a.home),r("Model",a.model),r("Effort",a.effort||"high"),null!=a.thinking&&r("Thinking",a.thinking?"on":"off"),null!=a.stream&&r("Streaming",!1===a.stream?"off":"on"),null!=a.vim&&r("Vim keymap",a.vim?"on":"off"),r("Theme",a.theme?str(a.theme):e&&e.light?"Light mode":"Dark mode"),r("Backend",a.backend),r("Base",a.base),r("Plan",a.plan),r("Account",a.account),null!=a.online&&r("Online",a.online?"yes":"no"),null!=a.turns&&r("Turns",str(num(a.turns))),null!=a.calls&&r("Tool calls",str(num(a.calls))),null!=a.version&&r("Version","v"+str(a.version)),r("Node",process.version),r("Platform",`${process.platform} ${process.arch}`);const p=Array.isArray(e.caps)?e.caps:[],i=s=>{const e=p.find((e=>Array.isArray(e)&&String(e[0])===s));return e?str(e[1]):""};r("Terminal",i("terminal")),r("Mark",i("mark")),r("Star",i("star")),r("Color",i("color")),r("Control",i("control")),r("Frame",i("size"));for(const s of kv(n,o,{keyStyle:n.gray,valStyle:n.white}))t.push(s);t.push([span("","")]);const u=a.permissions&&a.permissions.mode?str(a.permissions.mode):"default";return t.push([span(n.gray,`Permissions: ${u} — tool use follows your AEGIS settings.`)]),t}function buildCost(s,e={}){const n=themeOf(e),a=obj(s),{cols:t}=getSize(),o=Math.max(30,t-2),r=a.tokens&&"object"==typeof a.tokens?a.tokens:{},{input:p,output:i,cacheRead:u,cacheWrite:l,prompt:h,total:c}=tokenBuckets(r),d=num(a.costEur),m=str(a.model)||"the pinned model",g=num(a.contextWindow)||2e5,y=g>0?Math.min(100,Math.round(c/g*100)):0,f=[];return f.push([span(n.gray,"─".repeat(o))]),f.push([span(""," "),span(n.white+BOLD,"Session"),span(BOLD_OFF,""),span(n.gray," Status Config Usage Stats")]),f.push([span(""," "),span(n.gray,"Session")]),f.push([span(""," "),span(n.white,"Total cost:"),span(n.gray," "+" ".repeat(Math.max(0,14-fmtEur(d).length))+fmtEur(d))]),null!=a.balance&&f.push([span(""," "),span(n.white,"Balance:"),span(n.gray," "+" ".repeat(Math.max(0,14-fmtEur(a.balance).length))+fmtEur(a.balance))]),null==a.turns&&null==a.calls||f.push([span(""," "),span(n.white,"Turns:"),span(n.gray,` ${num(a.turns)} turns · ${num(a.calls)} calls`)]),f.push([span(""," "),span(n.white," Usage by model:")]),f.push([span(""," "),span(n.gray,` ${m}: ${fmtTokens(h)} input, ${fmtTokens(i)} output (${fmtEur(d)})`)]),(u||l)&&f.push([span(""," "),span(n.dim,` ↳ miss ${fmtTokens(p)} · cache read ${fmtTokens(u)} · cache write ${fmtTokens(l)}`)]),f.push([span(""," ")]),f.push([span(""," "),span(n.white+BOLD,"Current session"),span(BOLD_OFF,"")]),f.push(contextBar(c,g,n)),f.push([span(""," ")]),f.push([span(""," "),span(n.gray,`Session context: ${y}% of ${fmtTokens(g)} used.`)]),f.push([span(""," "),span(n.dim,"Cost is metered from the AEGIS token bank; tokens are counted this session.")]),f}function buildContext(s,e={}){const n=themeOf(e),a=obj(s),{cols:t}=getSize(),o=Math.max(30,t-2),r=a.tokens&&"object"==typeof a.tokens?a.tokens:{},{input:p,output:i,cacheRead:u,cacheWrite:l,prompt:h,total:c}=tokenBuckets(r),d=num(a.contextWindow)||2e5,m=[];m.push([span(n.gold+BOLD,"Context usage"),span(BOLD_OFF,"")]),m.push([span(""," "),span(n.gray,"─".repeat(Math.max(1,o-2)))]);const g=(s,e)=>[span(""," "),span(n.white,s),span(""," ".repeat(Math.max(1,16-[...s].length))),span(n.gray,fmtTokens(e)),span(""," ".repeat(Math.max(1,10-fmtTokens(e).length))),...contextBar(e,d,n)];return m.push(g("Prompt tokens",h)),(u||l)&&m.push([span(""," "),span(n.dim,` ↳ miss ${fmtTokens(p)} · cache read ${fmtTokens(u)} · cache write ${fmtTokens(l)}`)]),m.push(g("Output tokens",i)),m.push([span(""," ")]),m.push([span(""," "),span(n.gray,"─".repeat(Math.max(1,o-2)))]),m.push([span(""," "),span(n.white+BOLD,"Total"),span(""," ".repeat(9)),span(n.gray,fmtTokens(c)),span(""," ".repeat(Math.max(1,10-fmtTokens(c).length))),...contextBar(c,d,n)]),m.push([span(""," ")]),m.push([span(""," "),span(n.gray,`Context window: ${fmtTokens(d)} tokens`)]),m}function renderSessionsOverlay(s,e,n,a={}){const t=themeOf(a),o=obj(s),r=Math.max(30,num(e)?num(e)-4:76),p=str(o.version),i=str(o.model)||"default model",u=cwdName(o.cwd),l=Array.isArray(o.sessions)?o.sessions.filter(Boolean):[],h=l.filter((s=>s.awaiting||s.needsInput)).length,c=l.filter((s=>s.working)).length,d=l.filter((s=>s.completed)).length,m=s=>[span(t.gray,"│"),span(""," "),...s,span(""," ".repeat(Math.max(0,r-1-lineWidth(s)))),span(t.gray,"│")],g=[];return g.push([span(t.coral,"╭─── Aegiscode v"+p+" "+"─".repeat(Math.max(0,r-24))+"╮")]),g.push(m([span(t.white,i),span(t.gray," · "),span(t.white,u)])),g.push(m([span(t.gray,`${h} awaiting input · ${c} working · ${d} completed`)])),g.push([span(t.gray,"├"+"─".repeat(r)+"┤")]),g.push(m([span(t.white+BOLD,"Needs input"),span(BOLD_OFF,"")])),g.push(m([span(t.gray,"Sessions that have a question or need your decision land here")])),g.push(m([span(t.coral,GLYPH.bloom),span(t.gray," current session send a prompt to start "),span(t.gray,"—")])),g.push(m([span(t.white+BOLD,"Working"),span(BOLD_OFF,"")])),g.push(m([span(t.gray,"Sessions AEGIS is actively working on — they keep running even if you close the terminal")])),g.push(m([span(t.white+BOLD,"Completed"),span(BOLD_OFF,"")])),g.push(m([span(t.gray,"Finished sessions wait here for you to review")])),g.push([span(t.gray,"╰"+"─".repeat(r)+"╯")]),g.push([span(""," "),span(t.gray,"Sub-agents that keep working in the background need a local agent loop;")]),g.push([span(""," "),span(t.gray,"this build hands a bigger task to the pooled brain instead.")]),g}function buildAgents(s,e={}){const{cols:n,rows:a}=getSize();return renderSessionsOverlay(s,n,a,e)}function buildPermissions(s,e,n={}){const a=themeOf(n),t=obj(s),o=s=>Array.isArray(s)?s:[],r=null!=e&&""!==e?String(e):null!=t.defaultMode?String(t.defaultMode):"default",p=[];p.push([span(a.gold+BOLD,"Permissions"),span(BOLD_OFF,"")]),p.push([span(""," "),span(a.gray,"Default mode: "),span(a.white,r)]),p.push([span(""," ")]);const i=(s,e)=>{const n=[[span(""," "),span(a.white+BOLD,s),span(BOLD_OFF,"")]];e.length||n.push([span(""," "),span(a.gray,"(none)")]);for(const s of e)n.push([span(""," "),span(a.gray,str(s))]);return n};for(const s of i("Allow",o(t.allow)))p.push(s);for(const s of i("Deny",o(t.deny)))p.push(s);for(const s of i("Ask",o(t.ask)))p.push(s);return p.push([span("","")]),p.push([span(a.gray,"Usage:")]),p.push([span(a.gray,' /permissions allow "Bash(npm run *)"')]),p.push([span(a.gray,' /permissions deny "Edit(src/**)"')]),p.push([span(a.gray,' /permissions ask "Read(**/*.env)"')]),p.push([span(a.gray," /permissions default ask · /permissions clear")]),p.push([span("","")]),p.push([span(a.dim,`Stored in ${str(t._path)||"~/.aegiscode/permissions.json"}`)]),p}function buildModelList(s,e,n={}){const a=themeOf(n),t=Array.isArray(e)?e:[],o=str(s),r=s=>s.cls?"byok"===s.cls:"byok"===n.modelClass,p=t.some(r),i=[];i.push([span(a.gold+BOLD,"Models"),span(BOLD_OFF,"")]),i.push([span(a.gray,"─".repeat(30))]);for(const s of t){if(!s)continue;const e=str(s.id)||str(s.model),n=(""!==e&&e===o?"▶ ":" ")+e,t=str(s.name||s.label||s.model),p=r(s)?str(s.note)||str(s.model):str(s.model)||"(default)";i.push([span(a.white,n),span(""," ".repeat(Math.max(1,26-[...n].length))),span(a.gray,t),span(""," ".repeat(Math.max(1,22-[...t].length))),span(a.gray,p)])}return t.length||i.push([span(""," "),span(a.gray,"(no models configured)")]),i.push([span("","")]),i.push([span(a.gray,p?"Switch: /model <id> · Add a provider key: /byok-key <provider> · Run on it: /class byok":"Switch: /model <id> · Add: /model add <id> <name> <model> <baseURL> [apiKey] · Remove: /model remove <id>")]),i}function buildRewindList(s,e={}){const n=themeOf(e),a=Array.isArray(s)?s:[],t=[];t.push([span(n.gold+BOLD,"Rewind"),span(BOLD_OFF,"")]),t.push([span(""," "),span(n.gray,"Snapshots are taken after every exchange.")]),t.push([span(""," ")]);for(const s of a){if(!s)continue;const e=str(num(s.idx));t.push([span(""," "),span(n.green,e),span(""," ".repeat(Math.max(1,4-[...e].length))),span(n.white,`${num(s.depth)} messages`),span(n.gray,` · ${num(s.words)} words · ${ago(s.ts)}`)])}return a.length||t.push([span(""," "),span(n.gray,"(no checkpoints)")]),t.push([span("","")]),t.push([span(n.gray,"Usage: /rewind N to restore that checkpoint (0 = session start)")]),t}function buildHooksStatus(s,e={}){const n=themeOf(e),a=obj(s),t=Array.isArray(a.events)?a.events:[],o=a.byEvent&&"object"==typeof a.byEvent?a.byEvent:{},r=Array.isArray(a.fromPaths)?a.fromPaths:Array.isArray(a.sources)?a.sources:[],p=[];p.push([span(n.gold+BOLD,"Hooks status"),span(BOLD_OFF,"")]);const i=[["status",a.enabled?"enabled":"disabled"],["hooks",str(num(a.hooks))],["events",str(t.length)]];for(const s of kv(n,i,{keyStyle:n.gray,valStyle:n.white}))p.push(s);if(num(a.hooks)>0){p.push([span("","")]),p.push([span(""," "),span(n.white+BOLD,"by event"),span(BOLD_OFF,"")]);for(const[s,e]of Object.entries(o))p.push([span(""," "),span(n.green,GLYPH.bullet),span(n.white,` ${s}`),span(n.gray,` ${num(e)}`)])}return p.push([span("","")]),p.push([span(n.gray,"/hooks list for full config")]),p.push([span("","")]),p.push([span(n.dim,r.length?`Settings: ${r.join(", ")}`:"Settings: no settings.json with hooks found (checked ~/.aegis, .aegis, ~/.aegiscode, .aegiscode, ~/.claude)")]),p.push([span(n.gray,"Config hooks are read, not managed — edit the files above.")]),p.push([span(n.gray,"The repo guard hooks (.githooks/) are installed by /hooks install.")]),p}function buildHooksList(s,e={}){const n=themeOf(e),a=obj(s),t=a.hooks&&"object"==typeof a.hooks?a.hooks:{},o=[];o.push([span(n.gold+BOLD,"Hooks config"),span(BOLD_OFF,"")]);let r=!1;for(const[s,e]of Object.entries(t))if(Array.isArray(e)&&0!==e.length){r=!0,o.push([span("","")]),o.push([span(""," "),span(n.white+BOLD,s),span(BOLD_OFF,"")]);for(const s of e)s&&(o.push([span(""," "),span(n.lavender,str(s.name)||"(unnamed)")]),s.matcher&&(s.matcher.tools&&o.push([span(""," - tools: "),span(n.gray,str(s.matcher.tools))]),s.matcher.paths&&o.push([span(""," - paths: "),span(n.gray,str(s.matcher.paths))]),s.matcher.commands&&o.push([span(""," - commands: "),span(n.gray,str(s.matcher.commands))])),o.push([span("",` - hooks: ${Array.isArray(s.hooks)?s.hooks.length:0}`)]),o.push([span("","")]))}return r?(o.push([span("","")]),o.push([span(n.gray,"/hooks status for the summary")])):(o.push([span(""," "),span(n.gray,"no hooks configured.")]),o.push([span("","")]),o.push([span(""," "),span(n.gray,"add hooks to settings.json:")]),o.push([span(""," "),span(n.gray,"- ~/.aegis/settings.json (user)")]),o.push([span(""," "),span(n.gray,"- .aegis/settings.json (project)")])),o}function buildTroubleshooting(s,e={}){const n=themeOf(e),a=[];a.push([span(n.gold+BOLD,"Troubleshooting"),span(BOLD_OFF,"")]);const t=[["No output / blank screen","Run with TERM=xterm-256color, or switch to a lighter theme (/theme light)."],["Keys not responding","This client needs a real TTY — run it from a terminal, not a CI job."],["401 / unauthorized","Check the account line with /status, or set a provider key with /byok-set."],["No answers from the brain","Confirm the token-bank balance with /billing."],["Memory looks empty","Recall is per-topic — try /aegis-recall <topic> or save one with /aegis-remember <note>."]];for(const[s,e]of t)a.push([span(n.green,GLYPH.bullet),span(n.white," "+s)]),a.push([span(""," "),span(n.gray,e)]);return a.push([span("","")]),a.push([span(n.gray,"Run /status for account state. Help: https://aegiscloud.org")]),a}function buildOnboarding(s,e={}){const n=themeOf(e),a=[];a.push([span(n.gold+BOLD,"Getting started"),span(BOLD_OFF,"")]);const t=[["/help","list every command"],["/","open the command palette"],["?","shortcuts"],["/model <id>","pin a model"],["/theme light|dark","switch the colour theme"],["/aegis-ask","ask the pooled brain a question"],["/memory","show your AEGIS cloud memory"],["Ctrl-D","exit"]];for(const[s,e]of t)a.push([span(""," "),span(n.lavender,s),span(""," ".repeat(Math.max(1,20-[...s].length))),span(n.gray,e)]);return a.push([span("","")]),a.push([span(n.gray,'Try "summarize this file for me" to see the full flow.')]),a}function buildShellCompletion(s,e={}){const n=themeOf(e),a=[];a.push([span(n.gold+BOLD,"Shell completion"),span(BOLD_OFF,"")]),a.push([span(""," "),span(n.gray,"Aegiscode completes /commands with Tab inside the app.")]),a.push([span(""," "),span(n.gray,"For shell-level completion of the aegiscode CLI itself:")]),a.push([span(""," ")]);const t=[["bash",'eval "$(aegiscode shell-completion bash)"'],["zsh",'eval "$(aegiscode shell-completion zsh)"'],["fish","aegiscode shell-completion fish | source"]];for(const[s,e]of t)a.push([span(""," "),span(n.white+BOLD,s),span(""," ".repeat(Math.max(1,6-s.length))),span(n.gray,e)]);return a.push([span("","")]),a.push([span(n.dim,"Add the eval line to your ~/.bashrc or ~/.zshrc to make it persist.")]),a}function buildTerminalSetup(s,e={}){const n=themeOf(e),a=obj(s),t="undefined"!=typeof process&&process.env?process.env:{},{cols:o,rows:r}=getSize(),p=str(a.shell)||pathName(str(t.SHELL)),i=[["TERM",str(a.term)||str(t.TERM)||"(unset)"],["LANG",str(a.lang)||str(t.LANG)||"(unset)"],["Shell",p||"unknown"],["Size",`${o}x${r}`]],u=[];u.push([span(n.gold+BOLD,"Terminal setup"),span(BOLD_OFF,"")]);for(const s of kv(n,i,{keyStyle:n.white,valStyle:n.gray}))u.push(s);return u.push([span("","")]),u.push([span(n.gray,"Tips:")]),u.push([span(n.gray," • TERM=xterm-256color enables full color + resize handling")]),u.push([span(n.gray," • Set LANG (e.g. en_US.UTF-8) for correct glyphs and word wrap")]),u.push([span(n.gray," • Resize mid-session is handled (SIGWINCH); overlays adapt")]),u}function buildTerminalCaps(s,e={}){const n=themeOf(e),a=(Array.isArray(s)?s:[]).filter((s=>Array.isArray(s)&&s.length>=2)).map((([s,e])=>[str(s),str(e)])),t=[];if(t.push([span(n.gold+BOLD,"Terminal capabilities"),span(BOLD_OFF,"")]),!a.length)return t.push([span(""," "),span(n.gray,"No capability report available.")]),t;for(const s of kv(n,a,{keyStyle:n.white,valStyle:n.gray}))t.push(s);return t.push([span("","")]),e&&e.pinned&&(t.push([span(n.coral,GLYPH.warn),span(n.gold," width is pinned — resizes are ignored until /terminal auto")]),t.push([span("","")])),t.push([span(n.gray,"Override: /terminal ascii | unicode | color | no-color | background <dark|light> | star <native|narrow>")]),t.push([span(n.gray," /terminal width <cols> | auto | status")]),t.push([span(n.gray,"At launch: --ascii --unicode --no-color --width <cols> --terminal")]),t}function buildPRs(s,e={}){const n=themeOf(e),a=[];a.push([span(n.gold+BOLD,"Open pull requests"),span(BOLD_OFF,"")]);const t=str(s).trim();if(!t)return a.push([span(""," "),span(n.gray,"No open PRs in this repository.")]),a;for(const s of t.split("\n").slice(0,10))a.push([span(""," "),span(n.white,s)]);return a.push([span("","")]),a.push([span(n.gray,"Review with /review · comments via /pr-comments")]),a}function buildBenchmark(s,e={}){const n=themeOf(e),a=Array.isArray(s)?s:[],t=[];t.push([span(n.gold+BOLD,"Benchmark"),span(BOLD_OFF,"")]),t.push([span(""," "),span(n.gray,"In-app micro-benchmarks (this process, this machine):")]),t.push([span(""," ")]);for(const s of a){if(!Array.isArray(s)||s.length<2)continue;const e=str(s[0]);t.push([span(""," "),span(n.white,e),span(""," ".repeat(Math.max(1,30-[...e].length))),span(n.gray,`${num(s[1])} ms`)])}return a.length||t.push([span(""," "),span(n.gray,"(no benchmarks run)")]),t.push([span("","")]),t.push([span(n.dim,"Spoiler: the terminal renders faster than you type.")]),t}const WAIFU_ART=[" ▄▄▄▄▄▄▄▄▄▄▄▄"," ▄█▓▓▓▓▓▓▓▓▓▓▓▓█▄"," █▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█"," █▓▓▓█▓▓▓▓▓▓▓█▓▓▓█"," █▓▓█▓▓█▓▓▓█▓▓█▓▓█"," █▓▓█▓█▓▓▓█▓█▓▓█"," █▓▓▓█▓▓▓█▓▓▓█"," ██▓▓▓▓▓▓▓▓▓▓▓▓▓██"," █▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█"," █▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█"," █▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█"," ▀█▓▓▓▓▓▓▓▓▓▓▓▓▓█▀"," ▀▀▀███████▀▀▀"];function buildWaifu(s={}){const e=themeOf(s),n=[];n.push([span(e.gold+BOLD,"Waifu"),span(BOLD_OFF,"")]);for(const s of WAIFU_ART)n.push([span(e.lavender,s)]);return n.push([span("","")]),n.push([span(e.gray,"A distinguished gentleman, rendered in block characters.")]),n}function buildAegisStatus(s,e={}){const n=themeOf(e),a=obj(s),t=statsFrom(a),o=a.cloud&&"object"==typeof a.cloud?a.cloud:null,r=str(a.cloudNote),p=str(a.version),i=str(a.backend||a.store),u=[];u.push([span(n.gold+BOLD,"ÆGIS Status"),span(BOLD_OFF,"")]),u.push([span(n.gray,"─".repeat(30))]);const l=t?num(t.total):0,h=t?num(t.sessions):0;if(u.push([span(n.white,`Memory: ${l.toLocaleString()} entries across ${h} sessions`)]),t&&t.roles&&(null!=t.roles.user||null!=t.roles.assistant)){const s=t.roles,e=[];null!=s.user&&e.push(`${num(s.user)} user`),null!=s.assistant&&e.push(`${num(s.assistant)} assistant`),s.other&&e.push(`${num(s.other)} other`),e.length&&u.push([span(n.gray,` roles: ${e.join(" · ")}`)])}if(t&&t.tiers&&u.push([span(n.gray,` tiers: ${JSON.stringify(t.tiers)}`)]),i&&u.push([span(n.gray,` store: ${i}`)]),t&&null!=t.total){const s=num(t.withEmbeddings),e=l?Math.round(s/l*100):0;if(!0===t.embeddingsEnabled){const s=t.embeddingModels&&Object.keys(t.embeddingModels)[0]||"embedding";u.push([span(n.gray,` embed: ${s} · ${e}% coverage`)])}else!1===t.embeddingsEnabled&&l&&u.push([span(n.gray," embed: keyword-only")]);t.stale&&u.push([span(n.gray,` stale: ${num(t.stale)} entries >90d`)])}if(o){const s=o.key?"✓ connected":"✗ no API key",e=o.sync?"sync on":"sync off";u.push([span(n.white,`Cloud: ${s}, ${e}`)])}else r?u.push([span(n.gray,`Cloud: ${r}`)]):u.push([span(n.gray,"Cloud: not checked (aegis /cloud status unavailable)")]);return p&&u.push([span(n.gray,`CLI: aegis ${p}`)]),u}function buildAegisRecall(s,e={}){const n=themeOf(e),a=Array.isArray(s)?s.filter(Boolean):[],t=[];if(t.push([span(n.gold+BOLD,"ÆGIS Memory"),span(BOLD_OFF,"")]),t.push([span(n.gray,"─".repeat(30))]),!a.length)return t.push([span(n.gray,"No memory found for this topic.")]),t.push([span(n.gray,"Nothing relevant is stored yet — /aegis-remember <note> saves one.")]),t;for(const s of a.slice(0,10)){const e=str(s.content).split("\n")[0].slice(0,90);t.push([span(n.white+BOLD,`• ${e}`),span(BOLD_OFF,"")]);const a=s.timestamp?str(s.timestamp).slice(0,10):"",o=s.source?` (${str(s.source)})`:"",r=Array.isArray(s.tags)&&s.tags.length?" · tags: "+s.tags.join(", "):"";t.push([span(n.gray,` ${a}${o}${r}`)])}return a.length>10&&t.push([span(n.gray,`…and ${a.length-10} more`)]),t}function buildAegisMulti(s,e={}){const n=themeOf(e),a=str(s),t=[];return t.push([span(n.gold+BOLD,"ÆGIS Multi — compose"),span(BOLD_OFF,"")]),t.push([span(n.gray,"─".repeat(30))]),t.push([span(n.gray,"Paste into your aegis-cli session (the confirmation prompt works there):")]),t.push([span(n.white,` /multi ${a}`)]),t.push([span(n.gray," /multiyolo "+a+" — auto-approved variant")]),t.push([span("","")]),t.push([span(n.gray,"Optional flags: --save-as <name> · --template <id>")]),t.push([span(n.gray,'Add "run" to execute headless here instead: /aegis-multi <task> run')]),t}function buildAegisPrint(s,e={},n={}){const a=themeOf(n),t=obj(e),o=[];o.push([span(a.gold+BOLD,str(s)),span(BOLD_OFF,"")]),o.push([span(a.gray,"─".repeat(30))]);for(const s of str(t.result).split("\n"))o.push([span(a.white,s)]);return(t.model||t.provider)&&o.push([span(a.gray,` via ${str(t.provider)||"aegis"}${t.model?" · "+str(t.model):""}`)]),o}function buildBilling(s,e={}){const n=themeOf(e),a=obj(s),t=[];t.push([span(n.gold+BOLD,"Billing"),span(BOLD_OFF,"")]),t.push([span(n.gray,"─".repeat(30))]);const o=[];if(null!=a.balance&&o.push(["Balance",fmtEur(a.balance)]),null!=a.plan&&o.push(["Plan",str(a.plan)]),null!=a.account&&o.push(["Account",str(a.account)]),null!=a.costEur&&o.push(["This session",fmtEur(a.costEur)]),o.length)for(const s of kv(n,o,{indent:" ",keyStyle:n.gray,valStyle:n.white}))t.push(s);else t.push([span(""," "),span(n.gray,"No billing data available.")]);t.push([span("","")]),t.push([span(n.white,"AEGIS pooled inference"),span(n.gray," metered against your token bank")]);const r=a.payment&&"object"==typeof a.payment?a.payment:null;if(r){const{cols:s}=getSize(),e=r.paid?"✔":"✦";t.push(...wrapRows(`${e} ${str(r.label)||"Unlimited"}: ${str(r.reason)}`,2,r.paid?n.green:n.gold,s)),t.push(...wrapRows(str(r.honesty),2,n.gray,s)),!r.paid&&r.unlock&&t.push(...wrapRows(str(r.unlock),2,n.gray,s)),r.byok&&t.push(...wrapRows(str(r.byok),2,n.gray,s)),!1===r.verified&&t.push(...wrapRows("(account not confirmed this session — verdict may be stale)",2,n.gray,s)),r.url&&t.push([span(""," "),span(n.gray,str(r.url))])}else t.push([span(n.gray,` Top-ups and invoices: ${goUrl("topup","cost_screen")}`)]);return t}function buildTokens(s,e={}){const n=themeOf(e),a=obj(s),{cols:t}=getSize(),o=Math.max(24,t-2),r=a.tokens&&"object"==typeof a.tokens?a.tokens:{},{input:p,output:i,cacheRead:u,cacheWrite:l,total:h}=tokenBuckets(r),c=num(a.costEur),d=num(a.contextWindow)||2e5,m=d>0?Math.min(100,Math.round(h/d*100)):0,g=[];g.push([span(n.gold+BOLD,"Token usage"),span(BOLD_OFF,"")]),g.push([span(n.gray,"─".repeat(Math.min(30,o)))]);const y=Math.max(p,i,u,l,1),f=(s,e)=>{const a=Math.min(1,e/y),t=Math.max(0,Math.round(24*a));return[span(""," "),span(n.white,s),span(""," ".repeat(Math.max(1,11-[...s].length))),span(n.green,"█".repeat(t)),span(n.dim,"█".repeat(Math.max(0,24-t))),span(n.gray,` ${fmtTokens(e)}`)]};return g.push(f("input",p)),g.push(f("output",i)),g.push(f("cache read",u)),g.push(f("cache write",l)),g.push([span(""," ")]),g.push([span(""," "),span(n.white,"Total:"),span(n.gray,` ${fmtTokens(h)}`),span(""," ".repeat(8)),span(n.white,"Est. cost:"),span(n.gray,` ${fmtEur(c)}`)]),g.push([span(""," "),span(n.gray,`Context: ${m}% of ${fmtTokens(d)} window`)]),g.push([span(""," "),span(n.gray,"Tokens are counted from this session; cost is metered in euro.")]),g}function buildSkills(s,e,n={}){const a=themeOf(n),t=Array.isArray(s)?s.filter(Boolean):[],o=Array.isArray(e)?e:[],r=[];if(r.push([span(a.gold+BOLD,"Skills"),span(BOLD_OFF,"")]),r.push([span(a.gray,"─".repeat(30))]),!t.length){r.push([span(a.gray,"No skills found.")]),r.push([span(a.gray,"Skill dirs scanned:")]);for(const s of o)r.push([span(a.dim,` ${str(s)}`)]);return r.push([span("","")]),r.push([span(a.gray,"Add one: mkdir -p .aegis/skills/<name> and drop a SKILL.md inside.")]),r}let p=null;for(const s of t){s.source!==p&&(r.push([span(a.gray+BOLD,"user"===s.source?"User":"Project"),span(BOLD_OFF,"")]),p=s.source);const e=s.namespace?`${str(s.namespace)}/${str(s.name)}`:str(s.name),n=str(s.description)||"(no description)";r.push([span(a.white,` ${e}`),span(a.gray," ".repeat(Math.max(1,18-[...e].length))+n)])}return r.push([span("","")]),r.push([span(a.gray,"/skills <name> for details · /skills refresh to rescan")]),r}function buildSkillDetail(s,e={}){const n=themeOf(e),a=obj(s),t=a.namespace?`${str(a.namespace)}/${str(a.name)}`:str(a.name),o=[];o.push([span(n.gold+BOLD,`Skill: ${t}`),span(BOLD_OFF,"")]),o.push([span(n.gray,"─".repeat(30))]),a.description&&o.push([span(n.gray,str(a.description))]),o.push([span(n.dim,str(a.path))]),o.push([span("","")]);const r=str(a.content).split("\n"),p=r.slice(0,8).join("\n");for(const s of p.split("\n"))o.push([span(n.white,s)]);return r.length>8&&o.push([span(n.gray,`… (${r.length} lines)`)]),o}function buildMcp(s,e,n={}){const a=themeOf(n),t=Array.isArray(s)?s.map(((s,e)=>[str(s&&s.name)||String(e),s])):s&&"object"==typeof s?Object.entries(s):[],o=Array.isArray(e)?e:[],r=[];if(r.push([span(a.gold+BOLD,"MCP servers"),span(BOLD_OFF,"")]),r.push([span(a.gray,"─".repeat(30))]),t.length)for(const[s,e]of t){const n="string"==typeof e?e:(str(e&&e.command)+" "+(Array.isArray(e&&e.args)?e.args.join(" "):"")).trim();r.push([span(a.white,` ${str(s)}`),span(a.gray," ".repeat(Math.max(1,14-[...str(s)].length))+n)])}else r.push([span(a.gray,"No MCP servers configured.")]);return r.push([span("","")]),r.push([span(a.gray,"This build has no MCP runtime — servers are configuration only.")]),r.push([span(a.gray,"/mcp add <name> <command> [args…] · /mcp remove <name>")]),o.length&&r.push([span(a.dim,"Sources: "+o.join(", "))]),r}function buildRouter(s,e={}){const n=themeOf(e),a=obj(s),t=a.autoRouter&&"object"==typeof a.autoRouter?a.autoRouter:a.router&&"object"==typeof a.router?a.router:{enabled:!1,tiers:{}},o=t.tiers&&"object"==typeof t.tiers?t.tiers:{},r=[];return r.push([span(n.gold+BOLD,"Model router"),span(BOLD_OFF,"")]),r.push([span(n.gray,"─".repeat(30))]),r.push([span(n.white,"auto-router: "+(t.enabled?"on":"off"))]),r.push([span(n.gray,` simple ${str(o.simple)||"(auto)"}`)]),r.push([span(n.gray,` medium ${str(o.medium)||"(auto)"}`)]),r.push([span(n.gray,` complex ${str(o.complex)||"(auto)"}`)]),r.push([span("","")]),r.push([span(n.gray,"/router on|off · /router set <simple|medium|complex> <modelId>")]),r.push([span(n.dim,"Routing config is persisted for the real CLI; this build serves the model chosen by /model.")]),r}function buildMemory(s,e={}){const n=themeOf(e),a=obj(s),t=statsFrom(a),o=a.embedStatus&&"object"==typeof a.embedStatus?a.embedStatus:null,r=a.compactState&&"object"==typeof a.compactState?a.compactState:a.at?a:null,p=a.compactCfg&&"object"==typeof a.compactCfg?a.compactCfg:null,i=[];i.push([span(n.gold+BOLD,"ÆGIS Memory"),span(BOLD_OFF,"")]),i.push([span(n.gray,"─".repeat(30))]);const u=t?num(t.total):0,l=t?num(t.sessions):0;if(i.push([span(n.white,`${u.toLocaleString()} memories across ${l} sessions`)]),t&&t.roles&&"object"==typeof t.roles){const s=[];null!=t.roles.user&&s.push(`${num(t.roles.user)} user`),null!=t.roles.assistant&&s.push(`${num(t.roles.assistant)} assistant`),t.roles.other&&s.push(`${num(t.roles.other)} other`),s.length&&i.push([span(n.gray,` roles: ${s.join(" · ")}`)])}if(t&&t.tiers&&i.push([span(n.gray,` tiers: ${JSON.stringify(t.tiers)}`)]),t&&null!=t.total){const s=u?Math.round(num(t.withEmbeddings)/u*100):0;o&&o.engine?i.push([span(n.gray,` embed: ${str(o.engine)} · ${s}% coverage`)]):o&&i.push([span(n.gray," embed: keyword-only")]),t.stale&&i.push([span(n.gray,` stale: ${num(t.stale)} entries >90d`)])}return r&&i.push([span(n.gray,r.at?` last compact: ${str(r.at).slice(0,10)}`:" auto-compact: never run")]),p&&i.push([span(n.gray,` auto-compact: ${p.enabled?"on":"off"} (min ${num(p.minL1)} L1 · ${num(p.cooldownMin)}m cooldown)`)]),i.push([span("","")]),i.push([span(n.gray,"/memory tiers · /memory embeddings · /memory recall <q>")]),i.push([span(n.gray,"/memory compact · /memory profile · /aegis-remember <note> to save")]),i}function buildMemoryTiers(s,e={}){const n=themeOf(e),a=obj(s),t=statsFrom(a),o=Array.isArray(a.pending)?a.pending:[],r=a.compactState&&"object"==typeof a.compactState?a.compactState:null,p=a.compactCfg&&"object"==typeof a.compactCfg?a.compactCfg:null,i=[];if(i.push([span(n.gold+BOLD,"Memory Tiers"),span(BOLD_OFF,"")]),i.push([span(n.gray,"─".repeat(30))]),t&&t.tiers&&(i.push([span(n.white,`L0 turns ${num(t.tiers.L0)} raw session turns, volatile`)]),i.push([span(n.white,`L1 atomic ${num(t.tiers.L1)} facts · decisions · breakthroughs`)]),i.push([span(n.white,`L2 scenario ${num(t.tiers.L2)} distilled reusable context`)]),i.push([span(n.white,`L3 profile ${num(t.tiers.L3)} single distilled identity row`)])),i.push([span("","")]),i.push([span(n.gray,`pending L1 (auto-compact trigger): ${o.length}`)]),r&&r.at){const s=Array.isArray(r.scenarios)?r.scenarios.length:0;i.push([span(n.gray,`last auto-compact: ${str(r.at).slice(0,16)} · ${s} scenario${1===s?"":"s"}`)])}else i.push([span(n.gray,"last auto-compact: never")]);return i.push([span(n.gray,p?`auto-compact: ${p.enabled?"on":"off"} · min ${num(p.minL1)} L1 · ${num(p.cooldownMin)}m cooldown`:"auto-compact: on · min 5 L1 · 15m cooldown")]),i.push([span("","")]),i.push([span(n.gray,"/memory compact runs maintenance manually")]),i}function buildMemoryEmbeddings(s,e,n={}){const a=themeOf(n),t=s&&"object"==typeof s?s:null,o=e&&"object"==typeof e?e:null,r=[];if(r.push([span(a.gold+BOLD,"Memory Embeddings"),span(BOLD_OFF,"")]),r.push([span(a.gray,"─".repeat(30))]),t&&t.engine?(r.push([span(a.white,`engine: ${str(t.engine)} · ${str(t.model)}`)]),t.dim&&r.push([span(a.gray,` dim: ${num(t.dim)}`)])):(r.push([span(a.white,"engine: keyword-only (no embedder resolved)")]),t&&t.reason&&r.push([span(a.gray,` reason: ${str(t.reason)}`)])),r.push([span(a.gray,`mode: ${t&&str(t.mode)||"auto"} (env AEGIS_MEMORY_EMBED or memoryConfig.embedMode)`)]),o&&null!=o.total){const s=num(o.total),e=num(o.withEmbeddings),n=s?Math.round(e/s*100):0;if(r.push([span(a.gray,`coverage: ${e}/${s} rows (${n}%)`)]),o.embeddingModels&&Object.keys(o.embeddingModels).length){const s=Object.entries(o.embeddingModels).map((([s,e])=>`${s}: ${num(e)}`));r.push([span(a.gray,` models: ${s.join(" · ")}`)])}o.stale&&r.push([span(a.gray,` stale (>90d): ${num(o.stale)}`)])}return r.push([span("","")]),r.push([span(a.gray,"/memory embeddings on|off toggles the engine chain")]),r}function buildAutomode(s,e={}){const n=themeOf(e),a=[];return a.push([span(n.gold+BOLD,"⚠ automode enabled"),span(BOLD_OFF,"")]),a.push([span(n.gray,"─".repeat(30))]),a.push([span(n.white,"All tool executions are auto-approved: file writes,")]),a.push([span(n.white,"bash commands, and network requests run without asking.")]),a.push([span("","")]),a.push([span(n.gray,"Run /automode off to restore confirmations.")]),a.push([span(n.gray,"(/yolo is accepted as an alias.)")]),a}const buildYolo=buildAutomode;function buildReleaseNotes(s,e={}){const n=themeOf(e),a=[];a.push([span(n.gold+BOLD,`What's new in v${VERSION}`),span(BOLD_OFF,"")]),a.push([span(n.gray,"─".repeat(30))]);const t=["v6.7.3 — the shared renderer is re-staged into cli/vendor.","v6.7.1 — terminal capabilities are read from the terminal, not the platform.","v6.7.0 — a file edit renders as a coloured diff block.","v6.6.0 — autonomous mode: a persistent work queue with a detached worker.","v6.5.x — the live tool row, /cost billed from the ledger the server settled at.","v6.4.0 — `aegiscode login`/`logout`/`key`, a 0600 credential store, /cloud and /sync."];for(const s of t){const e=s.indexOf(" — "),t=-1===e?s:s.slice(0,e),o=-1===e?"":s.slice(e+3);a.push([span(n.green,"•"),span(n.gold,` ${t}`),span(n.white,o?` — ${o}`:"")])}let o=null;try{const s=require("./commands.js");o={n:s.visibleCommands().length,cats:s.CATEGORIES.length}}catch{}return o&&(a.push([span("","")]),a.push([span(n.gray,` ${o.n} commands across ${o.cats} categories — /help lists them.`)])),a.push([span(n.gray," The version above is read from the package; the prose is not.")]),a.push([span(n.gray," Repo: https://aegiscloud.org")]),a}function stubPanel(s,e,n){const a=themeOf(s);return[[span(a.gold+BOLD,e),span(BOLD_OFF,"")],[span(a.gray,` ${e} is not available in aegiscode — ${n}`)]]}function buildDoctor(s,e={}){return stubPanel(e,"Doctor","it needs the local environment diagnostic suite.")}function buildBuildPanel(s,e={}){const n=obj(s),a=themeOf(e);return[[span(a.gold+BOLD,`⬡ Build: ${str(n.plan&&n.plan.appName)||"build"}`),span(BOLD_OFF,"")],[span(a.gray," Build is not available in aegiscode — it needs a local multi-model agent build loop.")]]}module.exports={buildHelp:buildHelp,buildStatus:buildStatus,buildCost:buildCost,buildContext:buildContext,buildTokens:buildTokens,buildAgents:buildAgents,buildPermissions:buildPermissions,buildModelList:buildModelList,buildRewindList:buildRewindList,buildOnboarding:buildOnboarding,buildShellCompletion:buildShellCompletion,buildTerminalSetup:buildTerminalSetup,buildTerminalCaps:buildTerminalCaps,buildPRs:buildPRs,buildBenchmark:buildBenchmark,buildWaifu:buildWaifu,buildAegisStatus:buildAegisStatus,buildAegisRecall:buildAegisRecall,buildAegisMulti:buildAegisMulti,buildBilling:buildBilling,buildMemory:buildMemory,buildMemoryTiers:buildMemoryTiers,buildRouter:buildRouter,buildAutomode:buildAutomode,buildYolo:buildYolo,buildSkills:buildSkills,buildMcp:buildMcp,buildHooksStatus:buildHooksStatus,buildHooksList:buildHooksList,buildTroubleshooting:buildTroubleshooting,buildReleaseNotes:buildReleaseNotes,renderSessionsOverlay:renderSessionsOverlay,buildAegisPrint:buildAegisPrint,buildSkillDetail:buildSkillDetail,buildMemoryEmbeddings:buildMemoryEmbeddings,buildDoctor:buildDoctor,buildBuildPanel:buildBuildPanel,fmtEur:fmtEur,fmtTokens:fmtTokens};
|
|
3
|
+
"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),m=num(a.costEur),d=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(m).length))+fmtEur(m))]),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,` ${d}: ${fmtTokens(h)} input, ${fmtTokens(i)} output (${fmtEur(m)})`)]),(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,"pro"===e.modelClass?"Claude Code Pro (your own subscription) — not billed from the AEGIS token bank; cost above is a market-rate estimate.":"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),m=num(a.contextWindow)||2e5,d=[];d.push([span(n.gold+BOLD,"Context usage"),span(BOLD_OFF,"")]),d.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,m,n)];return d.push(g("Prompt tokens",h)),(u||l)&&d.push([span(""," "),span(n.dim,` ↳ miss ${fmtTokens(p)} · cache read ${fmtTokens(u)} · cache write ${fmtTokens(l)}`)]),d.push(g("Output tokens",i)),d.push([span(""," ")]),d.push([span(""," "),span(n.gray,"─".repeat(Math.max(1,o-2)))]),d.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,m,n)]),d.push([span(""," ")]),d.push([span(""," "),span(n.gray,`Context window: ${fmtTokens(m)} tokens`)]),d}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,m=l.filter((s=>s.completed)).length,d=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(d([span(t.white,i),span(t.gray," · "),span(t.white,u)])),g.push(d([span(t.gray,`${h} awaiting input · ${c} working · ${m} completed`)])),g.push([span(t.gray,"├"+"─".repeat(r)+"┤")]),g.push(d([span(t.white+BOLD,"Needs input"),span(BOLD_OFF,"")])),g.push(d([span(t.gray,"Sessions that have a question or need your decision land here")])),g.push(d([span(t.coral,GLYPH.bloom),span(t.gray," current session send a prompt to start "),span(t.gray,"—")])),g.push(d([span(t.white+BOLD,"Working"),span(BOLD_OFF,"")])),g.push(d([span(t.gray,"Sessions AEGIS is actively working on — they keep running even if you close the terminal")])),g.push(d([span(t.white+BOLD,"Completed"),span(BOLD_OFF,"")])),g.push(d([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)]);const i=t._permissionMode?str(t._permissionMode):"";p.push([span(""," "),span(a.gray,"Permission mode: "),i?span(a.white,i):span(a.dim,"unset (no flag passed)")]),p.push([span(""," ")]);const u=(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 u("Allow",o(t.allow)))p.push(s);for(const s of u("Deny",o(t.deny)))p.push(s);for(const s of u("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(a.gray," /permissions mode plan · /permissions mode off")]),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),m=num(a.contextWindow)||2e5,d=m>0?Math.min(100,Math.round(h/m*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: ${d}% of ${fmtTokens(m)} 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};
|
|
@@ -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 NEXUS_BRAIN_IDS=Object.freeze(["nexus-brain","aegis-brain"]),AEGIS_CLOUD_MODEL_IDS=Object.freeze(["nexus-brain","aegis-brain","nexus-brain-smart","aegis-brain-smart","nexus-brain-neo","aegis-brain-neo"]),AEGIS_CLOUD_MODEL_RE=/^(?:nexus|aegis)-brain(?:-(?:smart|neo))?$/,NEXUS_LABEL="Nexus";function aliasOfEntry(e){if(!e||"object"!=typeof e)return null;for(const i of[e.alias_of,e.aliasOf])if("string"==typeof i&&i.trim())return i.trim();return null}function isHiddenEntry(e){return Boolean(e)&&!0===e.hidden}function selectBrainEntry(e){const i=Array.isArray(e)?e.filter(Boolean):[];return i.find((e=>NEXUS_BRAIN_IDS.includes(e.id)&&!isHiddenEntry(e)&&null===aliasOfEntry(e)))||i.find((e=>NEXUS_BRAIN_IDS.includes(e.id)))||i.find((e=>NEXUS_BRAIN_IDS.includes(aliasOfEntry(e))))||null}function filterAegisCatalog(e){const i=selectBrainEntry(e);if(!i)return[];const{hidden:
|
|
3
|
+
"use strict";const NEXUS_BRAIN_IDS=Object.freeze(["nexus-brain","aegis-brain"]),AEGIS_CLOUD_MODEL_IDS=Object.freeze(["nexus-brain","aegis-brain","nexus-brain-smart","aegis-brain-smart","nexus-brain-neo","aegis-brain-neo"]),AEGIS_CLOUD_MODEL_RE=/^(?:nexus|aegis)-brain(?:-(?:smart|neo))?$/,NEXUS_LABEL="Nexus",AUTO_MODEL_ID="nexus";function isAutoModelId(e){return"nexus"===String(null==e?"":e).trim().toLowerCase()}const AUTO_LABEL="Nexus — auto-route",AUTO_NOTE="server picks fast/smart/neo from the ask";function aliasOfEntry(e){if(!e||"object"!=typeof e)return null;for(const i of[e.alias_of,e.aliasOf])if("string"==typeof i&&i.trim())return i.trim();return null}function isHiddenEntry(e){return Boolean(e)&&!0===e.hidden}function selectBrainEntry(e){const i=Array.isArray(e)?e.filter(Boolean):[];return i.find((e=>NEXUS_BRAIN_IDS.includes(e.id)&&!isHiddenEntry(e)&&null===aliasOfEntry(e)))||i.find((e=>NEXUS_BRAIN_IDS.includes(e.id)))||i.find((e=>NEXUS_BRAIN_IDS.includes(aliasOfEntry(e))))||null}function filterAegisCatalog(e){const i=selectBrainEntry(e);if(!i)return[];const{hidden:t,alias_of:n,aliasOf:r,...s}=i;return[{...s,label:"Nexus"}]}function isAegisCloudModel(e){const i="string"==typeof e?e.trim():e&&"object"==typeof e&&"string"==typeof e.id?e.id.trim():"";return!!AEGIS_CLOUD_MODEL_IDS.includes(i)||!!AEGIS_CLOUD_MODEL_RE.test(i)||NEXUS_BRAIN_IDS.includes(aliasOfEntry(e))}function omitAegisCloudModels(e){return(Array.isArray(e)?e:[]).filter((e=>{if(!e)return!1;if("string"==typeof e)return!isAegisCloudModel(e);const i="string"==typeof e.id?e.id.trim():"";return Boolean(i)&&!isAegisCloudModel(e)}))}function offerableCatalog(e){const i=Array.isArray(e)?e.filter(Boolean):[];if(!i.length)return[];const t=selectBrainEntry(i),n=[],r=new Set;if(t){const{hidden:e,alias_of:i,aliasOf:s,...o}=t;n.push({...o,label:"Nexus"});for(const e of NEXUS_BRAIN_IDS)r.add(e);"string"==typeof t.id&&r.add(t.id)}const s=new Set(i.map((e=>"string"==typeof e.id?e.id.trim():"")).filter(Boolean)),o=new Set(i.map((e=>aliasOfEntry(e))).filter((e=>e&&s.has(e))));for(const e of i){const i="string"==typeof e.id?e.id.trim():"";i&&!r.has(i)&&(aliasOfEntry(e)&&o.has(aliasOfEntry(e))||(r.add(i),n.push(e)))}return n}module.exports={NEXUS_BRAIN_IDS:NEXUS_BRAIN_IDS,NEXUS_LABEL:"Nexus",AUTO_MODEL_ID:"nexus",AUTO_LABEL:AUTO_LABEL,AUTO_NOTE:AUTO_NOTE,isAutoModelId:isAutoModelId,AEGIS_CLOUD_MODEL_IDS:AEGIS_CLOUD_MODEL_IDS,isAegisCloudModel:isAegisCloudModel,omitAegisCloudModels:omitAegisCloudModels,selectBrainEntry:selectBrainEntry,filterAegisCatalog:filterAegisCatalog,offerableCatalog:offerableCatalog};
|
|
@@ -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 BYOK_MODEL_ADDITIONS=Object.freeze({}),WIRE_MODEL_ALIASES=Object.freeze({deepseek:Object.freeze({"deepseek-v4.1-flash":"deepseek-flash","deepseek-flash-41":"deepseek-flash","deepseek-flash-0731":"deepseek-flash","deepseek-v4-flash-0731":"deepseek-flash","deepseek-pro":"deepseek-v4-pro","deepseek-v4-pro-latest":"deepseek-v4-pro","deepseek-v4.1-flash-1017":"deepseek-flash","deepseek-v4-pro-0813":"deepseek-v4-pro"})}),SNAPSHOT_SUFFIX_RE=/-(?:\d{4}|\d{8})$/;function knownWireId(e,r){return Object.prototype.hasOwnProperty.call(e,r)?e[r]:Object.values(e).includes(r)?r:""}function canonicalModelId(e,r){const
|
|
3
|
+
"use strict";const BYOK_MODEL_ADDITIONS=Object.freeze({}),WIRE_MODEL_ALIASES=Object.freeze({deepseek:Object.freeze({"deepseek-v4.1-flash":"deepseek-flash","deepseek-flash-41":"deepseek-flash","deepseek-flash-0731":"deepseek-flash","deepseek-v4-flash-0731":"deepseek-flash","deepseek-pro":"deepseek-v4-pro","deepseek-v4-pro-latest":"deepseek-v4-pro","deepseek-v4.1-flash-1017":"deepseek-flash","deepseek-v4-pro-0813":"deepseek-v4-pro"})}),SNAPSHOT_SUFFIX_RE=/-(?:\d{4}|\d{8})$/;function knownWireId(e,r){return Object.prototype.hasOwnProperty.call(e,r)?e[r]:Object.values(e).includes(r)?r:""}function canonicalModelId(e,r){const o="string"==typeof r?r.trim():"";if(!o)return o;const s="string"==typeof e?e.trim():"",n=s?WIRE_MODEL_ALIASES[s]:null;if(!n)return o;const t=knownWireId(n,o);if(t)return t;const i=o.replace(SNAPSHOT_SUFFIX_RE,"");if(i!==o){const e=knownWireId(n,i);if(e)return e}return o}function addedModelsFor(e){const r="string"==typeof e?e.trim():"",o=r?BYOK_MODEL_ADDITIONS[r]:null;return Array.isArray(o)?o.slice():[]}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 withByokAdditions(e){const r=Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null;if(!r)return[];const o=[];for(const e of r){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.id?e.id.trim():"",s=r?BYOK_MODEL_ADDITIONS[r]:null;if(!Array.isArray(s)||!s.length){o.push(e);continue}const n=new Set(modelIdsOf(e)),t=s.filter((e=>!n.has(e)));if(!t.length){o.push(e);continue}const i=Array.isArray(e.models)?e.models:[];o.push({...e,models:[...i,...t]})}return o}const NEXUS_ELIGIBLE_PROVIDERS=Object.freeze(["deepseek","openai","groq","gemini","openrouter","together","grok","xai","mistral","cerebras","fireworks"]),NEXUS_POOLED_PROVIDER_ID=Object.freeze({xai:"grok"});function nexusFallbackProvider(e){const r="string"==typeof e?e.trim().toLowerCase():"";return r&&NEXUS_ELIGIBLE_PROVIDERS.includes(r)?NEXUS_POOLED_PROVIDER_ID[r]||r:""}function nexusFallbackModel({provider:e,providerKey:r,aegisKey:o,providerKeyRefused:s}={}){return r||s?"":o?nexusFallbackProvider(e):""}function nexusFallbackNotice(e){const r=e&&e.pooled_from;return r?`no ${r} key — answered through your AEGIS account${e.pooled_model?` (${e.pooled_model})`:""}`:""}module.exports={BYOK_MODEL_ADDITIONS:BYOK_MODEL_ADDITIONS,WIRE_MODEL_ALIASES:WIRE_MODEL_ALIASES,NEXUS_ELIGIBLE_PROVIDERS:NEXUS_ELIGIBLE_PROVIDERS,NEXUS_POOLED_PROVIDER_ID:NEXUS_POOLED_PROVIDER_ID,addedModelsFor:addedModelsFor,canonicalModelId:canonicalModelId,nexusFallbackModel:nexusFallbackModel,nexusFallbackNotice:nexusFallbackNotice,nexusFallbackProvider:nexusFallbackProvider,withByokAdditions:withByokAdditions};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";
|
|
4
|
+
/**
|
|
5
|
+
* credits.js — the in-app "Credits & licence" content, built from ONE source.
|
|
6
|
+
*
|
|
7
|
+
* Neither host had a licence surface at all: `AGPL-3.0-or-later` lived in the
|
|
8
|
+
* file headers and in `LICENSE`, `LICENSING.md` held the plain-language
|
|
9
|
+
* summary, and the third-party attributions were split across
|
|
10
|
+
* `desktop/renderer/vendor/NOTICE.md` and `desktop/renderer/fonts/NOTICE.md` —
|
|
11
|
+
* three documents a user could only read by finding a checkout. The desktop's
|
|
12
|
+
* About panel showed a name and a version number; the terminal had no
|
|
13
|
+
* `/license` and no `/credits`.
|
|
14
|
+
*
|
|
15
|
+
* The fix is not to retype the attribution into a renderer (which would drift
|
|
16
|
+
* the moment a vendored file is bumped). It is to PARSE the files that already
|
|
17
|
+
* are the record, in one place, and hand both hosts a list of rows. When
|
|
18
|
+
* `marked` goes from 18.0.12 to 18.0.13 that NOTICE is the only file that
|
|
19
|
+
* changes, and both faces follow.
|
|
20
|
+
*
|
|
21
|
+
* Everything here is pure and filesystem-read-only; `buildCredits` takes the
|
|
22
|
+
* document texts rather than reading them, so it is assertable without the
|
|
23
|
+
* files and the two hosts can source them differently (the desktop reads them
|
|
24
|
+
* out of the packaged app dir, the CLI out of `cli/vendor/`).
|
|
25
|
+
*/const path=require("node:path"),fs=require("node:fs"),LICENCE_ID="AGPL-3.0-or-later",LICENCE_NAME="GNU Affero General Public License v3.0 or later",LICENCE_URL="https://www.gnu.org/licenses/agpl-3.0.html",SOURCE_URL="https://github.com/aegisinfo/aegiscode-plugin",COPYRIGHT="Copyright (C) 2026 Niklas Borneklint",DOCUMENTS=[{id:"licensing",title:"Licensing",file:path.join("LICENSING.md"),applies:"this program"},{id:"vendor",title:"Vendored third-party code",file:path.join("desktop","renderer","vendor","NOTICE.md"),applies:"renderer"},{id:"fonts",title:"Vendored webfonts",file:path.join("desktop","renderer","fonts","NOTICE.md"),applies:"renderer"}];function candidateRoots(){const t=__dirname;return[path.join(t,".."),path.join(t,"..",".."),path.join(t,"..","..","..")]}function readDocument(t){for(const e of candidateRoots()){const n=path.join(e,t.file);try{const e=fs.readFileSync(n,"utf8");return{...t,path:n,text:e}}catch{}}return null}function unwrapBullets(t){const e=[];let n=null;for(const r of String(t||"").split("\n")){const t=r.replace(/\s+$/,"");/^-\s+/.test(t)?(n&&e.push(n),n=t.replace(/^-\s+/,"").trim()):n&&/^\s{2,}\S/.test(t)?n+=" "+t.trim():n&&(e.push(n),n=null)}return n&&e.push(n),e}const LICENCE_RE=/((?:AGPL-3\.0-or-later|Apache-2\.0|MPL-2\.0|BSD-\d-Clause|OFL\s*1\.1|MIT|ISC)(?:\s*\/\s*(?:Apache-2\.0|MPL-2\.0|MIT|ISC))*)/i;function parseAttributions(t){const e=[];for(const n of unwrapBullets(t)){const t=/^`([^`]+)`\s*[—–-]\s*(.*)$/.exec(n);if(!t)continue;const r=t[1].trim(),i=t[2].trim(),s=/\[[^\]]*\]\((https?:\/\/[^)]+)\)/.exec(i),o=s?s[1]:null,c=LICENCE_RE.exec(i),l=/\bv(\d+\.\d+\.\d+)\b/.exec(i);e.push({name:r,version:l?l[1]:null,url:o,licence:c?c[1].replace(/\s+/g," ").trim():null,note:i})}return e}
|
|
26
|
+
/**
|
|
27
|
+
* Pull the `- \`Family\` — © …` rows out of the fonts NOTICE. Kept separate
|
|
28
|
+
* from parseAttributions because a font row's identifying token is a family
|
|
29
|
+
* name in backticks with a copyright line, not a file name with a version —
|
|
30
|
+
* merging them produced rows whose `licence` column said "© 2018 The Syne
|
|
31
|
+
* Project Authors".
|
|
32
|
+
*/function parseFonts(t){const e=[];for(const n of unwrapBullets(t)){const t=/^`([^`]+)`\s*[—–-]\s*(©[^()<]*[^\s()<])\s*\(\s*<?([^)\s>]+)>?\s*\)\s*[,.]?\s*(.*)$/.exec(n);if(!t)continue;const r=LICENCE_RE.exec(n);e.push({name:t[1].trim(),copyright:t[2].trim(),url:t[3]&&/^https?:\/\//.test(t[3].trim())?t[3].trim():null,licence:r?r[1].replace(/\s+/g," ").trim():null,note:t[4]?t[4].trim():null})}return e}
|
|
33
|
+
/**
|
|
34
|
+
* The whole credits payload. Both hosts render this list; neither invents a
|
|
35
|
+
* row of its own.
|
|
36
|
+
*
|
|
37
|
+
* Shape (all strings/null, so it survives IPC and JSON):
|
|
38
|
+
* {
|
|
39
|
+
* program: { licence, name, url, source, copyright, notice },
|
|
40
|
+
* documents: [{ id, title, applies, found, path }],
|
|
41
|
+
* code: [{ name, url, licence, note }],
|
|
42
|
+
* fonts: [{ name, copyright, url, licence }],
|
|
43
|
+
* missing: [id…]
|
|
44
|
+
* }
|
|
45
|
+
*/function buildCredits(t){const e={};for(const n of Array.isArray(t)?t:[])n&&n.id&&(e[n.id]=n);const n=e.vendor||null,r=e.fonts||null,i=e.licensing||null,s=i?extractNotice(i.text):"Copyright (C) 2026 Niklas Borneklint";return{program:{licence:LICENCE_ID,name:LICENCE_NAME,url:LICENCE_URL,source:SOURCE_URL,copyright:COPYRIGHT,notice:s},documents:DOCUMENTS.map((t=>({id:t.id,title:t.title,applies:t.applies,found:Boolean(e[t.id]),path:e[t.id]?e[t.id].path:null}))),code:n?parseAttributions(n.text):[],fonts:r?parseFonts(r.text):[],missing:DOCUMENTS.filter((t=>!e[t.id])).map((t=>t.id))}}function extractNotice(t){const e=String(t||""),n=e.indexOf("## Notice to apply to the program");if(-1===n)return"Copyright (C) 2026 Niklas Borneklint";const r=/```([\s\S]*?)```/.exec(e.slice(n));return r&&r[1].trim()||"Copyright (C) 2026 Niklas Borneklint"}function creditsFromDisk(t){const e=[];for(const n of DOCUMENTS){const r=t&&"function"==typeof t.readText?t.readText(n.file):readDocument(n);r&&e.push(r)}return buildCredits(e)}module.exports={LICENCE_ID:LICENCE_ID,LICENCE_NAME:LICENCE_NAME,LICENCE_URL:LICENCE_URL,SOURCE_URL:SOURCE_URL,COPYRIGHT:COPYRIGHT,DOCUMENTS:DOCUMENTS,buildCredits:buildCredits,creditsFromDisk:creditsFromDisk,parseAttributions:parseAttributions,parseFonts:parseFonts,unwrapBullets:unwrapBullets,readDocument:readDocument,extractNotice:extractNotice};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),os=require("node:os"),crypto=require("node:crypto");let DatabaseSync=null;try{DatabaseSync=require("node:sqlite").DatabaseSync}catch{DatabaseSync=null}const DEFAULTS={minMessages:2,minChars:2,maxCharsPerMessage:8e3,maxMessagesPerSession:400,maxSessionsPerSource:200,maxFilesPerSource:600,maxFileBytes:33554432,maxTotalMessages:2e4},NOISE=[/^<command-name>/i,/^<local-command-stdout>/i,/^<local-command-caveat>/i,/^<environment_context>/i,/^<user_instructions>/i,/^\[Request interrupted by user/i,/^Caveat: The messages below were generated by the user while running local commands/i,/^(ok|okay|yes|no|yep|nope|sure|thanks|thank you|continue|proceed|go on|done)[.!]?$/i],layout=require("./foreign-memory.js")._internal,platformOf=layout.platformOf,appRoots=layout.appRoots;function homeDir(e){return e||os.homedir()}function isDir(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function isFile(e){try{return fs.statSync(e).isFile()}catch{return!1}}function fileSize(e){try{return fs.statSync(e).size}catch{return 0}}function fileMtime(e){try{return fs.statSync(e).mtimeMs}catch{return Date.now()}}function stableId(...e){return`imp-${crypto.createHash("sha1").update(e.join("|")).digest("hex").slice(0,16)}`}function cleanText(e){return"string"!=typeof e?"":e.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g," ").replace(/\s+/g," ").trim()}function isNoise(e){return!e||NOISE.some((t=>t.test(e)))}function readJsonl(e){const t=[];let s;try{s=fs.readFileSync(e,"utf8")}catch{return t}for(const e of s.split("\n")){const s=e.trim();if(s)try{t.push(JSON.parse(s))}catch{}}return t}function walkFiles(e,{ext:t,limit:s}){const n=[],o=[e];for(;o.length&&n.length<s;){const e=o.pop();let i;try{i=fs.readdirSync(e,{withFileTypes:!0})}catch{continue}for(const r of i){if(n.length>=s)break;if(r.isSymbolicLink())continue;const i=path.join(e,r.name);if(r.isDirectory()){if("node_modules"===r.name||".git"===r.name)continue;o.push(i)}else if(r.isFile()){if(t&&!t.some((e=>r.name.endsWith(e))))continue;n.push(i)}}}return n}function textFromClaudeMessage(e){if(!e)return"";const t=null!=e.content?e.content:e;return"string"==typeof t?cleanText(t):Array.isArray(t)?cleanText(t.filter((e=>e&&"text"===e.type&&"string"==typeof e.text)).map((e=>e.text)).join("\n")):""}function extractClaudeSession(e,t){const s=readJsonl(e),n=[];let o="",i="",r="",a="",c="";for(const e of s){if(!e||"object"!=typeof e)continue;if(e.sessionId&&!c&&(c=e.sessionId),e.cwd&&!i&&(i=e.cwd),"summary"===e.type&&"string"==typeof e.summary&&!o){o=cleanText(e.summary);continue}const s="user"===e.type?"user":"assistant"===e.type?"assistant":null;if(!s)continue;if(!0===e.isSidechain)continue;const l=textFromClaudeMessage(e.message);isNoise(l)||(n.push({role:s,content:l.slice(0,t.maxCharsPerMessage)}),!r&&e.timestamp&&(r=e.timestamp),e.timestamp&&(a=e.timestamp))}return finishSession({file:e,messages:n,title:o,cwd:i,foreignId:c,first:r,last:a,opts:t})}function extractCodexSession(e,t){const s=readJsonl(e),n=[];let o="",i="",r="",a="";const c=(e,s)=>{isNoise(s)||n.push({role:e,content:s.slice(0,t.maxCharsPerMessage)})};for(const e of s){if(!e||"object"!=typeof e)continue;const t=e.payload&&"object"==typeof e.payload?e.payload:null,s=e.timestamp||t&&t.timestamp||"";if("session_meta"===e.type&&t)t.id&&!a&&(a=String(t.id)),t.cwd&&!o&&(o=String(t.cwd)),s&&!i&&(i=s);else if("response_item"===e.type&&t&&"message"===t.type){const e=t.role;if("user"!==e&&"assistant"!==e)continue;c(e,cleanText((Array.isArray(t.content)?t.content:[]).filter((e=>e&&("input_text"===e.type||"output_text"===e.type||"text"===e.type))).map((e=>e.text)).filter((e=>"string"==typeof e)).join("\n"))),s&&(r=s)}else"event_msg"===e.type&&t&&("user_message"===t.type?c("user",cleanText(t.message)):"agent_message"===t.type&&c("assistant",cleanText(t.message)),s&&(r=s))}return finishSession({file:e,messages:n,title:"",cwd:o,foreignId:a,first:i,last:r,opts:t})}function extractGenericSession(e,t){const s=readJsonl(e),n=[];let o="",i="",r="",a="";for(const e of s){if(!e||"object"!=typeof e)continue;const s=e.role||e.message&&e.message.role;if("user"!==s&&"assistant"!==s)continue;const c=null!=e.content?e.content:e.message&&e.message.content,l=cleanText("string"==typeof c?c:textFromClaudeMessage({content:c}));if(isNoise(l))continue;n.push({role:s,content:l.slice(0,t.maxCharsPerMessage)});const u=e.timestamp||e.created_at||e.createdAt||"";u&&!o&&(o=u),u&&(i=u),a||"string"!=typeof e.cwd||(a=e.cwd),r||"string"!=typeof e.title||(r=cleanText(e.title))}return finishSession({file:e,messages:n,title:r,cwd:a,foreignId:"",first:o,last:i,opts:t})}function extractJsonSessions(e,t){if(fileSize(e)>t.maxFileBytes)return[];let s;try{s=JSON.parse(fs.readFileSync(e,"utf8"))}catch{return[]}if(!s||"object"!=typeof s)return[];const n=Array.isArray(s)?s:Array.isArray(s.sessions)?s.sessions:Array.isArray(s.conversations)?s.conversations:Array.isArray(s.chats)?s.chats:Array.isArray(s.threads)?s.threads:null;if(!n)return[];const o=[];for(const[s,i]of n.entries()){if(!i||"object"!=typeof i)continue;const n=Array.isArray(i.messages)?i.messages:Array.isArray(i.conversation)?i.conversation:Array.isArray(i.turns)?i.turns:[],r=[];for(const e of n){if(!e||"object"!=typeof e)continue;const s="assistant"===e.role?"assistant":"user"===e.role?"user":null;if(!s)continue;const n=null!=e.content?e.content:e.text,o=cleanText("string"==typeof n?n:textFromClaudeMessage({content:n}));isNoise(o)||r.push({role:s,content:o.slice(0,t.maxCharsPerMessage)})}const a=finishSession({file:`${e}#${s}`,messages:r,title:cleanText(i.title||i.name||""),cwd:"string"==typeof i.cwd?i.cwd:"",foreignId:i.id||i.sessionId||i.uuid||"",first:i.createdAt||i.created_at||"",last:i.updatedAt||i.updated_at||"",opts:t});a&&o.push(a)}return o}function finishSession({file:e,messages:t,title:s,cwd:n,foreignId:o,first:i,last:r,opts:a}){const c=t.slice(0,a.maxMessagesPerSession);if(c.length<a.minMessages)return null;const l=c.find((e=>"user"===e.role));if(!l)return null;const u=(e,t)=>{const s=Date.parse(e);return Number.isFinite(s)?s:t},d=fileMtime(e.split("#")[0]);return{file:e,foreignId:o?String(o):path.basename(e).replace(/\.(jsonl|json)$/i,""),title:s||cleanText(l.content).slice(0,60)||path.basename(path.dirname(e))||"imported session",cwd:n||"",messages:c,createdAt:u(i,d),updatedAt:u(r,d)}}function extractJsonSessionDoc(e,t){if(fileSize(e)>t.maxFileBytes)return[];let s;try{s=JSON.parse(fs.readFileSync(e,"utf8"))}catch{return[]}if(!s||"object"!=typeof s)return[];const n=Array.isArray(s.messages)?s.messages:Array.isArray(s.conversation)?s.conversation:Array.isArray(s.turns)?s.turns:null;if(!n)return[];const o=[];for(const e of n){if(!e||"object"!=typeof e)continue;const s=e.role||e.type||e.author,n="assistant"===s||"model"===s||"gemini"===s||"ai"===s?"assistant":"user"===s||"human"===s?"user":null;if(!n)continue;const i=null!=e.content?e.content:e.text,r=cleanText("string"==typeof i?i:textFromClaudeMessage({content:i}));isNoise(r)||o.push({role:n,content:r.slice(0,t.maxCharsPerMessage)})}const i=finishSession({file:e,messages:o,title:cleanText(s.title||s.name||""),cwd:"string"==typeof s.cwd?s.cwd:"",foreignId:s.id||s.sessionId||path.basename(e).replace(/\.json$/i,""),first:s.createdAt||s.created_at||s.startTime||"",last:s.updatedAt||s.updated_at||s.endTime||"",opts:t});return i?[i]:[]}function openReadOnlyDb(e){if(!DatabaseSync)return null;try{return new DatabaseSync(e,{readOnly:!0})}catch{return null}}function extractOpencodeDb(e,t){const s=openReadOnlyDb(e);if(!s)return[];try{const n=s.prepare("SELECT id, title, directory, time_created, time_updated FROM session").all(),o=[];for(const i of n){const n=s.prepare("SELECT id, data FROM message WHERE session_id = ? ORDER BY time_created, id").all(i.id),r=[];for(const e of n){let n;try{n=JSON.parse(e.data)}catch{continue}const o=n&&"assistant"===n.role?"assistant":n&&"user"===n.role?"user":null;if(!o)continue;const i=cleanText(s.prepare("SELECT data FROM part WHERE message_id = ? ORDER BY time_created, id").all(e.id).map((e=>{try{const t=JSON.parse(e.data);return t&&"text"===t.type&&"string"==typeof t.text?t.text:""}catch{return""}})).filter(Boolean).join("\n"));isNoise(i)||r.push({role:o,content:i.slice(0,t.maxCharsPerMessage)})}const a=finishSession({file:`${e}#${i.id}`,messages:r,title:cleanText(i.title||""),cwd:"string"==typeof i.directory?i.directory:"",foreignId:i.id,first:i.time_created?new Date(i.time_created).toISOString():"",last:i.time_updated?new Date(i.time_updated).toISOString():"",opts:t});a&&o.push(a)}return o}finally{s.close()}}function extractCodexThreadHistoryDb(e,t){const s=openReadOnlyDb(e);if(!s)return[];try{const n=s.prepare("SELECT thread_id, item_type, item_json, created_at_ms FROM thread_items WHERE item_type IN ('userMessage','agentMessage','assistantMessage') ORDER BY thread_id, rollout_ordinal").all(),o=new Map;for(const e of n)o.has(e.thread_id)||o.set(e.thread_id,[]),o.get(e.thread_id).push(e);const i=[];for(const[s,n]of o){const o=[];let r="",a="";for(const e of n){let s;try{s=JSON.parse(e.item_json)}catch{continue}const n="userMessage"===e.item_type?"user":"assistant",i=cleanText((Array.isArray(s&&s.content)?s.content:[]).filter((e=>e&&"text"===e.type&&"string"==typeof e.text)).map((e=>e.text)).join("\n"));if(isNoise(i))continue;o.push({role:n,content:i.slice(0,t.maxCharsPerMessage)});const c=e.created_at_ms?new Date(e.created_at_ms).toISOString():"";c&&!r&&(r=c),c&&(a=c)}const c=finishSession({file:`${e}#${s}`,messages:o,title:"",cwd:"",foreignId:s,first:r,last:a,opts:t});c&&i.push(c)}return i}finally{s.close()}}const SQLITE_EXTRACTORS={opencode:extractOpencodeDb,codex:extractCodexThreadHistoryDb},SOURCES=[{id:"claude-code",label:"Claude Code",verified:!0,roots:e=>[path.join(e,".claude","projects")],extract:{".jsonl":extractClaudeSession}},{id:"claude-desktop",label:"Claude Desktop",verified:!1,roots:(e,t)=>appRoots(e,t,"Claude",{macSupport:!0}),extract:{".jsonl":extractClaudeSession,".json":extractJsonSessions}},{id:"codex",label:"OpenAI Codex CLI",verified:!0,roots:e=>[path.join(e,".codex","sessions")],sqlite:e=>[path.join(e,".codex","thread_history_1.sqlite"),path.join(e,".codex","history_1.sqlite")],extract:{".jsonl":extractCodexSession}},{id:"gemini-cli",label:"Gemini CLI",verified:!1,roots:e=>[path.join(e,".gemini","tmp")],extract:{".json":extractJsonSessionDoc,".jsonl":extractGenericSession}},{id:"opencode",label:"opencode",verified:!1,roots:(e,t)=>[...appRoots(e,t,"opencode",{data:!0}),path.join(e,".local","share","opencode")],sqlite:e=>[path.join(e,".local","share","opencode","opencode.db")],extract:{".json":extractJsonSessions,".jsonl":extractGenericSession}},{id:"cursor",label:"Cursor",verified:!1,roots:(e,t)=>[path.join(e,".cursor"),...appRoots(e,t,"Cursor",{macSupport:!0})],sqlite:(e,t)=>{const s="darwin"===t?path.join(e,"Library","Application Support","Cursor"):null,n=appRoots(e,t,"Cursor",{macSupport:!0})[0]||path.join(e,".cursor");return[s?path.join(s,"User","globalStorage","state.vscdb"):path.join(n,"User","globalStorage","state.vscdb")]},extract:{}},{id:"windsurf",label:"Windsurf / Codeium",verified:!1,roots:(e,t)=>[path.join(e,".windsurf"),path.join(e,".codeium"),...appRoots(e,t,"Windsurf",{config:!1,macSupport:!0})],extract:{".json":extractJsonSessions,".jsonl":extractGenericSession}},{id:"continue",label:"Continue",verified:!1,roots:e=>[path.join(e,".continue")],extract:{".json":extractJsonSessions,".jsonl":extractGenericSession}},{id:"goose",label:"Goose",verified:!1,roots:(e,t)=>appRoots(e,t,"goose",{data:!0}),sqlite:(e,t)=>appRoots(e,t,"goose",{data:!0}).map((e=>path.join(e,"sessions.db"))),extract:{".json":extractJsonSessions,".jsonl":extractGenericSession}},{id:"zed",label:"Zed",verified:!1,roots:(e,t)=>appRoots(e,t,"zed"),sqlite:(e,t)=>appRoots(e,t,"zed").flatMap((e=>[path.join(e,"threads","threads.db"),path.join(e,"conversations","conversations.db")])),extract:{}},{id:"kimi-code",label:"Kimi Code",verified:!1,roots:e=>[path.join(e,".kimi-code","sessions"),path.join(e,".kimi-code","history")],extract:{".jsonl":extractGenericSession,".json":extractJsonSessionDoc}},{id:"aegiscodex",label:"AEGIS Codex engine",verified:!0,roots:e=>[path.join(e,".aegiscodex","sessions"),path.join(e,".aegiscodex","history")],extract:{".jsonl":extractGenericSession,".json":extractJsonSessionDoc}}];function sourceById(e){return SOURCES.find((t=>t.id===e))||null}function listSources(e,t){const s=homeDir(e),n=platformOf(t);return SOURCES.map((e=>{const t=e.roots(s,n).filter(isDir),o=(e.sqlite?e.sqlite(s,n):[]).filter(isFile),i=o.length>0&&"function"==typeof SQLITE_EXTRACTORS[e.id];return{id:e.id,label:e.label,verified:e.verified,roots:t,databases:o,present:t.length>0||o.length>0,readable:t.length>0||i}}))}function suffixOf(e){const t=e.lastIndexOf("*");return-1===t?e:e.slice(t+1)}function extractorFor(e,t){for(const[s,n]of Object.entries(e))if(t.endsWith(suffixOf(s)))return n;return null}function scan(e={}){const t=homeDir(e.home),s=platformOf(e.platform),n=null!=e.maxSessionsPerSource?e.maxSessionsPerSource:DEFAULTS.maxSessionsPerSource,o=null!=e.limit?e.limit:1/0,i=e.sources&&e.sources.length?new Set(e.sources):null,r={minMessages:null!=e.minMessages?e.minMessages:DEFAULTS.minMessages,minChars:null!=e.minChars?e.minChars:DEFAULTS.minChars,maxCharsPerMessage:null!=e.maxCharsPerMessage?e.maxCharsPerMessage:DEFAULTS.maxCharsPerMessage,maxMessagesPerSession:null!=e.maxMessagesPerSession?e.maxMessagesPerSession:DEFAULTS.maxMessagesPerSession,maxFileBytes:null!=e.maxFileBytes?e.maxFileBytes:DEFAULTS.maxFileBytes},a=[],c=[],l=new Set;let u=0;for(const e of SOURCES){if(i&&!i.has(e.id))continue;const d=e.roots(t,s).filter(isDir),f=(e.sqlite?e.sqlite(t,s):[]).filter(isFile),p=d.length>0||f.length>0,m=Object.keys(e.extract).map(suffixOf),h=SQLITE_EXTRACTORS[e.id],g={id:e.id,label:e.label,verified:e.verified,present:p,roots:d,databases:f,files:0,scanned:0,count:0,skipped:0,unreadable:p&&!m.length&&!(f.length&&h),messages:0};if(!p){a.push(g);continue}const y=t=>{if(t.messages.length<r.minMessages)return void(g.skipped+=1);if(u+t.messages.length>DEFAULTS.maxTotalMessages)return!1;const s=stableId(e.id,t.foreignId||t.file,t.title);if(!l.has(s))return l.add(s),u+=t.messages.length,g.scanned+=1,g.count+=1,g.messages+=t.messages.length,c.push({id:s,source:e.id,sourceLabel:e.label,title:t.title,cwd:t.cwd,createdAt:t.createdAt,updatedAt:t.updatedAt,messages:t.messages,file:t.file}),!0;g.skipped+=1};if(m.length){const t=[];for(const e of d)t.push(...walkFiles(e,{ext:m,limit:DEFAULTS.maxFilesPerSource}));for(const s of t){if(g.count>=n||c.length>=o)break;if(fileSize(s)>r.maxFileBytes){g.skipped+=1;continue}const t=extractorFor(e.extract,s);if(!t)continue;let i;g.files+=1;try{i=t(s,r)}catch{g.skipped+=1;continue}const a=Array.isArray(i)?i:i?[i]:[];if(a.length)for(const e of a){if(g.count>=n||c.length>=o)break;if(!1===y(e))break}else g.skipped+=1}}if(f.length&&h)for(const e of f){if(g.count>=n||c.length>=o)break;let t;try{t=h(e,r)}catch{g.skipped+=1;continue}const s=Array.isArray(t)?t:t?[t]:[];if(g.files+=1,s.length)for(const e of s){if(g.count>=n||c.length>=o)break;if(!1===y(e))break}else g.skipped+=1}a.push(g)}return{sessions:c,sources:a,totals:{sessions:c.length,sourcesPresent:a.filter((e=>e.present)).length,sourcesWithSessions:a.filter((e=>e.count>0)).length,sourcesUnreadable:a.filter((e=>e.unreadable)).length,files:a.reduce(((e,t)=>e+t.files),0),messages:u,skipped:a.reduce(((e,t)=>e+t.skipped),0)},scannedAt:(new Date).toISOString()}}function toRecord(e,{pending:t=!1}={}){const s=(Array.isArray(e.messages)?e.messages:[]).map(((t,s)=>({role:"assistant"===t.role?"assistant":"user",content:String(null==t.content?"":t.content),at:0===s?e.createdAt||e.updatedAt||Date.now():void 0})));for(const e of s)null==e.at&&delete e.at;return{id:e.id,title:e.title||"imported session",messages:s,createdAt:e.createdAt||e.updatedAt||Date.now(),updatedAt:e.updatedAt||e.createdAt||Date.now(),origin:`import:${e.source}`,importedFrom:{source:e.source,label:e.sourceLabel,file:e.file,at:(new Date).toISOString()},pending:!0===t}}function chunk(e,t=50){const s=[];for(let n=0;n<e.length;n+=t)s.push(e.slice(n,n+t));return s}function describe(e){const t=(e.sources||[]).filter((e=>e.present));if(!t.length)return"No other AI tool sessions found on this machine.";const s=t.map((e=>{if(e.unreadable)return` ${e.label}: found, but its store is a database this version cannot read`;const t=e.verified?"":" (best-effort layout)";return` ${e.label}${t}: ${e.count} session(s) from ${e.files} file(s), ${e.skipped} skipped`}));return[`Found ${e.totals.sessions} importable session(s) across ${e.totals.sourcesWithSessions} source(s):`,...s].join("\n")}module.exports={DEFAULTS:DEFAULTS,SOURCES:SOURCES,scan:scan,listSources:listSources,describe:describe,chunk:chunk,toRecord:toRecord,stableId:stableId,sourceById:sourceById,_internal:{walkFiles:walkFiles,readJsonl:readJsonl,cleanText:cleanText,isNoise:isNoise,finishSession:finishSession,extractClaudeSession:extractClaudeSession,extractCodexSession:extractCodexSession,extractGenericSession:extractGenericSession,extractJsonSessions:extractJsonSessions,extractJsonSessionDoc:extractJsonSessionDoc,extractorFor:extractorFor,suffixOf:suffixOf,platformOf:platformOf,appRoots:appRoots}};
|
package/vendor/client/naming.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const GENERIC_TITLE="New conversation",TITLE_SYSTEM='You name conversations. Write a short descriptive title (2 to 6 words) that captures the topic of the conversation. Never repeat the user\'s words verbatim — if the message is just a greeting or has no clear topic, name it something like "New conversation". Sentence case, no quotes, no markdown, no trailing punctuation, no explanation.',isGenericTitle=e=>!e||String(e).trim().toLowerCase()===GENERIC_TITLE.toLowerCase(),GREETINGS=new Set(["hey","heey","heyy","heyyy","hi","hii","hello","hej","hejj","yo","sup","hola","howdy","hai","heyo","hiya","wassup","greetings","namaste","ahoy","hallo"]);function isTopicless(e){const t=String(e).trim().toLowerCase().replace(/[^a-z0-9\s]/g," ").replace(/\s+/g," ").trim();if(!t)return!0;const i=t.split(" ");return!!/^(good (morning|afternoon|evening)|whats up|wassup|hey there|hello there|hi there|how are you)\b/.test(t)||i.length<=2&&t.length<=12&&GREETINGS.has(i[0])}function looksLikeEcho(e,t){const i=e=>String(e).toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim(),n=i(e),o=i(t);if(!n||!o)return!1;if(n===o)return!0;if(o.length<=14&&(n.startsWith(o)||o.startsWith(n)))return!0;if(o.length<=24){const i=e=>new Set((String(e).toLowerCase().match(/[a-z0-9]+/g)||[]).filter((e=>!ECHO_STOP.has(e)))),n=i(e),o=i(t);if(n.size&&n.size===o.size&&[...n].every((e=>o.has(e))))return!0}return!1}const ECHO_STOP=new Set(["the","a","an","to","of","in","on","at","for","and","or","is","are","be","it","its","my","our","please","can","you","just","do","that","this"]);function cleanTitle(e){return String(null==e?"":e).replace(/\s+/g," ").trim().replace(/["'`“”‘’]/g,"").replace(/[*_#]/g,"").replace(/^\s*(?:title|name)\s*[:\-–]\s*/i,"").replace(/[.\s]+$/g,"").slice(0,60).trim()}const titlePromptOf=e=>`Write a short title for a conversation that begins with: "${String(e).slice(0,500)}"`,FILLER=/^(?:please|pls|plz|hey|hi|hello|ok(?:ay)?|so|now|just|also|and|then|maybe|well|um|uh|can you|could you|would you|will you|i want you to|i want to|i need you to|i need to|i'?d like you to|i would like you to|i'?d like to|help me|help|let'?s|lets|go ahead and)\b[\s,:;-]*/i,TRAILING_STOP=new Set(["the","a","an","in","on","at","to","for","of","and","or","with","is","are","my","our","this","that","please","can","you","could","would","i","we","just","do","it"]);function deriveTitle(e){let t=String(null==e?"":e).trim().replace(/\s+/g," ");if(!t)return GENERIC_TITLE;for(let e=0;e<6;e++){const e=t.replace(FILLER,"").trim();if(e===t)break;t=e}const i=t.split(" ").filter(Boolean);if(!i.length)return GENERIC_TITLE;const n=i.slice(0,6);for(;n.length>2&&TRAILING_STOP.has(n[n.length-1].toLowerCase().replace(/[^a-z0-9]/g,""));)n.pop();let o=n.join(" ").replace(/[.,!?;:]+$/,"").trim();return o?(o=o[0].toUpperCase()+o.slice(1),o.slice(0,60).trim()||GENERIC_TITLE):GENERIC_TITLE}async function nameConversation(e,{callModel:t,signal:i}={}){const n=null==e?"":String(e);if(!n.trim())return"";if(isTopicless(n))return GENERIC_TITLE;if(!("function"!=typeof t||i&&i.aborted)){let e=null;try{e=await t(titlePromptOf(n),{system:TITLE_SYSTEM,signal:i,naming:!0})}catch{e=null}const o=cleanTitle(e);if(o)return looksLikeEcho(o,n)?GENERIC_TITLE:o}return deriveTitle(n)}async function refineTitle(e,t,i={}){const n=i&&!0===i.named,o=i&&!0===i.seeded;if(n)return null;if(!o&&!isGenericTitle(e))return null;if(!String(t||"").trim()||isTopicless(t))return null;const r=cleanTitle(await nameConversation(t,i));return!r||isGenericTitle(r)?null:r}async function nameSession(e,t,i,n,o={}){if(!e||"function"!=typeof e.setTitle)return null;if(!i)return null;const r="function"==typeof e.getSession?e.getSession(t,i):null,s=r&&r.title,l
|
|
3
|
+
"use strict";const GENERIC_TITLE="New conversation",TITLE_SYSTEM='You name conversations. Write a short descriptive title (2 to 6 words) that captures the topic of the conversation. Never repeat the user\'s words verbatim — if the message is just a greeting or has no clear topic, name it something like "New conversation". Sentence case, no quotes, no markdown, no trailing punctuation, no explanation.',isGenericTitle=e=>!e||String(e).trim().toLowerCase()===GENERIC_TITLE.toLowerCase(),GREETINGS=new Set(["hey","heey","heyy","heyyy","hi","hii","hello","hej","hejj","yo","sup","hola","howdy","hai","heyo","hiya","wassup","greetings","namaste","ahoy","hallo"]);function isTopicless(e){const t=String(e).trim().toLowerCase().replace(/[^a-z0-9\s]/g," ").replace(/\s+/g," ").trim();if(!t)return!0;const i=t.split(" ");return!!/^(good (morning|afternoon|evening)|whats up|wassup|hey there|hello there|hi there|how are you)\b/.test(t)||i.length<=2&&t.length<=12&&GREETINGS.has(i[0])}function looksLikeEcho(e,t){const i=e=>String(e).toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim(),n=i(e),o=i(t);if(!n||!o)return!1;if(n===o)return!0;if(o.length<=14&&(n.startsWith(o)||o.startsWith(n)))return!0;if(o.length<=24){const i=e=>new Set((String(e).toLowerCase().match(/[a-z0-9]+/g)||[]).filter((e=>!ECHO_STOP.has(e)))),n=i(e),o=i(t);if(n.size&&n.size===o.size&&[...n].every((e=>o.has(e))))return!0}return!1}const ECHO_STOP=new Set(["the","a","an","to","of","in","on","at","for","and","or","is","are","be","it","its","my","our","please","can","you","just","do","that","this"]);function cleanTitle(e){return String(null==e?"":e).replace(/\s+/g," ").trim().replace(/["'`“”‘’]/g,"").replace(/[*_#]/g,"").replace(/^\s*(?:title|name)\s*[:\-–]\s*/i,"").replace(/[.\s]+$/g,"").slice(0,60).trim()}const titlePromptOf=e=>`Write a short title for a conversation that begins with: "${String(e).slice(0,500)}"`,FILLER=/^(?:please|pls|plz|hey|hi|hello|ok(?:ay)?|so|now|just|also|and|then|maybe|well|um|uh|can you|could you|would you|will you|i want you to|i want to|i need you to|i need to|i'?d like you to|i would like you to|i'?d like to|help me|help|let'?s|lets|go ahead and)\b[\s,:;-]*/i,TRAILING_STOP=new Set(["the","a","an","in","on","at","to","for","of","and","or","with","is","are","my","our","this","that","please","can","you","could","would","i","we","just","do","it"]);function deriveTitle(e){let t=String(null==e?"":e).trim().replace(/\s+/g," ");if(!t)return GENERIC_TITLE;for(let e=0;e<6;e++){const e=t.replace(FILLER,"").trim();if(e===t)break;t=e}const i=t.split(" ").filter(Boolean);if(!i.length)return GENERIC_TITLE;const n=i.slice(0,6);for(;n.length>2&&TRAILING_STOP.has(n[n.length-1].toLowerCase().replace(/[^a-z0-9]/g,""));)n.pop();let o=n.join(" ").replace(/[.,!?;:]+$/,"").trim();return o?(o=o[0].toUpperCase()+o.slice(1),o.slice(0,60).trim()||GENERIC_TITLE):GENERIC_TITLE}async function nameConversation(e,{callModel:t,signal:i}={}){const n=null==e?"":String(e);if(!n.trim())return"";if(isTopicless(n))return GENERIC_TITLE;if(!("function"!=typeof t||i&&i.aborted)){let e=null;try{e=await t(titlePromptOf(n),{system:TITLE_SYSTEM,signal:i,naming:!0})}catch{e=null}const o=cleanTitle(e);if(o)return looksLikeEcho(o,n)?GENERIC_TITLE:o}return deriveTitle(n)}async function refineTitle(e,t,i={}){const n=i&&!0===i.named,o=i&&!0===i.seeded;if(n)return null;if(!o&&!isGenericTitle(e))return null;if(!String(t||"").trim()||isTopicless(t))return null;const r=cleanTitle(await nameConversation(t,i));return!r||isGenericTitle(r)?null:r}async function nameSession(e,t,i,n,o={}){if(!e||"function"!=typeof e.setTitle)return null;if(!i)return null;const r="function"==typeof e.getSession?e.getSession(t,i):null,s=r&&r.title,l=!(!r||r.named);if(l&&s&&!isGenericTitle(s)&&!looksLikeEcho(s,n)){try{e.setTitle(t,i,s,{named:!0})}catch{return null}return null}const a={...o,seeded:l},c=await refineTitle(s,n,a);if(c){try{e.setTitle(t,i,c,{named:!0})}catch{return null}return c}if(isTopicless(n)&&r&&!r.named&&!isGenericTitle(s)){try{e.setTitle(t,i,GENERIC_TITLE)}catch{return null}return GENERIC_TITLE}return null}module.exports={GENERIC_TITLE:GENERIC_TITLE,TITLE_SYSTEM:TITLE_SYSTEM,isGenericTitle:isGenericTitle,isTopicless:isTopicless,looksLikeEcho:looksLikeEcho,cleanTitle:cleanTitle,titlePromptOf:titlePromptOf,deriveTitle:deriveTitle,nameConversation:nameConversation,refineTitle:refineTitle,nameSession:nameSession};
|
package/vendor/client/prefs.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),PREFS_FILE="preferences.json",PREFS_VERSION=1,SHARED_PREF_KEYS=Object.freeze(["themeIndex","model","modelClass","currentModelId","models","effort","vim","memoryPersist","confirmMode"]),LEGACY_MEMORY_PERSIST_NAMESPACE="__memoryPersist",LEGACY_CONFIRM_MODE_NAMESPACE="__confirmMode",SECRET_KEY_RE=/(^|[^a-z0-9])(api[_-]?key|apikey|key|keys|token|secret|password|passwd|credential|credentials|authorization|bearer|private[_-]?key|access[_-]?key|session[_-]?key)([^a-z0-9]|$)/i,SECRET_VALUE_RES=[/\baegis_[A-Za-z0-9_\-]{12,}/,/\bsk-[A-Za-z0-9_\-]{12,}/,/\bghp_[A-Za-z0-9_\-]{20,}/,/\bxox[baprs]-[A-Za-z0-9\-]{10,}/,/\beyJ[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{8,}/,/^[A-Za-z0-9+/]{48,}={0,2}$/];function prefsDir(e){const r=e||{};return r.dir&&String(r.dir).trim()?path.resolve(String(r.dir).trim()):aegisHome(r.env)}function prefsFile(e){const r=e||{};return r.file&&String(r.file).trim()?path.resolve(String(r.file).trim()):path.join(prefsDir(r),PREFS_FILE)}function scanForSecrets(e,r="",t=[]){if(null==e)return t;if("string"==typeof e)return SECRET_VALUE_RES.some((r=>r.test(e)))&&t.push(r||"(root)"),t;if("object"!=typeof e)return t;if(Array.isArray(e))return e.forEach(((e,o)=>scanForSecrets(e,`${r}[${o}]`,t))),t;for(const[o,s]of Object.entries(e)){const e=r?`${r}.${o}`:o;SECRET_KEY_RE.test(o)&&null!=s&&""!==s&&!1!==s?t.push(e):scanForSecrets(s,e,t)}return t}function assertNoSecrets(e,r="shared preference store"){const t=scanForSecrets(e);if(t.length)throw new Error(`${r} must not carry key material — refusing to write (found: ${t.join(", ")}). Secrets belong in the host-local credential store, where the OS can protect them.`);return e}function readJson(e,r){try{const t=JSON.parse(fs.readFileSync(e,"utf8"));return t&&"object"==typeof t&&!Array.isArray(t)?t:r}catch{return r}}function load(e){return readJson(prefsFile(e),{})}function write(e,r){assertNoSecrets(e);const t=prefsFile(r);fs.mkdirSync(path.dirname(t),{recursive:!0});const o=`${t}.tmp-${process.pid}`;fs.writeFileSync(o,JSON.stringify(e,null,2)+"\n",{mode:384}),fs.renameSync(o,t);try{fs.chmodSync(t,384)}catch{}return e}function set(e,r){const t={...load(r),...e||{}};for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return void 0===t.version&&(t.version=1),write(t,r)}function get(e,r,t){const o=load(r)[e];return void 0===o?t:o}function has(e,r){return void 0!==load(r)[e]}function remove(e,r){const t=load(r);return delete t[e],write(t,r)}function extractNonSecretHalf(e){const r={},t=(e||{})[LEGACY_MEMORY_PERSIST_NAMESPACE];t&&"object"==typeof t&&"boolean"==typeof t.enabled&&(r.memoryPersist=t.enabled);const o=(e||{})[LEGACY_CONFIRM_MODE_NAMESPACE];return o&&"object"==typeof o&&"boolean"==typeof o.enabled&&(r.confirmMode=o.enabled),r}function adopt(e){const r=e||{},t=prefsFile(r),o=r.legacyDir,s=o?path.join(String(o),"settings.json"):null;if(s&&path.resolve(s)===t)return{adopted:!1,keys:[],from:s,reason:"shared store is the legacy file"};if(!s||!fs.existsSync(s))return{adopted:!1,keys:[],from:s,reason:"no legacy settings file"};const n=load(r),
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),PREFS_FILE="preferences.json",PREFS_VERSION=1,SHARED_PREF_KEYS=Object.freeze(["themeIndex","model","modelClass","currentModelId","models","effort","vim","memoryPersist","confirmMode","permissionMode","sandboxPolicy"]),LEGACY_MEMORY_PERSIST_NAMESPACE="__memoryPersist",LEGACY_CONFIRM_MODE_NAMESPACE="__confirmMode",SECRET_KEY_RE=/(^|[^a-z0-9])(api[_-]?key|apikey|key|keys|token|secret|password|passwd|credential|credentials|authorization|bearer|private[_-]?key|access[_-]?key|session[_-]?key)([^a-z0-9]|$)/i,SECRET_VALUE_RES=[/\baegis_[A-Za-z0-9_\-]{12,}/,/\bsk-[A-Za-z0-9_\-]{12,}/,/\bghp_[A-Za-z0-9_\-]{20,}/,/\bxox[baprs]-[A-Za-z0-9\-]{10,}/,/\beyJ[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{8,}/,/^[A-Za-z0-9+/]{48,}={0,2}$/];function prefsDir(e){const r=e||{};return r.dir&&String(r.dir).trim()?path.resolve(String(r.dir).trim()):aegisHome(r.env)}function prefsFile(e){const r=e||{};return r.file&&String(r.file).trim()?path.resolve(String(r.file).trim()):path.join(prefsDir(r),PREFS_FILE)}function scanForSecrets(e,r="",t=[]){if(null==e)return t;if("string"==typeof e)return SECRET_VALUE_RES.some((r=>r.test(e)))&&t.push(r||"(root)"),t;if("object"!=typeof e)return t;if(Array.isArray(e))return e.forEach(((e,o)=>scanForSecrets(e,`${r}[${o}]`,t))),t;for(const[o,s]of Object.entries(e)){const e=r?`${r}.${o}`:o;SECRET_KEY_RE.test(o)&&null!=s&&""!==s&&!1!==s?t.push(e):scanForSecrets(s,e,t)}return t}function assertNoSecrets(e,r="shared preference store"){const t=scanForSecrets(e);if(t.length)throw new Error(`${r} must not carry key material — refusing to write (found: ${t.join(", ")}). Secrets belong in the host-local credential store, where the OS can protect them.`);return e}function readJson(e,r){try{const t=JSON.parse(fs.readFileSync(e,"utf8"));return t&&"object"==typeof t&&!Array.isArray(t)?t:r}catch{return r}}function load(e){return readJson(prefsFile(e),{})}function write(e,r){assertNoSecrets(e);const t=prefsFile(r);fs.mkdirSync(path.dirname(t),{recursive:!0});const o=`${t}.tmp-${process.pid}`;fs.writeFileSync(o,JSON.stringify(e,null,2)+"\n",{mode:384}),fs.renameSync(o,t);try{fs.chmodSync(t,384)}catch{}return e}function set(e,r){const t={...load(r),...e||{}};for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return void 0===t.version&&(t.version=1),write(t,r)}function get(e,r,t){const o=load(r)[e];return void 0===o?t:o}function has(e,r){return void 0!==load(r)[e]}function remove(e,r){const t=load(r);return delete t[e],write(t,r)}function extractNonSecretHalf(e){const r={},t=(e||{})[LEGACY_MEMORY_PERSIST_NAMESPACE];t&&"object"==typeof t&&"boolean"==typeof t.enabled&&(r.memoryPersist=t.enabled);const o=(e||{})[LEGACY_CONFIRM_MODE_NAMESPACE];return o&&"object"==typeof o&&"boolean"==typeof o.enabled&&(r.confirmMode=o.enabled),r}function adopt(e){const r=e||{},t=prefsFile(r),o=r.legacyDir,s=o?path.join(String(o),"settings.json"):null;if(s&&path.resolve(s)===t)return{adopted:!1,keys:[],from:s,reason:"shared store is the legacy file"};if(!s||!fs.existsSync(s))return{adopted:!1,keys:[],from:s,reason:"no legacy settings file"};const n=load(r),i=extractNonSecretHalf(readJson(s,{})),a=Object.keys(i).filter((e=>void 0===n[e]));if(!a.length)return{adopted:!1,keys:[],from:s,reason:Object.keys(i).length?"shared store already carries these preferences":"legacy store has no shared preferences"};const c={};for(const e of a)c[e]=i[e];return c.adopted={from:s,at:(new Date).toISOString(),names:a.slice().sort()},write({...n,...c},r),{adopted:!0,keys:a.slice().sort(),from:s}}module.exports={PREFS_FILE:PREFS_FILE,PREFS_VERSION:1,SHARED_PREF_KEYS:SHARED_PREF_KEYS,LEGACY_MEMORY_PERSIST_NAMESPACE:LEGACY_MEMORY_PERSIST_NAMESPACE,prefsDir:prefsDir,prefsFile:prefsFile,load:load,set:set,get:get,has:has,remove:remove,scanForSecrets:scanForSecrets,assertNoSecrets:assertNoSecrets,extractNonSecretHalf:extractNonSecretHalf,adopt:adopt};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";function haystack(e){if(!e||"object"!=typeof e)return"";const t=[e.title,e.summary,e.cwd,e.id].filter((e=>"string"==typeof e&&e)),s=Array.isArray(e.messages)?e.messages:[];for(const e of s)if(e&&"user"===e.role&&"string"==typeof e.content&&e.content){t.push(e.content.slice(0,400));break}return t.join("\n")}function scoreSession(e,t){const s=String(e||"").trim().toLowerCase();if(!s)return{matched:!0,score:0,field:"all"};const r="string"==typeof(t&&t.title)?t.title.toLowerCase():"",n=haystack(t).toLowerCase();if(r&&r===s)return{matched:!0,score:1e3,field:"title"};if(r&&r.startsWith(s))return{matched:!0,score:900,field:"title"};const o=r?r.indexOf(s):-1;if(-1!==o)return{matched:!0,score:700-o,field:"title"};const i=n.indexOf(s);if(-1!==i)return{matched:!0,score:Math.max(1,400-i),field:"body"};if(r){let e=100,t=-2,n=-1,o=!0;for(const i of s){const s=r.indexOf(i,n+1);if(-1===s){o=!1;break}e+=s===t+1?15:5,0===s&&(e+=20),t=s,n=s}if(o)return{matched:!0,score:e,field:"title"}}return{matched:!1,score:0,field:null}}function rankSessions(e,t){const s=Array.isArray(t)?t:[],r=String(e||"").trim();if(!r)return s.slice();const n=[];for(let e=0;e<s.length;e+=1){const t=s[e],o=scoreSession(r,t);o.matched&&n.push({s:t,i:e,score:o.score})}return n.sort(((e,t)=>t.score-e.score||e.i-t.i)),n.map((e=>e.s))}function matchReason(e,t){const s=String(e||"").trim();if(!s)return null;const r=scoreSession(s,t);return r.matched?"title"===r.field?"title":"body"===r.field?"content":null:null}module.exports={haystack:haystack,scoreSession:scoreSession,rankSessions:rankSessions,matchReason:matchReason};
|