aegiscode 7.0.24 → 7.0.26

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.
Files changed (113) hide show
  1. package/package.json +7 -3
  2. package/scripts/check.mjs +52 -1
  3. package/scripts/demo.mjs +94 -1
  4. package/scripts/predist.mjs +75 -1
  5. package/scripts/runtests.mjs +56 -1
  6. package/scripts/seal-gate.mjs +74 -1
  7. package/src/agents.js +139 -1
  8. package/src/app.js +2957 -1
  9. package/src/art.js +289 -1
  10. package/src/chatflow.js +3023 -1
  11. package/src/checkpoint.js +90 -1
  12. package/src/clipboard.js +424 -1
  13. package/src/cloudsync.js +528 -1
  14. package/src/commands.js +4089 -1
  15. package/src/config.js +581 -1
  16. package/src/connect.js +349 -1
  17. package/src/credentials.js +33 -1
  18. package/src/deps.js +232 -1
  19. package/src/devrun.js +187 -1
  20. package/src/diff.js +333 -1
  21. package/src/diffview.js +296 -1
  22. package/src/engine.js +297 -1
  23. package/src/entitlement.js +355 -1
  24. package/src/events.js +707 -1
  25. package/src/export.js +67 -1
  26. package/src/filepreview.js +153 -1
  27. package/src/fingerprint.js +592 -1
  28. package/src/format.js +259 -1
  29. package/src/fuzzy.js +119 -1
  30. package/src/history.js +423 -1
  31. package/src/init.js +175 -1
  32. package/src/input.js +139 -1
  33. package/src/keys.js +183 -1
  34. package/src/markdown.js +306 -1
  35. package/src/models.js +507 -1
  36. package/src/naming.js +57 -1
  37. package/src/overlays.js +462 -1
  38. package/src/panels.js +1418 -1
  39. package/src/ping.js +226 -1
  40. package/src/presence.js +238 -1
  41. package/src/render.js +516 -1
  42. package/src/screen.js +518 -1
  43. package/src/screens.js +896 -1
  44. package/src/secret.js +59 -1
  45. package/src/securefs.js +359 -1
  46. package/src/settings.js +155 -1
  47. package/src/shared.js +52 -1
  48. package/src/sharedpaths.js +53 -1
  49. package/src/signup.js +156 -1
  50. package/src/summarize.js +95 -1
  51. package/src/sysdiag.js +585 -1
  52. package/src/system.js +40 -1
  53. package/src/theme.js +570 -1
  54. package/src/title.js +220 -1
  55. package/src/todos.js +115 -1
  56. package/src/tokens.js +263 -1
  57. package/src/topup.js +210 -1
  58. package/src/update.js +191 -1
  59. package/vendor/client/aegis.js +2441 -1
  60. package/vendor/client/attest.js +518 -1
  61. package/vendor/client/authorship-key.js +410 -1
  62. package/vendor/client/auto-provision.js +134 -1
  63. package/vendor/client/brain-catalog.js +268 -1
  64. package/vendor/client/byok-catalog.js +199 -1
  65. package/vendor/client/catalog-client.js +487 -1
  66. package/vendor/client/conversation-export.js +177 -1
  67. package/vendor/client/credentials.js +494 -1
  68. package/vendor/client/device-fingerprint.js +141 -1
  69. package/vendor/client/drive-connect.js +110 -1
  70. package/vendor/client/drive-upload.js +234 -1
  71. package/vendor/client/env-file.js +1273 -1
  72. package/vendor/client/fingerprint.js +1064 -1
  73. package/vendor/client/foreign-memory.js +669 -1
  74. package/vendor/client/google-signin.js +133 -1
  75. package/vendor/client/hooks.js +430 -1
  76. package/vendor/client/model-discovery.js +373 -1
  77. package/vendor/client/naming.js +283 -1
  78. package/vendor/client/platform.js +937 -1
  79. package/vendor/client/prefs.js +351 -1
  80. package/vendor/client/presence-constants.js +107 -1
  81. package/vendor/client/presence.js +438 -1
  82. package/vendor/client/record-vault.js +1055 -3
  83. package/vendor/client/session-store.js +575 -1
  84. package/vendor/client/topup.js +297 -1
  85. package/vendor/client/touch.js +458 -1
  86. package/vendor/client/update.js +763 -1
  87. package/vendor/client/user-models.js +381 -1
  88. package/vendor/desktop/lib/local/agents.js +105 -1
  89. package/vendor/desktop/lib/local/attachments.js +276 -1
  90. package/vendor/desktop/lib/local/autonomous.js +1045 -1
  91. package/vendor/desktop/lib/local/claude-pro.js +1028 -1
  92. package/vendor/desktop/lib/local/context.js +125 -1
  93. package/vendor/desktop/lib/local/engine.js +3666 -1
  94. package/vendor/desktop/lib/local/entitlement.js +660 -1
  95. package/vendor/desktop/lib/local/git-scope.js +228 -1
  96. package/vendor/desktop/lib/local/local.js +2145 -1
  97. package/vendor/desktop/lib/local/prompt.js +280 -1
  98. package/vendor/desktop/lib/local/queue.js +560 -1
  99. package/vendor/desktop/lib/local/session-rounds.js +238 -1
  100. package/vendor/desktop/lib/local/spill.js +75 -1
  101. package/vendor/desktop/lib/local/turn-guard.js +300 -1
  102. package/vendor/desktop/lib/local/worktree-lock.js +235 -1
  103. package/vendor/desktop/lib/settings.js +890 -1
  104. package/vendor/desktop/renderer/usage.js +1239 -1
  105. package/vendor/hosts/install.js +638 -1
  106. package/vendor/hosts/openai-shim.js +515 -1
  107. package/vendor/hosts/spec.js +164 -1
  108. package/vendor/hosts/targets.js +346 -1
  109. package/vendor/mcp/server.js +221 -1
  110. package/vendor/mcp/tools.js +408 -1
  111. package/vendor/one/src/child.js +285 -1
  112. package/vendor/one/src/permissions.js +383 -1
  113. package/SOURCE-OFFER.txt +0 -9
package/src/panels.js CHANGED
@@ -1,3 +1,1420 @@
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
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
+ 'use strict';
7
+
8
+ /**
9
+ * Panel builders — the bodies that slash-commands print.
10
+ *
11
+ * Ported from the upstream engine reference (868 lines), keeping its layouts
12
+ * and copy wherever the capability exists in this client. Everything here is
13
+ * PURE: a builder receives all of its data as arguments and returns an array of
14
+ * span lines (each line an array of `{ t, s, w }`, see `screen.js`). No stdout
15
+ * writes, no `process.exit`, no network, no filesystem reads — which is exactly
16
+ * what makes them assertable from a plain Node test with no TTY.
17
+ *
18
+ * Style objects come from `themeOf(ctx)` (`ctx = { light }`), never a
19
+ * module-scoped palette. Money is euro: `fmtEur` renders 4dp below a cent (a
20
+ * pooled call settles near €0.0007) and 2dp at or above it, so a real charge
21
+ * never reads as "€0.00". The reference printed USD; every `$` became `€`.
22
+ * Claude/Anthropic names became AEGIS (`aegiscode`, `aegiscloud.org`)
23
+ * and `~/.aegiscodex` became
24
+ * `~/.aegiscode`.
25
+ *
26
+ * Every builder is defensive: a missing field is omitted, never rendered as
27
+ * `undefined`, `NaN` or `[object Object]`.
28
+ *
29
+ * ── Ported for real ──────────────────────────────────────────────────────────
30
+ * buildHelp buildStatus buildCost buildContext buildTokens buildAgents
31
+ * renderSessionsOverlay buildPermissions buildModelList buildRewindList
32
+ * buildOnboarding buildShellCompletion buildTerminalSetup buildPRs
33
+ * buildBenchmark buildWaifu buildAegisStatus buildAegisRecall buildAegisMulti
34
+ * buildBilling buildMemory buildMemoryTiers buildRouter buildAutomode buildSkills
35
+ * buildMcp buildHooksStatus buildHooksList buildTroubleshooting
36
+ * buildReleaseNotes
37
+ * (plus the pure reference helpers with no missing capability)
38
+ * buildAegisPrint buildSkillDetail buildMemoryEmbeddings
39
+ *
40
+ * ── Honest stubs (capability absent in this client) ──────────────────────────
41
+ * buildDoctor — needs the local environment diagnostic suite (runDoctor),
42
+ * which belongs to the upstream engine; /doctor is unavailable.
43
+ * buildBuildPanel — needs a local multi-model agent build loop this client
44
+ * does not host.
45
+ */
46
+
47
+ const { span, getSize, lineWidth } = require('./screen.js');
48
+ const { themeOf, BOLD, BOLD_OFF, GLYPH } = require('./theme.js');
49
+ // Pure, like this module (signup.js requires nothing and does no I/O), so the
50
+ // "everything here is assertable from a plain Node test" contract still holds.
51
+ const { goUrl } = require('./signup.js');
52
+ // Path NAMES for the session overlay — the shared rule, not a second `split('/')`
53
+ // (which reported the whole path on win32). See format.js's path section.
54
+ const { cwdName, pathName } = require('./format.js');
55
+
56
+ const VERSION = require('../package.json').version;
57
+
58
+ // ── local helpers (this file stays self-contained apart from theme/screen) ────
59
+
60
+ /** Finite number or 0 — never NaN (which would print as "NaN"). */
61
+ function num(v) {
62
+ const n = Number(v);
63
+ return Number.isFinite(n) ? n : 0;
64
+ }
65
+
66
+ /** A safe display string: null/undefined become '', everything else String()s. */
67
+ function str(v) {
68
+ return v == null ? '' : String(v);
69
+ }
70
+
71
+ /**
72
+ * Word-wrap one sentence into span rows, indented, so a long claim survives
73
+ * `padLine()`.
74
+ *
75
+ * Local rather than imported on purpose (see the header: this file stays
76
+ * self-contained apart from theme/screen). `screens.js` has a `wrapped()` that
77
+ * does the same job, but it lives behind the screen-drawing module, which
78
+ * requires this one — importing it here would close a require cycle to reuse
79
+ * fifteen lines.
80
+ *
81
+ * Anything one word longer than the terminal is emitted on its own row rather
82
+ * than dropped: `padLine()` clips it, which is what already happens today, and
83
+ * losing a word is better than losing the sentence.
84
+ */
85
+ function wrapRows(text, indent, style, cols) {
86
+ const width = Math.max(20, (Number(cols) || 80) - 2 - indent);
87
+ const pad = ' '.repeat(indent);
88
+ const words = str(text).split(/\s+/).filter(Boolean);
89
+ const out = [];
90
+ let line = '';
91
+ for (const word of words) {
92
+ const next = line ? `${line} ${word}` : word;
93
+ if (line && next.length > width) {
94
+ out.push([span('', pad), span(style, line)]);
95
+ line = word;
96
+ } else {
97
+ line = next;
98
+ }
99
+ }
100
+ if (line) out.push([span('', pad), span(style, line)]);
101
+ return out.length ? out : [[span('', pad), span(style, '')]];
102
+ }
103
+
104
+ /**
105
+ * The four token buckets these panels render, in the shared shape.
106
+ *
107
+ * `input` is the MISS half only — that is what `usageBuckets` normalises it to
108
+ * for every provider, and what the ledger rows and the desktop roll store — so
109
+ * the prompt a context window actually holds is `input + cacheRead +
110
+ * cacheWrite`, NOT `input` alone. Totalling `input + output` (what this file
111
+ * did before) therefore silently dropped the entire cached prompt: the exact
112
+ * turns where the cache was working and the context was largest were the turns
113
+ * the meter under-reported.
114
+ *
115
+ * `tok.total` wins when a caller supplies one (the live session tally does), so
116
+ * this fallback can only ever add information, never overwrite it. One formula,
117
+ * one place: /cost, /context and /tokens must not disagree about the same turn.
118
+ */
119
+ function tokenBuckets(tok) {
120
+ const input = num(tok.input);
121
+ const output = num(tok.output);
122
+ const cacheRead = num(tok.cacheRead);
123
+ const cacheWrite = num(tok.cacheWrite);
124
+ const prompt = input + cacheRead + cacheWrite;
125
+ return { input, output, cacheRead, cacheWrite, prompt, total: num(tok.total) || prompt + output };
126
+ }
127
+
128
+ /** Group digits: 1562 -> "1,562". Matches the CLI's format.js rule. */
129
+ function fmtTokens(n) {
130
+ const v = Number(n);
131
+ if (!Number.isFinite(v) || v <= 0) return '0';
132
+ return Math.round(v)
133
+ .toString()
134
+ .replace(/\B(?=(\d{3})+(?!\d))/g, ',');
135
+ }
136
+
137
+ /** € amount, 4dp below a cent (per-call spend) and 2dp at or above it. */
138
+ function fmtEur(n) {
139
+ const v = Number(n);
140
+ if (!Number.isFinite(v)) return '€?';
141
+ const abs = Math.abs(v);
142
+ return `€${abs < 0.01 ? abs.toFixed(4) : abs.toFixed(2)}`;
143
+ }
144
+
145
+ /** Relative-time stamp, ported verbatim from the reference's `ago()`. */
146
+ function ago(ts) {
147
+ if (!ts) return '';
148
+ const ms = Date.now() - new Date(String(ts)).getTime();
149
+ if (!(ms >= 0) || Number.isNaN(ms)) return '';
150
+ if (ms < 60_000) return `${Math.max(1, Math.round(ms / 1000))}s ago`;
151
+ if (ms < 3_600_000) return `${Math.round(ms / 60_000)}m ago`;
152
+ if (ms < 86_400_000) return `${Math.round(ms / 3_600_000)}h ago`;
153
+ return `${Math.round(ms / 86_400_000)}d ago`;
154
+ }
155
+
156
+ /** A `█`-filled progress bar as a span line (the reference's contextBar). */
157
+ function contextBar(used, window, t, width = 50) {
158
+ const pct = Math.max(0, Math.min(1, window > 0 ? num(used) / window : 0));
159
+ const filled = Math.round(pct * width);
160
+ return [
161
+ span('', ' '),
162
+ span(t.green, '█'.repeat(filled)),
163
+ span(t.dim, '█'.repeat(Math.max(0, width - filled))),
164
+ span(t.gray, ` ${Math.round(pct * 100)}% used`),
165
+ ];
166
+ }
167
+
168
+ /** Aligned key/value rows, the reference's `k + ' '.repeat(maxK-len) + ' : '`. */
169
+ function kv(t, rows, { indent = ' ', keyStyle = null, valStyle = null } = {}) {
170
+ const maxK = rows.reduce((m, r) => Math.max(m, [...r[0]].length), 0);
171
+ return rows.map(([k, v]) => [
172
+ span(keyStyle != null ? keyStyle : t.gray, indent + k + ' '.repeat(maxK - [...k].length) + ' : '),
173
+ span(valStyle != null ? valStyle : t.white, str(v)),
174
+ ]);
175
+ }
176
+
177
+ /** The `state` argument, guaranteed to be an object. */
178
+ function obj(state) {
179
+ return state && typeof state === 'object' ? state : {};
180
+ }
181
+
182
+ /** An object that looks like ÆGIS memory stats, from either `state.memory` or
183
+ * `state` itself (the reference passed the stats object directly). */
184
+ function statsFrom(state) {
185
+ const s = obj(state);
186
+ if (s.stats && typeof s.stats === 'object') return s.stats;
187
+ if (s.memory && typeof s.memory === 'object' && (s.memory.total != null || s.memory.tiers || s.memory.sessions != null || s.memory.roles)) {
188
+ return s.memory;
189
+ }
190
+ if (s.total != null || s.tiers || s.roles) return s;
191
+ return null;
192
+ }
193
+
194
+ /** Category labels, copied from the reference registry's CATEGORIES table. */
195
+ const CATEGORY_LABELS = {
196
+ session: 'Session & context',
197
+ workspace: 'Workspace',
198
+ model: 'Model & behavior',
199
+ data: 'Data',
200
+ auth: 'Auth',
201
+ support: 'Support',
202
+ fun: 'Fun',
203
+ aegis: 'Aegis plugin',
204
+ custom: 'Custom',
205
+ };
206
+
207
+ function categoryLabel(cmd) {
208
+ if (cmd && cmd.categoryLabel) return String(cmd.categoryLabel);
209
+ const id = str(cmd && cmd.category);
210
+ if (CATEGORY_LABELS[id]) return CATEGORY_LABELS[id];
211
+ return id ? id.charAt(0).toUpperCase() + id.slice(1) : 'Commands';
212
+ }
213
+
214
+ // ── /help ────────────────────────────────────────────────────────────────────
215
+
216
+ /** @param {Array} commands [{name,aliases,desc,hint,args,category,unavailable}] */
217
+ function buildHelp(commands, ctx = {}) {
218
+ const t = themeOf(ctx);
219
+ const list = Array.isArray(commands)
220
+ ? commands
221
+ : Array.isArray(obj(commands).commands)
222
+ ? commands.commands
223
+ : [];
224
+ const out = [];
225
+ out.push([span(t.gold + BOLD, 'Commands'), span(BOLD_OFF, '')]);
226
+ out.push([span(t.gray, '─'.repeat(30))]);
227
+ let lastCat = null;
228
+ for (const cmd of list) {
229
+ if (!cmd || !cmd.name) continue;
230
+ const cat = str(cmd.category);
231
+ if (cat !== lastCat) {
232
+ out.push([span('', '')]);
233
+ out.push([span(t.gray + BOLD, categoryLabel(cmd)), span(BOLD_OFF, '')]);
234
+ lastCat = cat;
235
+ }
236
+ const name = String(cmd.name);
237
+ const pad = ' '.repeat(Math.max(1, 16 - [...name].length));
238
+ const desc = str(cmd.desc != null ? cmd.desc : cmd.help);
239
+ const nameStyle = cmd.unavailable ? t.gray : t.white;
240
+ const descStyle = cmd.unavailable ? t.dim : t.gray;
241
+ const tail = cmd.unavailable ? ' (unavailable)' : '';
242
+ out.push([span(nameStyle, '/' + name), span(descStyle, pad + desc + tail)]);
243
+ }
244
+ if (!list.length) {
245
+ out.push([span('', '')]);
246
+ out.push([span(t.gray, 'No commands registered.')]);
247
+ }
248
+ out.push([span('', '')]);
249
+ // 71 cells, and it has to stay under 80. This row was 81: the label already
250
+ // reads "Shortcuts:", so `? shortcuts` repeated the word — which cost the 10
251
+ // cells that pushed it one over, and `padLine()` truncates to `cols` rather
252
+ // than wrapping, so on every 80-column terminal the row rendered as
253
+ // "Ctrl-D exi". Measured by test/cli-panels.test.mjs, which asserts every
254
+ // buildHelp row fits the terminal.
255
+ out.push([
256
+ span(t.gray, 'Shortcuts: '), span(t.white, '?'), span(t.gray, ' · '),
257
+ span(t.white, '/help'), span(t.gray, ' commands · '), span(t.white, '↑↓'), span(t.gray, ' history · '),
258
+ span(t.white, 'Ctrl-L'), span(t.gray, ' clear · '), span(t.white, 'Ctrl-D'), span(t.gray, ' exit'),
259
+ ]);
260
+ return out;
261
+ }
262
+
263
+ // ── /status ──────────────────────────────────────────────────────────────────
264
+
265
+ /**
266
+ * @param {object} state session state (see the module header in the task)
267
+ * @param {{light?: boolean, caps?: Array<[string,string]>}} [ctx] `caps` is the
268
+ * `caps.describe()` row list, rendered as the terminal-capability rows.
269
+ */
270
+ function buildStatus(state, ctx = {}) {
271
+ const t = themeOf(ctx);
272
+ const s = obj(state);
273
+ const lines = [];
274
+ lines.push([span(t.gold + BOLD, 'Status'), span(BOLD_OFF, '')]);
275
+
276
+ const rows = [];
277
+ const add = (k, v) => {
278
+ const value = str(v);
279
+ if (value !== '') rows.push([k, value]);
280
+ };
281
+ add('Session ID', s.sessionId);
282
+ add('Working directory', s.cwd);
283
+ add('Home', s.home);
284
+ add('Model', s.model);
285
+ // `null` = auto: the pool sizes each turn from the ask, so the row says so
286
+ // rather than vanishing (add() skips empty values).
287
+ add('Effort', s.effort || 'high');
288
+ if (s.thinking != null) add('Thinking', s.thinking ? 'on' : 'off');
289
+ if (s.stream != null) add('Streaming', s.stream === false ? 'off' : 'on');
290
+ if (s.vim != null) add('Vim keymap', s.vim ? 'on' : 'off');
291
+ add('Theme', s.theme ? str(s.theme) : (ctx && ctx.light ? 'Light mode' : 'Dark mode'));
292
+ add('Backend', s.backend);
293
+ add('Base', s.base);
294
+ add('Plan', s.plan);
295
+ add('Account', s.account);
296
+ if (s.online != null) add('Online', s.online ? 'yes' : 'no');
297
+ if (s.turns != null) add('Turns', str(num(s.turns)));
298
+ if (s.calls != null) add('Tool calls', str(num(s.calls)));
299
+ if (s.version != null) add('Version', 'v' + str(s.version));
300
+ add('Node', process.version);
301
+ add('Platform', `${process.platform} ${process.arch}`);
302
+ // Terminal capabilities, read off the same `caps.describe()` rows `/terminal`
303
+ // renders — passed in on `ctx` so this builder stays pure (no caps.js require)
304
+ // and the two reports cannot drift. Absent in tests and headless runs; `add()`
305
+ // skips empty values, so the rows simply do not appear.
306
+ const capsRows = Array.isArray(ctx.caps) ? ctx.caps : [];
307
+ const cap = (k) => {
308
+ const hit = capsRows.find((r) => Array.isArray(r) && String(r[0]) === k);
309
+ return hit ? str(hit[1]) : '';
310
+ };
311
+ add('Terminal', cap('terminal'));
312
+ add('Mark', cap('mark'));
313
+ add('Star', cap('star'));
314
+ add('Color', cap('color'));
315
+ add('Control', cap('control'));
316
+ add('Frame', cap('size'));
317
+
318
+ for (const l of kv(t, rows, { keyStyle: t.gray, valStyle: t.white })) lines.push(l);
319
+
320
+ lines.push([span('', '')]);
321
+ const mode = s.permissions && s.permissions.mode ? str(s.permissions.mode) : 'default';
322
+ lines.push([span(t.gray, `Permissions: ${mode} — tool use follows your AEGIS settings.`)]);
323
+ return lines;
324
+ }
325
+
326
+ // ── /cost — the session's euro tally ─────────────────────────────────────────
327
+
328
+ /** @param {object} state {tokens, costEur, balance, model, turns, calls} */
329
+ function buildCost(state, ctx = {}) {
330
+ const t = themeOf(ctx);
331
+ const s = obj(state);
332
+ const { cols } = getSize();
333
+ const W = Math.max(30, cols - 2);
334
+ const tok = s.tokens && typeof s.tokens === 'object' ? s.tokens : {};
335
+ const { input, output, cacheRead, cacheWrite, prompt, total } = tokenBuckets(tok);
336
+ const cost = num(s.costEur);
337
+ const model = str(s.model) || 'the pinned model';
338
+ const window = num(s.contextWindow) || 200000;
339
+ const pct = window > 0 ? Math.min(100, Math.round((total / window) * 100)) : 0;
340
+
341
+ const lines = [];
342
+ lines.push([span(t.gray, '─'.repeat(W))]);
343
+ lines.push([
344
+ span('', ' '), span(t.white + BOLD, 'Session'), span(BOLD_OFF, ''),
345
+ span(t.gray, ' Status Config Usage Stats'),
346
+ ]);
347
+ lines.push([span('', ' '), span(t.gray, 'Session')]);
348
+ lines.push([span('', ' '), span(t.white, 'Total cost:'), span(t.gray, ' ' + ' '.repeat(Math.max(0, 14 - fmtEur(cost).length)) + fmtEur(cost))]);
349
+ if (s.balance != null) {
350
+ lines.push([span('', ' '), span(t.white, 'Balance:'), span(t.gray, ' ' + ' '.repeat(Math.max(0, 14 - fmtEur(s.balance).length)) + fmtEur(s.balance))]);
351
+ }
352
+ if (s.turns != null || s.calls != null) {
353
+ lines.push([span('', ' '), span(t.white, 'Turns:'), span(t.gray, ` ${num(s.turns)} turns · ${num(s.calls)} calls`)]);
354
+ }
355
+ lines.push([span('', ' '), span(t.white, ' Usage by model:')]);
356
+ // The prompt, not the miss. `input` is the miss half only (see tokenBuckets),
357
+ // so printing it as "input" reported 1.2k for a turn that had sent 31.2k —
358
+ // the same under-report /context was fixed for, in the panel that sits right
359
+ // next to it. With a cache in play the row is a sum, so show the split too.
360
+ lines.push([span('', ' '), span(t.gray, ` ${model}: ${fmtTokens(prompt)} input, ${fmtTokens(output)} output (${fmtEur(cost)})`)]);
361
+ if (cacheRead || cacheWrite) {
362
+ lines.push([span('', ' '), span(t.dim, ` ↳ miss ${fmtTokens(input)} · cache read ${fmtTokens(cacheRead)} · cache write ${fmtTokens(cacheWrite)}`)]);
363
+ }
364
+ lines.push([span('', ' ')]);
365
+ lines.push([span('', ' '), span(t.white + BOLD, 'Current session'), span(BOLD_OFF, '')]);
366
+ lines.push(contextBar(total, window, t));
367
+ lines.push([span('', ' ')]);
368
+ lines.push([span('', ' '), span(t.gray, `Session context: ${pct}% of ${fmtTokens(window)} used.`)]);
369
+ lines.push([span('', ' '), span(t.dim, 'Cost is metered from the AEGIS token bank; tokens are counted this session.')]);
370
+ return lines;
371
+ }
372
+
373
+ // ── /context — token usage by bucket ─────────────────────────────────────────
374
+
375
+ /** @param {object} state {tokens} */
376
+ function buildContext(state, ctx = {}) {
377
+ const t = themeOf(ctx);
378
+ const s = obj(state);
379
+ const { cols } = getSize();
380
+ const W = Math.max(30, cols - 2);
381
+ const tok = s.tokens && typeof s.tokens === 'object' ? s.tokens : {};
382
+ const { input, output, cacheRead, cacheWrite, prompt, total } = tokenBuckets(tok);
383
+ const window = num(s.contextWindow) || 200000;
384
+
385
+ const lines = [];
386
+ lines.push([span(t.gold + BOLD, 'Context usage'), span(BOLD_OFF, '')]);
387
+ lines.push([span('', ' '), span(t.gray, '─'.repeat(Math.max(1, W - 2)))]);
388
+ const row = (label, tokens) => [
389
+ span('', ' '), span(t.white, label),
390
+ span('', ' '.repeat(Math.max(1, 16 - [...label].length))),
391
+ span(t.gray, fmtTokens(tokens)),
392
+ span('', ' '.repeat(Math.max(1, 10 - fmtTokens(tokens).length))),
393
+ ...contextBar(tokens, window, t),
394
+ ];
395
+ lines.push(row('Prompt tokens', prompt));
396
+ // With a cache in play the prompt row is a SUM, and a sum hides the one thing
397
+ // the operator is looking for: how much of the prompt was re-sent at full
398
+ // price. Show the split, so "280.0k" cannot be misread as 280k of fresh
399
+ // input. Absent a cache the row is byte-identical to before.
400
+ if (cacheRead || cacheWrite) {
401
+ lines.push([
402
+ span('', ' '),
403
+ span(t.dim, ` ↳ miss ${fmtTokens(input)} · cache read ${fmtTokens(cacheRead)} · cache write ${fmtTokens(cacheWrite)}`),
404
+ ]);
405
+ }
406
+ lines.push(row('Output tokens', output));
407
+ lines.push([span('', ' ')]);
408
+ lines.push([span('', ' '), span(t.gray, '─'.repeat(Math.max(1, W - 2)))]);
409
+ lines.push([
410
+ span('', ' '), span(t.white + BOLD, 'Total'), span('', ' '.repeat(9)),
411
+ span(t.gray, fmtTokens(total)),
412
+ span('', ' '.repeat(Math.max(1, 10 - fmtTokens(total).length))),
413
+ ...contextBar(total, window, t),
414
+ ]);
415
+ lines.push([span('', ' ')]);
416
+ lines.push([span('', ' '), span(t.gray, `Context window: ${fmtTokens(window)} tokens`)]);
417
+ return lines;
418
+ }
419
+
420
+ // ── agents / sessions overlay ────────────────────────────────────────────────
421
+
422
+ /** @param {object} state {version, model, cwd, sessions} */
423
+ function renderSessionsOverlay(state, width, height, ctx = {}) {
424
+ const t = themeOf(ctx);
425
+ const s = obj(state);
426
+ const W = Math.max(30, num(width) ? num(width) - 4 : 76);
427
+ const ver = str(s.version);
428
+ const model = str(s.model) || 'default model';
429
+ const cwd = cwdName(s.cwd);
430
+ const sessions = Array.isArray(s.sessions) ? s.sessions.filter(Boolean) : [];
431
+ const awaiting = sessions.filter((x) => x.awaiting || x.needsInput).length;
432
+ const working = sessions.filter((x) => x.working).length;
433
+ const completed = sessions.filter((x) => x.completed).length;
434
+
435
+ const line = (spans) => [
436
+ span(t.gray, '│'), span('', ' '), ...spans,
437
+ span('', ' '.repeat(Math.max(0, W - 1 - lineWidth(spans)))),
438
+ span(t.gray, '│'),
439
+ ];
440
+ const box = [];
441
+ box.push([span(t.coral, '╭─── Aegiscode v' + ver + ' ' + '─'.repeat(Math.max(0, W - 24)) + '╮')]);
442
+ box.push(line([span(t.white, model), span(t.gray, ' · '), span(t.white, cwd)]));
443
+ box.push(line([span(t.gray, `${awaiting} awaiting input · ${working} working · ${completed} completed`)]));
444
+ box.push([span(t.gray, '├' + '─'.repeat(W) + '┤')]);
445
+ box.push(line([span(t.white + BOLD, 'Needs input'), span(BOLD_OFF, '')]));
446
+ box.push(line([span(t.gray, 'Sessions that have a question or need your decision land here')]));
447
+ box.push(line([span(t.coral, GLYPH.bloom), span(t.gray, ' current session send a prompt to start '), span(t.gray, '—')]));
448
+ box.push(line([span(t.white + BOLD, 'Working'), span(BOLD_OFF, '')]));
449
+ box.push(line([span(t.gray, 'Sessions AEGIS is actively working on — they keep running even if you close the terminal')]));
450
+ box.push(line([span(t.white + BOLD, 'Completed'), span(BOLD_OFF, '')]));
451
+ box.push(line([span(t.gray, 'Finished sessions wait here for you to review')]));
452
+ box.push([span(t.gray, '╰' + '─'.repeat(W) + '╯')]);
453
+ box.push([span('', ' '), span(t.gray, 'Sub-agents that keep working in the background need a local agent loop;')]);
454
+ box.push([span('', ' '), span(t.gray, 'this build hands a bigger task to the pooled brain instead.')]);
455
+ return box;
456
+ }
457
+
458
+ /** @param {object} state /agents — the sessions overlay at the terminal size. */
459
+ function buildAgents(state, ctx = {}) {
460
+ const { cols, rows } = getSize();
461
+ return renderSessionsOverlay(state, cols, rows, ctx);
462
+ }
463
+
464
+ // ── /permissions ─────────────────────────────────────────────────────────────
465
+
466
+ /** @param {object} rules {allow,deny,ask,defaultMode,_path} @param {string} [mode] */
467
+ function buildPermissions(rules, mode, ctx = {}) {
468
+ const t = themeOf(ctx);
469
+ const r = obj(rules);
470
+ const list = (v) => (Array.isArray(v) ? v : []);
471
+ const def = mode != null && mode !== '' ? String(mode) : (r.defaultMode != null ? String(r.defaultMode) : 'default');
472
+
473
+ const lines = [];
474
+ lines.push([span(t.gold + BOLD, 'Permissions'), span(BOLD_OFF, '')]);
475
+ lines.push([span('', ' '), span(t.gray, 'Default mode: '), span(t.white, def)]);
476
+ lines.push([span('', ' ')]);
477
+ const section = (name, patterns) => {
478
+ const out = [[span('', ' '), span(t.white + BOLD, name), span(BOLD_OFF, '')]];
479
+ if (!patterns.length) out.push([span('', ' '), span(t.gray, '(none)')]);
480
+ for (const p of patterns) out.push([span('', ' '), span(t.gray, str(p))]);
481
+ return out;
482
+ };
483
+ for (const l of section('Allow', list(r.allow))) lines.push(l);
484
+ for (const l of section('Deny', list(r.deny))) lines.push(l);
485
+ for (const l of section('Ask', list(r.ask))) lines.push(l);
486
+ lines.push([span('', '')]);
487
+ lines.push([span(t.gray, 'Usage:')]);
488
+ lines.push([span(t.gray, ' /permissions allow "Bash(npm run *)"')]);
489
+ lines.push([span(t.gray, ' /permissions deny "Edit(src/**)"')]);
490
+ lines.push([span(t.gray, ' /permissions ask "Read(**/*.env)"')]);
491
+ lines.push([span(t.gray, ' /permissions default ask · /permissions clear')]);
492
+ lines.push([span('', '')]);
493
+ lines.push([span(t.dim, `Stored in ${str(r._path) || '~/.aegiscode/permissions.json'}`)]);
494
+ return lines;
495
+ }
496
+
497
+ // ── /model list ──────────────────────────────────────────────────────────────
498
+
499
+ /** @param {string} currentId @param {Array} models [{id,name,model}] */
500
+ function buildModelList(currentId, models, ctx = {}) {
501
+ const t = themeOf(ctx);
502
+ const list = Array.isArray(models) ? models : [];
503
+ const cur0 = str(currentId);
504
+ // Which class each row belongs to. On byok a row is `provider:model` (the
505
+ // engine's listModels('byok') shape) and `model` is unset, so the third
506
+ // column would otherwise print "(default)" down the whole panel; the row's
507
+ // `note` is what actually tells the user whether this machine holds the key.
508
+ // A merged list (both classes at once, e.g. the /model picker's full list)
509
+ // tags each row with its own `cls`, checked first so an aegis row and a byok
510
+ // row in the same panel each render with the format that fits its shape;
511
+ // `ctx.modelClass` is the fallback for a single-class list with no per-row tag.
512
+ const byokRow = (m) => (m.cls ? m.cls === 'byok' : ctx.modelClass === 'byok');
513
+ const anyByok = list.some(byokRow);
514
+ const lines = [];
515
+ lines.push([span(t.gold + BOLD, 'Models'), span(BOLD_OFF, '')]);
516
+ lines.push([span(t.gray, '─'.repeat(30))]);
517
+ for (const m of list) {
518
+ if (!m) continue;
519
+ const idv = str(m.id) || str(m.model);
520
+ const cur = idv !== '' && idv === cur0;
521
+ const id = (cur ? '▶ ' : ' ') + idv;
522
+ const name = str(m.name || m.label || m.model);
523
+ const model = byokRow(m) ? str(m.note) || str(m.model) : str(m.model) || '(default)';
524
+ lines.push([
525
+ span(t.white, id), span('', ' '.repeat(Math.max(1, 26 - [...id].length))),
526
+ span(t.gray, name), span('', ' '.repeat(Math.max(1, 22 - [...name].length))),
527
+ span(t.gray, model),
528
+ ]);
529
+ }
530
+ if (!list.length) lines.push([span('', ' '), span(t.gray, '(no models configured)')]);
531
+ lines.push([span('', '')]);
532
+ lines.push([
533
+ span(t.gray, anyByok
534
+ ? 'Switch: /model <id> · Add a provider key: /byok-key <provider> · Run on it: /class byok'
535
+ : 'Switch: /model <id> · Add: /model add <id> <name> <model> <baseURL> [apiKey] · Remove: /model remove <id>'),
536
+ ]);
537
+ return lines;
538
+ }
539
+
540
+ // ── /rewind ──────────────────────────────────────────────────────────────────
541
+
542
+ /** @param {Array} items [{idx,depth,words,ts}] */
543
+ function buildRewindList(items, ctx = {}) {
544
+ const t = themeOf(ctx);
545
+ const list = Array.isArray(items) ? items : [];
546
+ const lines = [];
547
+ lines.push([span(t.gold + BOLD, 'Rewind'), span(BOLD_OFF, '')]);
548
+ lines.push([span('', ' '), span(t.gray, 'Snapshots are taken after every exchange.')]);
549
+ lines.push([span('', ' ')]);
550
+ for (const it of list) {
551
+ if (!it) continue;
552
+ const idx = str(num(it.idx));
553
+ lines.push([
554
+ span('', ' '), span(t.green, idx),
555
+ span('', ' '.repeat(Math.max(1, 4 - [...idx].length))),
556
+ span(t.white, `${num(it.depth)} messages`),
557
+ span(t.gray, ` · ${num(it.words)} words · ${ago(it.ts)}`),
558
+ ]);
559
+ }
560
+ if (!list.length) lines.push([span('', ' '), span(t.gray, '(no checkpoints)')]);
561
+ lines.push([span('', '')]);
562
+ lines.push([span(t.gray, 'Usage: /rewind N to restore that checkpoint (0 = session start)')]);
563
+ return lines;
564
+ }
565
+
566
+ // ── /hooks ───────────────────────────────────────────────────────────────────
567
+
568
+ /** @param {object} stats {enabled,hooks,events,byEvent,fromPaths} */
569
+ function buildHooksStatus(stats, ctx = {}) {
570
+ const t = themeOf(ctx);
571
+ const st = obj(stats);
572
+ const events = Array.isArray(st.events) ? st.events : [];
573
+ const byEvent = st.byEvent && typeof st.byEvent === 'object' ? st.byEvent : {};
574
+ const fromPaths = Array.isArray(st.fromPaths) ? st.fromPaths : Array.isArray(st.sources) ? st.sources : [];
575
+
576
+ const lines = [];
577
+ lines.push([span(t.gold + BOLD, 'Hooks status'), span(BOLD_OFF, '')]);
578
+ const rows = [
579
+ ['status', st.enabled ? 'enabled' : 'disabled'],
580
+ ['hooks', str(num(st.hooks))],
581
+ ['events', str(events.length)],
582
+ ];
583
+ for (const l of kv(t, rows, { keyStyle: t.gray, valStyle: t.white })) lines.push(l);
584
+ if (num(st.hooks) > 0) {
585
+ lines.push([span('', '')]);
586
+ lines.push([span('', ' '), span(t.white + BOLD, 'by event'), span(BOLD_OFF, '')]);
587
+ for (const [event, count] of Object.entries(byEvent)) {
588
+ lines.push([span('', ' '), span(t.green, GLYPH.bullet), span(t.white, ` ${event}`), span(t.gray, ` ${num(count)}`)]);
589
+ }
590
+ }
591
+ lines.push([span('', '')]);
592
+ lines.push([span(t.gray, '/hooks list for full config')]);
593
+ lines.push([span('', '')]);
594
+ lines.push([span(t.dim, fromPaths.length
595
+ ? `Settings: ${fromPaths.join(', ')}`
596
+ : 'Settings: no settings.json with hooks found (checked ~/.aegis, .aegis, ~/.aegiscode, .aegiscode, ~/.claude)')]);
597
+ lines.push([span(t.gray, 'Config hooks are read, not managed — edit the files above.')]);
598
+ lines.push([span(t.gray, 'The repo guard hooks (.githooks/) are installed by /hooks install.')]);
599
+ return lines;
600
+ }
601
+
602
+ /** @param {object} config {hooks:{event:[{name,matcher,hooks}]}} */
603
+ function buildHooksList(config, ctx = {}) {
604
+ const t = themeOf(ctx);
605
+ const cfg = obj(config);
606
+ const hooks = cfg.hooks && typeof cfg.hooks === 'object' ? cfg.hooks : {};
607
+ const lines = [];
608
+ lines.push([span(t.gold + BOLD, 'Hooks config'), span(BOLD_OFF, '')]);
609
+ let hasAny = false;
610
+ for (const [event, matchers] of Object.entries(hooks)) {
611
+ if (!Array.isArray(matchers) || matchers.length === 0) continue;
612
+ hasAny = true;
613
+ lines.push([span('', '')]);
614
+ lines.push([span('', ' '), span(t.white + BOLD, event), span(BOLD_OFF, '')]);
615
+ for (const matcher of matchers) {
616
+ if (!matcher) continue;
617
+ lines.push([span('', ' '), span(t.lavender, str(matcher.name) || '(unnamed)')]);
618
+ if (matcher.matcher) {
619
+ if (matcher.matcher.tools) lines.push([span('', ' - tools: '), span(t.gray, str(matcher.matcher.tools))]);
620
+ if (matcher.matcher.paths) lines.push([span('', ' - paths: '), span(t.gray, str(matcher.matcher.paths))]);
621
+ if (matcher.matcher.commands) lines.push([span('', ' - commands: '), span(t.gray, str(matcher.matcher.commands))]);
622
+ }
623
+ lines.push([span('', ` - hooks: ${Array.isArray(matcher.hooks) ? matcher.hooks.length : 0}`)]);
624
+ lines.push([span('', '')]);
625
+ }
626
+ }
627
+ if (!hasAny) {
628
+ lines.push([span('', ' '), span(t.gray, 'no hooks configured.')]);
629
+ lines.push([span('', '')]);
630
+ lines.push([span('', ' '), span(t.gray, 'add hooks to settings.json:')]);
631
+ lines.push([span('', ' '), span(t.gray, '- ~/.aegis/settings.json (user)')]);
632
+ lines.push([span('', ' '), span(t.gray, '- .aegis/settings.json (project)')]);
633
+ } else {
634
+ lines.push([span('', '')]);
635
+ lines.push([span(t.gray, '/hooks status for the summary')]);
636
+ }
637
+ return lines;
638
+ }
639
+
640
+ // ── support panels ───────────────────────────────────────────────────────────
641
+
642
+ function buildTroubleshooting(state, ctx = {}) {
643
+ const t = themeOf(ctx);
644
+ const lines = [];
645
+ lines.push([span(t.gold + BOLD, 'Troubleshooting'), span(BOLD_OFF, '')]);
646
+ const tips = [
647
+ ['No output / blank screen', 'Run with TERM=xterm-256color, or switch to a lighter theme (/theme light).'],
648
+ ['Keys not responding', 'This client needs a real TTY — run it from a terminal, not a CI job.'],
649
+ ['401 / unauthorized', 'Check the account line with /status, or set a provider key with /byok-set.'],
650
+ ['No answers from the brain', 'Confirm the token-bank balance with /billing.'],
651
+ ['Memory looks empty', 'Recall is per-topic — try /aegis-recall <topic> or save one with /aegis-remember <note>.'],
652
+ ];
653
+ for (const [issue, fix] of tips) {
654
+ lines.push([span(t.green, GLYPH.bullet), span(t.white, ' ' + issue)]);
655
+ lines.push([span('', ' '), span(t.gray, fix)]);
656
+ }
657
+ lines.push([span('', '')]);
658
+ lines.push([span(t.gray, 'Run /status for account state. Help: https://aegiscloud.org')]);
659
+ return lines;
660
+ }
661
+
662
+ function buildOnboarding(state, ctx = {}) {
663
+ const t = themeOf(ctx);
664
+ const lines = [];
665
+ lines.push([span(t.gold + BOLD, 'Getting started'), span(BOLD_OFF, '')]);
666
+ const tips = [
667
+ ['/help', 'list every command'],
668
+ ['/', 'open the command palette'],
669
+ ['?', 'shortcuts'],
670
+ ['/model <id>', 'pin a model'],
671
+ ['/theme light|dark', 'switch the colour theme'],
672
+ ['/aegis-ask', 'ask the pooled brain a question'],
673
+ ['/memory', 'show your AEGIS cloud memory'],
674
+ ['Ctrl-D', 'exit'],
675
+ ];
676
+ for (const [key, what] of tips) {
677
+ lines.push([span('', ' '), span(t.lavender, key), span('', ' '.repeat(Math.max(1, 20 - [...key].length))), span(t.gray, what)]);
678
+ }
679
+ lines.push([span('', '')]);
680
+ lines.push([span(t.gray, 'Try "summarize this file for me" to see the full flow.')]);
681
+ return lines;
682
+ }
683
+
684
+ function buildShellCompletion(state, ctx = {}) {
685
+ const t = themeOf(ctx);
686
+ const lines = [];
687
+ lines.push([span(t.gold + BOLD, 'Shell completion'), span(BOLD_OFF, '')]);
688
+ lines.push([span('', ' '), span(t.gray, 'Aegiscode completes /commands with Tab inside the app.')]);
689
+ lines.push([span('', ' '), span(t.gray, 'For shell-level completion of the aegiscode CLI itself:')]);
690
+ lines.push([span('', ' ')]);
691
+ const rows = [
692
+ ['bash', 'eval "$(aegiscode shell-completion bash)"'],
693
+ ['zsh', 'eval "$(aegiscode shell-completion zsh)"'],
694
+ ['fish', 'aegiscode shell-completion fish | source'],
695
+ ];
696
+ for (const [shell, cmd] of rows) {
697
+ lines.push([span('', ' '), span(t.white + BOLD, shell), span('', ' '.repeat(Math.max(1, 6 - shell.length))), span(t.gray, cmd)]);
698
+ }
699
+ lines.push([span('', '')]);
700
+ lines.push([span(t.dim, 'Add the eval line to your ~/.bashrc or ~/.zshrc to make it persist.')]);
701
+ return lines;
702
+ }
703
+
704
+ function buildTerminalSetup(state, ctx = {}) {
705
+ const t = themeOf(ctx);
706
+ const s = obj(state);
707
+ const env = typeof process !== 'undefined' && process.env ? process.env : {};
708
+ const { cols, rows } = getSize();
709
+ const shell = str(s.shell) || pathName(str(env.SHELL));
710
+ const table = [
711
+ ['TERM', str(s.term) || str(env.TERM) || '(unset)'],
712
+ ['LANG', str(s.lang) || str(env.LANG) || '(unset)'],
713
+ ['Shell', shell || 'unknown'],
714
+ ['Size', `${cols}x${rows}`],
715
+ ];
716
+ const lines = [];
717
+ lines.push([span(t.gold + BOLD, 'Terminal setup'), span(BOLD_OFF, '')]);
718
+ for (const l of kv(t, table, { keyStyle: t.white, valStyle: t.gray })) lines.push(l);
719
+ lines.push([span('', '')]);
720
+ lines.push([span(t.gray, 'Tips:')]);
721
+ lines.push([span(t.gray, ' • TERM=xterm-256color enables full color + resize handling')]);
722
+ lines.push([span(t.gray, ' • Set LANG (e.g. en_US.UTF-8) for correct glyphs and word wrap')]);
723
+ lines.push([span(t.gray, ' • Resize mid-session is handled (SIGWINCH); overlays adapt')]);
724
+ return lines;
725
+ }
726
+
727
+ // ── /terminal ────────────────────────────────────────────────────────────────
728
+
729
+ /**
730
+ * The capability report — the same rows `aegiscode --terminal` prints, because
731
+ * both render `caps.describe()`. Taking the rows as an argument keeps this
732
+ * builder pure (see the module header): no `require('./caps.js')` here, so
733
+ * `/terminal` and the launcher flag cannot drift into two different reports.
734
+ *
735
+ * This is the panel the CLI help promised at `aegiscode.js:63` ("`/terminal
736
+ * ascii` toggles it mid-session") long before the command existed.
737
+ *
738
+ * @param {Array<[string,string]>} report rows from `caps.describe()`
739
+ * @param {{pinned?: boolean, light?: boolean}} [ctx] `pinned` adds the warning
740
+ * shown after `/terminal width`, which turns off resize re-reads.
741
+ */
742
+ function buildTerminalCaps(report, ctx = {}) {
743
+ const t = themeOf(ctx);
744
+ const rows = (Array.isArray(report) ? report : [])
745
+ .filter((r) => Array.isArray(r) && r.length >= 2)
746
+ .map(([k, v]) => [str(k), str(v)]);
747
+ const lines = [];
748
+ lines.push([span(t.gold + BOLD, 'Terminal capabilities'), span(BOLD_OFF, '')]);
749
+ if (!rows.length) {
750
+ lines.push([span('', ' '), span(t.gray, 'No capability report available.')]);
751
+ return lines;
752
+ }
753
+ for (const l of kv(t, rows, { keyStyle: t.white, valStyle: t.gray })) lines.push(l);
754
+ lines.push([span('', '')]);
755
+ if (ctx && ctx.pinned) {
756
+ lines.push([span(t.coral, GLYPH.warn), span(t.gold, ' width is pinned — resizes are ignored until /terminal auto')]);
757
+ lines.push([span('', '')]);
758
+ }
759
+ lines.push([span(t.gray, 'Override: /terminal ascii | unicode | color | no-color | background <dark|light> | star <native|narrow>')]);
760
+ lines.push([span(t.gray, ' /terminal width <cols> | auto | status')]);
761
+ lines.push([span(t.gray, 'At launch: --ascii --unicode --no-color --width <cols> --terminal')]);
762
+ return lines;
763
+ }
764
+
765
+ function buildPRs(ghOutput, ctx = {}) {
766
+ const t = themeOf(ctx);
767
+ const lines = [];
768
+ lines.push([span(t.gold + BOLD, 'Open pull requests'), span(BOLD_OFF, '')]);
769
+ const trimmed = str(ghOutput).trim();
770
+ if (!trimmed) {
771
+ lines.push([span('', ' '), span(t.gray, 'No open PRs in this repository.')]);
772
+ return lines;
773
+ }
774
+ for (const l of trimmed.split('\n').slice(0, 10)) {
775
+ lines.push([span('', ' '), span(t.white, l)]);
776
+ }
777
+ lines.push([span('', '')]);
778
+ lines.push([span(t.gray, 'Review with /review · comments via /pr-comments')]);
779
+ return lines;
780
+ }
781
+
782
+ // ── /benchmark ───────────────────────────────────────────────────────────────
783
+
784
+ /** @param {Array} results [[label, ms], ...] */
785
+ function buildBenchmark(results, ctx = {}) {
786
+ const t = themeOf(ctx);
787
+ const list = Array.isArray(results) ? results : [];
788
+ const lines = [];
789
+ lines.push([span(t.gold + BOLD, 'Benchmark'), span(BOLD_OFF, '')]);
790
+ lines.push([span('', ' '), span(t.gray, 'In-app micro-benchmarks (this process, this machine):')]);
791
+ lines.push([span('', ' ')]);
792
+ for (const item of list) {
793
+ if (!Array.isArray(item) || item.length < 2) continue;
794
+ const label = str(item[0]);
795
+ lines.push([span('', ' '), span(t.white, label), span('', ' '.repeat(Math.max(1, 30 - [...label].length))), span(t.gray, `${num(item[1])} ms`)]);
796
+ }
797
+ if (!list.length) lines.push([span('', ' '), span(t.gray, '(no benchmarks run)')]);
798
+ lines.push([span('', '')]);
799
+ lines.push([span(t.dim, 'Spoiler: the terminal renders faster than you type.')]);
800
+ return lines;
801
+ }
802
+
803
+ // ── /waifu ───────────────────────────────────────────────────────────────────
804
+
805
+ const WAIFU_ART = [
806
+ ' ▄▄▄▄▄▄▄▄▄▄▄▄',
807
+ ' ▄█▓▓▓▓▓▓▓▓▓▓▓▓█▄',
808
+ ' █▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█',
809
+ ' █▓▓▓█▓▓▓▓▓▓▓█▓▓▓█',
810
+ ' █▓▓█▓▓█▓▓▓█▓▓█▓▓█',
811
+ ' █▓▓█▓█▓▓▓█▓█▓▓█',
812
+ ' █▓▓▓█▓▓▓█▓▓▓█',
813
+ ' ██▓▓▓▓▓▓▓▓▓▓▓▓▓██',
814
+ ' █▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█',
815
+ ' █▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█',
816
+ ' █▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█',
817
+ ' ▀█▓▓▓▓▓▓▓▓▓▓▓▓▓█▀',
818
+ ' ▀▀▀███████▀▀▀',
819
+ ];
820
+
821
+ function buildWaifu(ctx = {}) {
822
+ const t = themeOf(ctx);
823
+ const lines = [];
824
+ lines.push([span(t.gold + BOLD, 'Waifu'), span(BOLD_OFF, '')]);
825
+ for (const row of WAIFU_ART) lines.push([span(t.lavender, row)]);
826
+ lines.push([span('', '')]);
827
+ lines.push([span(t.gray, 'A distinguished gentleman, rendered in block characters.')]);
828
+ return lines;
829
+ }
830
+
831
+ // ── /aegis-* panels ──────────────────────────────────────────────────────────
832
+
833
+ /** @param {object} state {stats|memory, cloud, cloudNote, version, backend} */
834
+ function buildAegisStatus(state, ctx = {}) {
835
+ const t = themeOf(ctx);
836
+ const s = obj(state);
837
+ const stats = statsFrom(s);
838
+ const cloud = s.cloud && typeof s.cloud === 'object' ? s.cloud : null;
839
+ const cloudNote = str(s.cloudNote);
840
+ const version = str(s.version);
841
+ const backend = str(s.backend || s.store);
842
+
843
+ const lines = [];
844
+ lines.push([span(t.gold + BOLD, 'ÆGIS Status'), span(BOLD_OFF, '')]);
845
+ lines.push([span(t.gray, '─'.repeat(30))]);
846
+ const total = stats ? num(stats.total) : 0;
847
+ const sessions = stats ? num(stats.sessions) : 0;
848
+ lines.push([span(t.white, `Memory: ${total.toLocaleString()} entries across ${sessions} sessions`)]);
849
+ if (stats && stats.roles && (stats.roles.user != null || stats.roles.assistant != null)) {
850
+ const roles = stats.roles;
851
+ const parts = [];
852
+ if (roles.user != null) parts.push(`${num(roles.user)} user`);
853
+ if (roles.assistant != null) parts.push(`${num(roles.assistant)} assistant`);
854
+ if (roles.other) parts.push(`${num(roles.other)} other`);
855
+ if (parts.length) lines.push([span(t.gray, ` roles: ${parts.join(' · ')}`)]);
856
+ }
857
+ if (stats && stats.tiers) lines.push([span(t.gray, ` tiers: ${JSON.stringify(stats.tiers)}`)]);
858
+ if (backend) lines.push([span(t.gray, ` store: ${backend}`)]);
859
+ if (stats && stats.total != null) {
860
+ const withEmb = num(stats.withEmbeddings);
861
+ const pct = total ? Math.round((withEmb / total) * 100) : 0;
862
+ if (stats.embeddingsEnabled === true) {
863
+ const eng = (stats.embeddingModels && Object.keys(stats.embeddingModels)[0]) || 'embedding';
864
+ lines.push([span(t.gray, ` embed: ${eng} · ${pct}% coverage`)]);
865
+ } else if (stats.embeddingsEnabled === false && total) {
866
+ lines.push([span(t.gray, ' embed: keyword-only')]);
867
+ }
868
+ if (stats.stale) lines.push([span(t.gray, ` stale: ${num(stats.stale)} entries >90d`)]);
869
+ }
870
+ if (cloud) {
871
+ const key = cloud.key ? '✓ connected' : '✗ no API key';
872
+ const sync = cloud.sync ? 'sync on' : 'sync off';
873
+ lines.push([span(t.white, `Cloud: ${key}, ${sync}`)]);
874
+ } else if (cloudNote) {
875
+ lines.push([span(t.gray, `Cloud: ${cloudNote}`)]);
876
+ } else {
877
+ lines.push([span(t.gray, 'Cloud: not checked (aegis /cloud status unavailable)')]);
878
+ }
879
+ if (version) lines.push([span(t.gray, `CLI: aegis ${version}`)]);
880
+ return lines;
881
+ }
882
+
883
+ /** @param {Array} results [{content,timestamp,source,tags}] */
884
+ function buildAegisRecall(results, ctx = {}) {
885
+ const t = themeOf(ctx);
886
+ const list = Array.isArray(results) ? results.filter(Boolean) : [];
887
+ const lines = [];
888
+ lines.push([span(t.gold + BOLD, 'ÆGIS Memory'), span(BOLD_OFF, '')]);
889
+ lines.push([span(t.gray, '─'.repeat(30))]);
890
+ if (!list.length) {
891
+ lines.push([span(t.gray, 'No memory found for this topic.')]);
892
+ lines.push([span(t.gray, 'Nothing relevant is stored yet — /aegis-remember <note> saves one.')]);
893
+ return lines;
894
+ }
895
+ for (const r of list.slice(0, 10)) {
896
+ const first = str(r.content).split('\n')[0].slice(0, 90);
897
+ lines.push([span(t.white + BOLD, `• ${first}`), span(BOLD_OFF, '')]);
898
+ const when = r.timestamp ? str(r.timestamp).slice(0, 10) : '';
899
+ const src = r.source ? ` (${str(r.source)})` : '';
900
+ const tags = Array.isArray(r.tags) && r.tags.length ? ' · tags: ' + r.tags.join(', ') : '';
901
+ lines.push([span(t.gray, ` ${when}${src}${tags}`)]);
902
+ }
903
+ if (list.length > 10) lines.push([span(t.gray, `…and ${list.length - 10} more`)]);
904
+ return lines;
905
+ }
906
+
907
+ /** @param {string} task */
908
+ function buildAegisMulti(task, ctx = {}) {
909
+ const t = themeOf(ctx);
910
+ const subject = str(task);
911
+ const lines = [];
912
+ lines.push([span(t.gold + BOLD, 'ÆGIS Multi — compose'), span(BOLD_OFF, '')]);
913
+ lines.push([span(t.gray, '─'.repeat(30))]);
914
+ lines.push([span(t.gray, 'Paste into your aegis-cli session (the confirmation prompt works there):')]);
915
+ lines.push([span(t.white, ` /multi ${subject}`)]);
916
+ lines.push([span(t.gray, ' /multiyolo ' + subject + ' — auto-approved variant')]);
917
+ lines.push([span('', '')]);
918
+ lines.push([span(t.gray, 'Optional flags: --save-as <name> · --template <id>')]);
919
+ lines.push([span(t.gray, 'Add "run" to execute headless here instead: /aegis-multi <task> run')]);
920
+ return lines;
921
+ }
922
+
923
+ /** Shared renderer for --print slash results (/council, /ask, /multi run). */
924
+ function buildAegisPrint(title, opts = {}, ctx = {}) {
925
+ const t = themeOf(ctx);
926
+ const o = obj(opts);
927
+ const lines = [];
928
+ lines.push([span(t.gold + BOLD, str(title)), span(BOLD_OFF, '')]);
929
+ lines.push([span(t.gray, '─'.repeat(30))]);
930
+ for (const l of str(o.result).split('\n')) lines.push([span(t.white, l)]);
931
+ if (o.model || o.provider) {
932
+ lines.push([span(t.gray, ` via ${str(o.provider) || 'aegis'}${o.model ? ' · ' + str(o.model) : ''}`)]);
933
+ }
934
+ return lines;
935
+ }
936
+
937
+ // ── /billing ─────────────────────────────────────────────────────────────────
938
+
939
+ /** @param {object} state {balance,plan,account,costEur} */
940
+ function buildBilling(state, ctx = {}) {
941
+ const t = themeOf(ctx);
942
+ const s = obj(state);
943
+ const lines = [];
944
+ lines.push([span(t.gold + BOLD, 'Billing'), span(BOLD_OFF, '')]);
945
+ lines.push([span(t.gray, '─'.repeat(30))]);
946
+ const rows = [];
947
+ if (s.balance != null) rows.push(['Balance', fmtEur(s.balance)]);
948
+ if (s.plan != null) rows.push(['Plan', str(s.plan)]);
949
+ if (s.account != null) rows.push(['Account', str(s.account)]);
950
+ if (s.costEur != null) rows.push(['This session', fmtEur(s.costEur)]);
951
+ if (rows.length) {
952
+ for (const l of kv(t, rows, { indent: ' ', keyStyle: t.gray, valStyle: t.white })) lines.push(l);
953
+ } else {
954
+ lines.push([span('', ' '), span(t.gray, 'No billing data available.')]);
955
+ }
956
+ lines.push([span('', '')]);
957
+ lines.push([span(t.white, 'AEGIS pooled inference'), span(t.gray, ' metered against your token bank')]);
958
+ // ── the paid prompt ───────────────────────────────────────────────────────
959
+ // `/billing` is the one screen a free user reaches when they are already
960
+ // thinking about money, and it used to spend that moment saying "AEGIS has no
961
+ // subscription of its own" — a claim that contradicted the plan Pro is sold
962
+ // as, on the only surface where the contradiction could cost a sale. It is
963
+ // now the place the ONE reason to pay is stated, in the words the desktop's
964
+ // welcome panel and the drain's refusal both use (`state.payment`, built by
965
+ // `cli/src/entitlement.js` from the shared module, so a terminal and a GUI
966
+ // cannot pitch two different products).
967
+ //
968
+ // The panel stays pure: it renders the view it is handed and never probes,
969
+ // never decides entitlement, and never invents a link. A caller that passes
970
+ // no view gets the top-up row it always printed, minus the false claim.
971
+ const pay = s.payment && typeof s.payment === 'object' ? s.payment : null;
972
+ if (pay) {
973
+ const { cols } = getSize();
974
+ const mark = pay.paid ? '✔' : '✦';
975
+ lines.push(...wrapRows(`${mark} ${str(pay.label) || 'Unlimited'}: ${str(pay.reason)}`, 2, pay.paid ? t.green : t.gold, cols));
976
+ // The honesty line rides every paid prompt, wrapped rather than clipped —
977
+ // `padLine()` truncates, and a truncated honesty line would read as the
978
+ // promise alone.
979
+ lines.push(...wrapRows(str(pay.honesty), 2, t.gray, cols));
980
+ if (!pay.paid && pay.unlock) lines.push(...wrapRows(str(pay.unlock), 2, t.gray, cols));
981
+ // The relay's price, on the lane a BYOK user is actually billed on. Printed
982
+ // only when the server published a rate (`pay.byok` is '' otherwise) —
983
+ // a hardcoded fee here would be a client disagreeing with the ledger, and
984
+ // saying nothing is the only honest alternative to inventing one. Wrapped,
985
+ // never clipped: `padLine()` truncates, and a truncated fee line would read
986
+ // as a cheaper lane than the one that bills.
987
+ if (pay.byok) lines.push(...wrapRows(str(pay.byok), 2, t.gray, cols));
988
+ // `verified === false` is the module's "we did not get a real answer"
989
+ // (timeout, unreadable body, no key). The offer still renders — this panel
990
+ // is allowed to sell — but a timeout is not presented as a fact about the
991
+ // account, which is the difference between a prompt and a lie.
992
+ if (pay.verified === false) lines.push(...wrapRows('(account not confirmed this session — verdict may be stale)', 2, t.gray, cols));
993
+ if (pay.url) lines.push([span('', ' '), span(t.gray, str(pay.url))]);
994
+ } else {
995
+ // Was a literal `https://aegiscloud.org/billing`, which has never been a
996
+ // route on aegis1 — only `/billing/success` is real; the page is `/topup`.
997
+ // So the one row on the one screen that exists to convert a free user sent
998
+ // every user who reached it to a 404, and correcting a wrong path needed an
999
+ // npm release because it was compiled into the client. Now it points at
1000
+ // `/go/topup`, a server-side indirection: the destination can change without
1001
+ // a client release, and the click arrives tagged with the channel. 75 cells
1002
+ // of 80 — measured, because `padLine()` truncates rather than wraps.
1003
+ lines.push([span(t.gray, ` Top-ups and invoices: ${goUrl('topup', 'cost_screen')}`)]);
1004
+ }
1005
+ return lines;
1006
+ }
1007
+
1008
+ // ── /tokens ──────────────────────────────────────────────────────────────────
1009
+
1010
+ /** @param {object} state {tokens, costEur} */
1011
+ function buildTokens(state, ctx = {}) {
1012
+ const t = themeOf(ctx);
1013
+ const s = obj(state);
1014
+ const { cols } = getSize();
1015
+ const W = Math.max(24, cols - 2);
1016
+ const tok = s.tokens && typeof s.tokens === 'object' ? s.tokens : {};
1017
+ const { input, output, cacheRead, cacheWrite, total } = tokenBuckets(tok);
1018
+ const cost = num(s.costEur);
1019
+ const window = num(s.contextWindow) || 200000;
1020
+ const pct = window > 0 ? Math.min(100, Math.round((total / window) * 100)) : 0;
1021
+
1022
+ const lines = [];
1023
+ lines.push([span(t.gold + BOLD, 'Token usage'), span(BOLD_OFF, '')]);
1024
+ lines.push([span(t.gray, '─'.repeat(Math.min(30, W)))]);
1025
+ const max = Math.max(input, output, cacheRead, cacheWrite, 1);
1026
+ const bar = (label, tokens) => {
1027
+ const frac = Math.min(1, tokens / max);
1028
+ const filled = Math.max(0, Math.round(frac * 24));
1029
+ return [
1030
+ span('', ' '), span(t.white, label),
1031
+ span('', ' '.repeat(Math.max(1, 11 - [...label].length))),
1032
+ span(t.green, '█'.repeat(filled)),
1033
+ span(t.dim, '█'.repeat(Math.max(0, 24 - filled))),
1034
+ span(t.gray, ` ${fmtTokens(tokens)}`),
1035
+ ];
1036
+ };
1037
+ lines.push(bar('input', input));
1038
+ lines.push(bar('output', output));
1039
+ lines.push(bar('cache read', cacheRead));
1040
+ lines.push(bar('cache write', cacheWrite));
1041
+ lines.push([span('', ' ')]);
1042
+ lines.push([
1043
+ span('', ' '), span(t.white, 'Total:'), span(t.gray, ` ${fmtTokens(total)}`),
1044
+ span('', ' '.repeat(8)), span(t.white, 'Est. cost:'), span(t.gray, ` ${fmtEur(cost)}`),
1045
+ ]);
1046
+ lines.push([span('', ' '), span(t.gray, `Context: ${pct}% of ${fmtTokens(window)} window`)]);
1047
+ lines.push([span('', ' '), span(t.gray, 'Tokens are counted from this session; cost is metered in euro.')]);
1048
+ return lines;
1049
+ }
1050
+
1051
+ // ── /skills ──────────────────────────────────────────────────────────────────
1052
+
1053
+ /** @param {Array} skills [{source,name,namespace,description}] @param {Array} scannedDirs */
1054
+ function buildSkills(skills, scannedDirs, ctx = {}) {
1055
+ const t = themeOf(ctx);
1056
+ const list = Array.isArray(skills) ? skills.filter(Boolean) : [];
1057
+ const dirs = Array.isArray(scannedDirs) ? scannedDirs : [];
1058
+ const lines = [];
1059
+ lines.push([span(t.gold + BOLD, 'Skills'), span(BOLD_OFF, '')]);
1060
+ lines.push([span(t.gray, '─'.repeat(30))]);
1061
+ if (!list.length) {
1062
+ lines.push([span(t.gray, 'No skills found.')]);
1063
+ lines.push([span(t.gray, 'Skill dirs scanned:')]);
1064
+ for (const d of dirs) lines.push([span(t.dim, ` ${str(d)}`)]);
1065
+ lines.push([span('', '')]);
1066
+ lines.push([span(t.gray, 'Add one: mkdir -p .aegis/skills/<name> and drop a SKILL.md inside.')]);
1067
+ return lines;
1068
+ }
1069
+ let lastSource = null;
1070
+ for (const s of list) {
1071
+ if (s.source !== lastSource) {
1072
+ lines.push([span(t.gray + BOLD, s.source === 'user' ? 'User' : 'Project'), span(BOLD_OFF, '')]);
1073
+ lastSource = s.source;
1074
+ }
1075
+ const name = s.namespace ? `${str(s.namespace)}/${str(s.name)}` : str(s.name);
1076
+ const desc = str(s.description) || '(no description)';
1077
+ lines.push([span(t.white, ` ${name}`), span(t.gray, ' '.repeat(Math.max(1, 18 - [...name].length)) + desc)]);
1078
+ }
1079
+ lines.push([span('', '')]);
1080
+ lines.push([span(t.gray, '/skills <name> for details · /skills refresh to rescan')]);
1081
+ return lines;
1082
+ }
1083
+
1084
+ /** /skills <name> — one skill's frontmatter + body excerpt. */
1085
+ function buildSkillDetail(skill, ctx = {}) {
1086
+ const t = themeOf(ctx);
1087
+ const s = obj(skill);
1088
+ const name = s.namespace ? `${str(s.namespace)}/${str(s.name)}` : str(s.name);
1089
+ const lines = [];
1090
+ lines.push([span(t.gold + BOLD, `Skill: ${name}`), span(BOLD_OFF, '')]);
1091
+ lines.push([span(t.gray, '─'.repeat(30))]);
1092
+ if (s.description) lines.push([span(t.gray, str(s.description))]);
1093
+ lines.push([span(t.dim, str(s.path))]);
1094
+ lines.push([span('', '')]);
1095
+ const body = str(s.content);
1096
+ const bodyLines = body.split('\n');
1097
+ const excerpt = bodyLines.slice(0, 8).join('\n');
1098
+ for (const l of excerpt.split('\n')) lines.push([span(t.white, l)]);
1099
+ if (bodyLines.length > 8) lines.push([span(t.gray, `… (${bodyLines.length} lines)`)]);
1100
+ return lines;
1101
+ }
1102
+
1103
+ // ── /mcp ─────────────────────────────────────────────────────────────────────
1104
+
1105
+ /** @param {Array|object} servers @param {Array} fromPaths */
1106
+ function buildMcp(servers, fromPaths, ctx = {}) {
1107
+ const t = themeOf(ctx);
1108
+ const entries = Array.isArray(servers)
1109
+ ? servers.map((srv, i) => [str(srv && srv.name) || String(i), srv])
1110
+ : servers && typeof servers === 'object'
1111
+ ? Object.entries(servers)
1112
+ : [];
1113
+ const paths = Array.isArray(fromPaths) ? fromPaths : [];
1114
+ const lines = [];
1115
+ lines.push([span(t.gold + BOLD, 'MCP servers'), span(BOLD_OFF, '')]);
1116
+ lines.push([span(t.gray, '─'.repeat(30))]);
1117
+ if (!entries.length) {
1118
+ lines.push([span(t.gray, 'No MCP servers configured.')]);
1119
+ } else {
1120
+ for (const [name, srv] of entries) {
1121
+ const cmd = typeof srv === 'string'
1122
+ ? srv
1123
+ : (str(srv && srv.command) + ' ' + (Array.isArray(srv && srv.args) ? srv.args.join(' ') : '')).trim();
1124
+ lines.push([span(t.white, ` ${str(name)}`), span(t.gray, ' '.repeat(Math.max(1, 14 - [...str(name)].length)) + cmd)]);
1125
+ }
1126
+ }
1127
+ lines.push([span('', '')]);
1128
+ lines.push([span(t.gray, 'This build has no MCP runtime — servers are configuration only.')]);
1129
+ lines.push([span(t.gray, '/mcp add <name> <command> [args…] · /mcp remove <name>')]);
1130
+ if (paths.length) lines.push([span(t.dim, 'Sources: ' + paths.join(', '))]);
1131
+ return lines;
1132
+ }
1133
+
1134
+ // ── /router ──────────────────────────────────────────────────────────────────
1135
+
1136
+ /** @param {object} state {autoRouter|router:{enabled,tiers}} */
1137
+ function buildRouter(state, ctx = {}) {
1138
+ const t = themeOf(ctx);
1139
+ const s = obj(state);
1140
+ const router = s.autoRouter && typeof s.autoRouter === 'object'
1141
+ ? s.autoRouter
1142
+ : s.router && typeof s.router === 'object'
1143
+ ? s.router
1144
+ : { enabled: false, tiers: {} };
1145
+ const tiers = router.tiers && typeof router.tiers === 'object' ? router.tiers : {};
1146
+ const lines = [];
1147
+ lines.push([span(t.gold + BOLD, 'Model router'), span(BOLD_OFF, '')]);
1148
+ lines.push([span(t.gray, '─'.repeat(30))]);
1149
+ lines.push([span(t.white, `auto-router: ${router.enabled ? 'on' : 'off'}`)]);
1150
+ lines.push([span(t.gray, ` simple ${str(tiers.simple) || '(auto)'}`)]);
1151
+ lines.push([span(t.gray, ` medium ${str(tiers.medium) || '(auto)'}`)]);
1152
+ lines.push([span(t.gray, ` complex ${str(tiers.complex) || '(auto)'}`)]);
1153
+ lines.push([span('', '')]);
1154
+ lines.push([span(t.gray, '/router on|off · /router set <simple|medium|complex> <modelId>')]);
1155
+ lines.push([span(t.dim, 'Routing config is persisted for the real CLI; this build serves the model chosen by /model.')]);
1156
+ return lines;
1157
+ }
1158
+
1159
+ // ── /billing (provider list) + /memory ───────────────────────────────────────
1160
+
1161
+ /** @param {object} state {memory|stats, embedStatus, compactState, compactCfg} */
1162
+ function buildMemory(state, ctx = {}) {
1163
+ const t = themeOf(ctx);
1164
+ const s = obj(state);
1165
+ const stats = statsFrom(s);
1166
+ const embedStatus = s.embedStatus && typeof s.embedStatus === 'object' ? s.embedStatus : null;
1167
+ const compact = s.compactState && typeof s.compactState === 'object' ? s.compactState : (s.at ? s : null);
1168
+ const cfg = s.compactCfg && typeof s.compactCfg === 'object' ? s.compactCfg : null;
1169
+
1170
+ const lines = [];
1171
+ lines.push([span(t.gold + BOLD, 'ÆGIS Memory'), span(BOLD_OFF, '')]);
1172
+ lines.push([span(t.gray, '─'.repeat(30))]);
1173
+ const total = stats ? num(stats.total) : 0;
1174
+ const sessions = stats ? num(stats.sessions) : 0;
1175
+ lines.push([span(t.white, `${total.toLocaleString()} memories across ${sessions} sessions`)]);
1176
+ if (stats && stats.roles && typeof stats.roles === 'object') {
1177
+ const parts = [];
1178
+ if (stats.roles.user != null) parts.push(`${num(stats.roles.user)} user`);
1179
+ if (stats.roles.assistant != null) parts.push(`${num(stats.roles.assistant)} assistant`);
1180
+ if (stats.roles.other) parts.push(`${num(stats.roles.other)} other`);
1181
+ if (parts.length) lines.push([span(t.gray, ` roles: ${parts.join(' · ')}`)]);
1182
+ }
1183
+ if (stats && stats.tiers) lines.push([span(t.gray, ` tiers: ${JSON.stringify(stats.tiers)}`)]);
1184
+ if (stats && stats.total != null) {
1185
+ const pct = total ? Math.round((num(stats.withEmbeddings) / total) * 100) : 0;
1186
+ if (embedStatus && embedStatus.engine) {
1187
+ lines.push([span(t.gray, ` embed: ${str(embedStatus.engine)} · ${pct}% coverage`)]);
1188
+ } else if (embedStatus) {
1189
+ lines.push([span(t.gray, ' embed: keyword-only')]);
1190
+ }
1191
+ if (stats.stale) lines.push([span(t.gray, ` stale: ${num(stats.stale)} entries >90d`)]);
1192
+ }
1193
+ if (compact) {
1194
+ lines.push([span(t.gray, compact.at ? ` last compact: ${str(compact.at).slice(0, 10)}` : ' auto-compact: never run')]);
1195
+ }
1196
+ if (cfg) {
1197
+ lines.push([span(t.gray, ` auto-compact: ${cfg.enabled ? 'on' : 'off'} (min ${num(cfg.minL1)} L1 · ${num(cfg.cooldownMin)}m cooldown)`)]);
1198
+ }
1199
+ lines.push([span('', '')]);
1200
+ lines.push([span(t.gray, '/memory tiers · /memory embeddings · /memory recall <q>')]);
1201
+ lines.push([span(t.gray, '/memory compact · /memory profile · /aegis-remember <note> to save')]);
1202
+ return lines;
1203
+ }
1204
+
1205
+ /** @param {object} state {memory|stats, pending, compactState, compactCfg} */
1206
+ function buildMemoryTiers(state, ctx = {}) {
1207
+ const t = themeOf(ctx);
1208
+ const s = obj(state);
1209
+ const stats = statsFrom(s);
1210
+ const pending = Array.isArray(s.pending) ? s.pending : [];
1211
+ const compact = s.compactState && typeof s.compactState === 'object' ? s.compactState : null;
1212
+ const cfg = s.compactCfg && typeof s.compactCfg === 'object' ? s.compactCfg : null;
1213
+
1214
+ const lines = [];
1215
+ lines.push([span(t.gold + BOLD, 'Memory Tiers'), span(BOLD_OFF, '')]);
1216
+ lines.push([span(t.gray, '─'.repeat(30))]);
1217
+ if (stats && stats.tiers) {
1218
+ lines.push([span(t.white, `L0 turns ${num(stats.tiers.L0)} raw session turns, volatile`)]);
1219
+ lines.push([span(t.white, `L1 atomic ${num(stats.tiers.L1)} facts · decisions · breakthroughs`)]);
1220
+ lines.push([span(t.white, `L2 scenario ${num(stats.tiers.L2)} distilled reusable context`)]);
1221
+ lines.push([span(t.white, `L3 profile ${num(stats.tiers.L3)} single distilled identity row`)]);
1222
+ }
1223
+ lines.push([span('', '')]);
1224
+ lines.push([span(t.gray, `pending L1 (auto-compact trigger): ${pending.length}`)]);
1225
+ if (compact && compact.at) {
1226
+ const sc = Array.isArray(compact.scenarios) ? compact.scenarios.length : 0;
1227
+ lines.push([span(t.gray, `last auto-compact: ${str(compact.at).slice(0, 16)} · ${sc} scenario${sc === 1 ? '' : 's'}`)]);
1228
+ } else {
1229
+ lines.push([span(t.gray, 'last auto-compact: never')]);
1230
+ }
1231
+ lines.push([span(t.gray, cfg
1232
+ ? `auto-compact: ${cfg.enabled ? 'on' : 'off'} · min ${num(cfg.minL1)} L1 · ${num(cfg.cooldownMin)}m cooldown`
1233
+ : 'auto-compact: on · min 5 L1 · 15m cooldown')]);
1234
+ lines.push([span('', '')]);
1235
+ lines.push([span(t.gray, '/memory compact runs maintenance manually')]);
1236
+ return lines;
1237
+ }
1238
+
1239
+ /** /memory embeddings [status] — engine chain + vector coverage panel. */
1240
+ function buildMemoryEmbeddings(status, stats, ctx = {}) {
1241
+ const t = themeOf(ctx);
1242
+ const st = status && typeof status === 'object' ? status : null;
1243
+ const s = stats && typeof stats === 'object' ? stats : null;
1244
+ const lines = [];
1245
+ lines.push([span(t.gold + BOLD, 'Memory Embeddings'), span(BOLD_OFF, '')]);
1246
+ lines.push([span(t.gray, '─'.repeat(30))]);
1247
+ if (st && st.engine) {
1248
+ lines.push([span(t.white, `engine: ${str(st.engine)} · ${str(st.model)}`)]);
1249
+ if (st.dim) lines.push([span(t.gray, ` dim: ${num(st.dim)}`)]);
1250
+ } else {
1251
+ lines.push([span(t.white, 'engine: keyword-only (no embedder resolved)')]);
1252
+ if (st && st.reason) lines.push([span(t.gray, ` reason: ${str(st.reason)}`)]);
1253
+ }
1254
+ lines.push([span(t.gray, `mode: ${st ? str(st.mode) || 'auto' : 'auto'} (env AEGIS_MEMORY_EMBED or memoryConfig.embedMode)`)]);
1255
+ if (s && s.total != null) {
1256
+ const total = num(s.total);
1257
+ const withEmb = num(s.withEmbeddings);
1258
+ const pct = total ? Math.round((withEmb / total) * 100) : 0;
1259
+ lines.push([span(t.gray, `coverage: ${withEmb}/${total} rows (${pct}%)`)]);
1260
+ if (s.embeddingModels && Object.keys(s.embeddingModels).length) {
1261
+ const parts = Object.entries(s.embeddingModels).map(([m, n]) => `${m}: ${num(n)}`);
1262
+ lines.push([span(t.gray, ` models: ${parts.join(' · ')}`)]);
1263
+ }
1264
+ if (s.stale) lines.push([span(t.gray, ` stale (>90d): ${num(s.stale)}`)]);
1265
+ }
1266
+ lines.push([span('', '')]);
1267
+ lines.push([span(t.gray, '/memory embeddings on|off toggles the engine chain')]);
1268
+ return lines;
1269
+ }
1270
+
1271
+ // ── /automode ────────────────────────────────────────────────────────────────
1272
+ //
1273
+ // This mode is called "automode" here, the same word the engine repo
1274
+ // (aegiscodex-dev) uses for its ← -on-an-empty-input mode: one name for one
1275
+ // idea across the two faces. `/yolo` remains a working ALIAS — it is what the
1276
+ // desktop switch, the persisted posture and every existing install's muscle
1277
+ // memory say, so dropping it would break the command for people who typed it
1278
+ // yesterday — but nothing user-facing is *labelled* YOLO any more.
1279
+
1280
+ function buildAutomode(state, ctx = {}) {
1281
+ const t = themeOf(ctx);
1282
+ const lines = [];
1283
+ lines.push([span(t.gold + BOLD, '⚠ automode enabled'), span(BOLD_OFF, '')]);
1284
+ lines.push([span(t.gray, '─'.repeat(30))]);
1285
+ lines.push([span(t.white, 'All tool executions are auto-approved: file writes,')]);
1286
+ lines.push([span(t.white, 'bash commands, and network requests run without asking.')]);
1287
+ lines.push([span('', '')]);
1288
+ lines.push([span(t.gray, 'Run /automode off to restore confirmations.')]);
1289
+ lines.push([span(t.gray, '(/yolo is accepted as an alias.)')]);
1290
+ return lines;
1291
+ }
1292
+
1293
+ // The pre-rename name, kept as an export so vendored copies and the panels
1294
+ // test's export list cannot break on the rename. Same function object.
1295
+ const buildYolo = buildAutomode;
1296
+
1297
+ // ── /release-notes ───────────────────────────────────────────────────────────
1298
+
1299
+ /**
1300
+ * `/release-notes` — the long form of the welcome box's `What's new`.
1301
+ *
1302
+ * This panel was stale in a way the welcome box was not. It opened at v0.1.0
1303
+ * and closed with three bullets declaring /login /doctor /permissions /mcp
1304
+ * /skills /hooks /agents /resume /rewind /compact /init /export /vim /yolo
1305
+ * "unavailable here — each says why". Every one of those is implemented now
1306
+ * (no command reports `unavailable`, and `stubPanel` has zero callers), so the
1307
+ * panel was telling anyone who ran it that a third of the command surface did
1308
+ * not exist. The list below is the real one.
1309
+ *
1310
+ * The command count is read from the registry at call time rather than frozen
1311
+ * as a literal, because a frozen count is precisely what nobody re-derived.
1312
+ */
1313
+ function buildReleaseNotes(state, ctx = {}) {
1314
+ const t = themeOf(ctx);
1315
+ const out = [];
1316
+ out.push([span(t.gold + BOLD, `What's new in v${VERSION}`), span(BOLD_OFF, '')]);
1317
+ out.push([span(t.gray, '─'.repeat(30))]);
1318
+
1319
+ const bullets = [
1320
+ 'v6.7.3 — the shared renderer is re-staged into cli/vendor.',
1321
+ 'v6.7.1 — terminal capabilities are read from the terminal, not the platform.',
1322
+ 'v6.7.0 — a file edit renders as a coloured diff block.',
1323
+ 'v6.6.0 — autonomous mode: a persistent work queue with a detached worker.',
1324
+ 'v6.5.x — the live tool row, /cost billed from the ledger the server settled at.',
1325
+ 'v6.4.0 — `aegiscode login`/`logout`/`key`, a 0600 credential store, /cloud and /sync.',
1326
+ ];
1327
+ for (const text of bullets) {
1328
+ const i = text.indexOf(' — ');
1329
+ const head = i === -1 ? text : text.slice(0, i);
1330
+ const body = i === -1 ? '' : text.slice(i + 3);
1331
+ out.push([span(t.green, '•'), span(t.gold, ` ${head}`), span(t.white, body ? ` — ${body}` : '')]);
1332
+ }
1333
+
1334
+ let counts = null;
1335
+ try {
1336
+ // Call-time require: commands.js requires this module, so a top-level
1337
+ // require would close a cycle at load for no benefit.
1338
+ const commands = require('./commands.js');
1339
+ counts = { n: commands.visibleCommands().length, cats: commands.CATEGORIES.length };
1340
+ } catch {
1341
+ // A release-notes panel is never worth failing a render over — the bullets
1342
+ // above stand on their own without the count.
1343
+ }
1344
+ if (counts) {
1345
+ out.push([span('', '')]);
1346
+ out.push([span(t.gray, ` ${counts.n} commands across ${counts.cats} categories — /help lists them.`)]);
1347
+ }
1348
+ out.push([span(t.gray, ' The version above is read from the package; the prose is not.')]);
1349
+ out.push([span(t.gray, ' Repo: https://aegiscloud.org')]);
1350
+ return out;
1351
+ }
1352
+
1353
+ // ── honest stubs (capability absent in this client) ──────────────────────────
1354
+
1355
+ /** Two-line honest panel: a heading and the reason it is absent. */
1356
+ function stubPanel(ctx, name, reason) {
1357
+ const t = themeOf(ctx);
1358
+ return [
1359
+ [span(t.gold + BOLD, name), span(BOLD_OFF, '')],
1360
+ [span(t.gray, ` ${name} is not available in aegiscode — ${reason}`)],
1361
+ ];
1362
+ }
1363
+
1364
+ function buildDoctor(state, ctx = {}) {
1365
+ return stubPanel(ctx, 'Doctor', 'it needs the local environment diagnostic suite.');
1366
+ }
1367
+
1368
+ function buildBuildPanel(args, ctx = {}) {
1369
+ const o = obj(args);
1370
+ const t = themeOf(ctx);
1371
+ return [
1372
+ [span(t.gold + BOLD, `⬡ Build: ${str(o.plan && o.plan.appName) || 'build'}`), span(BOLD_OFF, '')],
1373
+ [span(t.gray, ' Build is not available in aegiscode — it needs a local multi-model agent build loop.')],
1374
+ ];
1375
+ }
1376
+
1377
+ module.exports = {
1378
+ buildHelp,
1379
+ buildStatus,
1380
+ buildCost,
1381
+ buildContext,
1382
+ buildTokens,
1383
+ buildAgents,
1384
+ buildPermissions,
1385
+ buildModelList,
1386
+ buildRewindList,
1387
+ buildOnboarding,
1388
+ buildShellCompletion,
1389
+ buildTerminalSetup,
1390
+ buildTerminalCaps,
1391
+ buildPRs,
1392
+ buildBenchmark,
1393
+ buildWaifu,
1394
+ buildAegisStatus,
1395
+ buildAegisRecall,
1396
+ buildAegisMulti,
1397
+ buildBilling,
1398
+ buildMemory,
1399
+ buildMemoryTiers,
1400
+ buildRouter,
1401
+ buildAutomode,
1402
+ buildYolo,
1403
+ buildSkills,
1404
+ buildMcp,
1405
+ buildHooksStatus,
1406
+ buildHooksList,
1407
+ buildTroubleshooting,
1408
+ buildReleaseNotes,
1409
+ renderSessionsOverlay,
1410
+ // pure reference helpers with no missing capability
1411
+ buildAegisPrint,
1412
+ buildSkillDetail,
1413
+ buildMemoryEmbeddings,
1414
+ // honest stubs
1415
+ buildDoctor,
1416
+ buildBuildPanel,
1417
+ // local formatting helpers (exported for the panel tests)
1418
+ fmtEur,
1419
+ fmtTokens,
1420
+ };