aegis-desktop 1.0.32 → 1.0.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/renderer/diff.js +1 -1
- package/renderer/diffview.js +1 -1
- package/vendor/faces/cli/package.json +1 -1
- package/vendor/faces/cli/src/commands.js +1 -1
- package/vendor/faces/cli/src/diff.js +1 -1
- package/vendor/faces/cli/src/diffview.js +1 -1
- package/vendor/sandbox/provenance.json +7 -7
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "aegis-desktop",
|
|
3
3
|
"productName": "AEGIS Desktop",
|
|
4
4
|
"desktopName": "aegis-desktop",
|
|
5
|
-
"version": "1.0.
|
|
5
|
+
"version": "1.0.34",
|
|
6
6
|
"description": "Thin Electron host for AEGIS — a local chat UI over the shared client/aegis.js transport. Ships transport + UI only; engine logic stays server-side.",
|
|
7
7
|
"author": {
|
|
8
8
|
"name": "AEGIS Code",
|
package/renderer/diff.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";let fs=null,path=null;try{"function"==typeof require&&(fs=require("node:fs"),path=require("node:path"))}catch{fs=null,path=null}const DIFF_LIMITS={fileBytes:262144,lcsCells:25e4,rows:400,context:3};function splitLines(t){const e=String(null==t?"":t).replace(/\r\n?/g,"\n");if(""===e)return[];const n=e.split("\n");return n.length&&""===n[n.length-1]&&n.pop(),n}function lineDiff(t,e){const n=splitLines(t),s=splitLines(e);let i=0;for(;i<n.length&&i<s.length&&n[i]===s[i];)i++;let l=0;for(;l<n.length-i&&l<s.length-i&&n[n.length-1-l]===s[s.length-1-l];)l++;const r=n.slice(i,n.length-l),o=s.slice(i,s.length-l),
|
|
3
|
+
"use strict";let fs=null,path=null;try{"function"==typeof require&&(fs=require("node:fs"),path=require("node:path"))}catch{fs=null,path=null}const DIFF_LIMITS={fileBytes:262144,lcsCells:25e4,rows:400,context:3};function splitLines(t){const e=String(null==t?"":t).replace(/\r\n?/g,"\n");if(""===e)return[];const n=e.split("\n");return n.length&&""===n[n.length-1]&&n.pop(),n}function lineDiff(t,e){const n=splitLines(t),s=splitLines(e);let i=0;for(;i<n.length&&i<s.length&&n[i]===s[i];)i++;let l=0;for(;l<n.length-i&&l<s.length-i&&n[n.length-1-l]===s[s.length-1-l];)l++;const r=n.slice(i,n.length-l),o=s.slice(i,s.length-l),c=lcsOps(r,o),a=null===c,u=c||[...r.map((t=>({sign:"-",text:t}))),...o.map((t=>({sign:"+",text:t})))];if(!u.some((t=>" "!==t.sign)))return{rows:[],adds:0,dels:0,truncated:a};const g=DIFF_LIMITS.context,p=[];let f=1,d=1;const h=i>g?i-g:0,x=h;x>0&&p.push({sign:" ",text:"",marker:!0,note:`… ${x} unchanged line${1===x?"":"s"}`});for(let t=h;t<i;t++)p.push({sign:" ",text:n[t],no:d}),d++,f++;for(const t of u)" "===t.sign?(p.push({sign:" ",text:t.text,no:d}),d++,f++):"-"===t.sign?(p.push({sign:"-",text:t.text,no:f}),f++):(p.push({sign:"+",text:t.text,no:d}),d++);const m=s.length-l,I=Math.min(l,g);d=m+1;for(let t=0;t<I;t++)p.push({sign:" ",text:s[m+t],no:d}),d++,f++;if(l>g){const t=l-g;p.push({sign:" ",text:"",marker:!0,note:`… ${t} unchanged line${1===t?"":"s"}`})}const _=p.filter((t=>"+"===t.sign)).length,w=p.filter((t=>"-"===t.sign)).length;let y=p,F=!1;return y.length>DIFF_LIMITS.rows&&(y=y.slice(0,DIFF_LIMITS.rows),y.push({sign:" ",text:"",marker:!0,note:`… ${p.length-DIFF_LIMITS.rows} more diff lines`}),F=!0),{rows:y,adds:_,dels:w,truncated:a||F}}function lcsOps(t,e){const n=t.length,s=e.length;if(!n||!s)return[...t.map((t=>({sign:"-",text:t}))),...e.map((t=>({sign:"+",text:t})))];if(n*s>DIFF_LIMITS.lcsCells)return null;const i=s+1,l=new Int32Array((n+1)*i);for(let r=n-1;r>=0;r--)for(let n=s-1;n>=0;n--)l[r*i+n]=t[r]===e[n]?l[(r+1)*i+(n+1)]+1:Math.max(l[(r+1)*i+n],l[r*i+(n+1)]);const r=[];let o=0,c=0;for(;o<n&&c<s;)t[o]===e[c]?(r.push({sign:" ",text:t[o]}),o++,c++):l[(o+1)*i+c]>=l[o*i+(c+1)]?(r.push({sign:"-",text:t[o]}),o++):(r.push({sign:"+",text:e[c]}),c++);for(;o<n;)r.push({sign:"-",text:t[o++]});for(;c<s;)r.push({sign:"+",text:e[c++]});return r}function fileRows(t){const e=splitLines(t),n=e.slice(0,DIFF_LIMITS.rows),s=n.map(((t,e)=>({sign:" ",text:t,no:e+1}))),i=e.length-n.length;return i>0&&s.push({sign:" ",text:"",marker:!0,note:`… ${i} more lines`}),{rows:s,adds:0,dels:0,truncated:i>0}}function readCapped(t,e={}){if(!fs)return{text:null,missing:!0};const n=null==e.bytes?DIFF_LIMITS.fileBytes:e.bytes;try{const e=fs.statSync(t);if(!e.isFile())return{text:null,missing:!0};const s=fs.readFileSync(t,"utf8");return e.size>n?{text:s.slice(0,n),missing:!1,truncated:!0}:{text:s,missing:!1}}catch{return{text:null,missing:!0}}}function shortPath(t,e){const n=String(t||"");if(!e||!path)return n;const s=path.relative(e,n);if(s&&!s.startsWith("..")&&!path.isAbsolute(s))return s;const i=n.split(path.sep).filter(Boolean),l=n.startsWith(path.sep)?path.sep:"";return i.length>2?l+"…"+path.sep+i.slice(-2).join(path.sep):n}function editPreview(t,e,n={}){try{const s=null==n.cwd?"undefined"!=typeof process?process.cwd():"":n.cwd,i=n.readFile||readCapped;if(!e||"object"!=typeof e)return null;const l="string"==typeof e.file_path?e.file_path:"string"==typeof e.path?e.path:null;if(!l)return null;const r={file:l,short:shortPath(l,s)};if("Edit"===t||"editFile"===t)return"string"!=typeof e.old_string||"string"!=typeof e.new_string?null:Object.assign({kind:"Update"},r,lineDiff(e.old_string,e.new_string),{replaceAll:!!e.replace_all});if("Write"===t||"writeFile"===t){if("string"!=typeof e.content)return null;const t=i(l)||{text:null,missing:!0};let n=lineDiff(null==t.text?"":t.text,e.content);return n.rows.length||t.missing||!e.content||(n=fileRows(e.content)),Object.assign({kind:t.missing?"Create":"Write"},r,n,{truncated:n.truncated||!!t.truncated})}if("MultiEdit"===t){const t=(Array.isArray(e.edits)?e.edits:[]).filter((t=>t&&"string"==typeof t.old_string&&"string"==typeof t.new_string));if(!t.length)return null;const n=i(l)||{text:null,missing:!0};if("string"==typeof n.text){let e=n.text,s=0;for(const n of t)-1!==e.indexOf(n.old_string)?e=n.replace_all?e.split(n.old_string).join(n.new_string):e.replace(n.old_string,n.new_string):s++;const i=lineDiff(n.text,e);return Object.assign({kind:"Update"},r,i,{misses:s,replaceAll:t.some((t=>t.replace_all))})}let s=[],o=0,c=0,a=!1;return t.forEach(((e,n)=>{const i=lineDiff(e.old_string,e.new_string);n&&s.push({sign:" ",text:"",marker:!0,note:`… edit ${n+1} of ${t.length}`}),s=s.concat(i.rows),o+=i.adds,c+=i.dels,a=a||i.truncated})),Object.assign({kind:"Update"},r,{rows:s,adds:o,dels:c,truncated:a,stacked:t.length})}return null}catch{return null}}function changeSummary(t){const e=[];return t.adds&&e.push(`Added ${t.adds} line${1===t.adds?"":"s"}`),t.dels&&e.push(`removed ${t.dels} line${1===t.dels?"":"s"}`),e.length?e.join(", "):"no line changes"}"undefined"!=typeof module&&module.exports&&(module.exports={DIFF_LIMITS:DIFF_LIMITS,splitLines:splitLines,lineDiff:lineDiff,lcsOps:lcsOps,readCapped:readCapped,shortPath:shortPath,changeSummary:changeSummary,editPreview:editPreview});
|
package/renderer/diffview.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const AUTO_OPEN_ROWS=30,MAX_BLOCK_ROWS=200,DIFF_COLORS={delFg:"#dc5a5a",delBg:"#3d0100",addFg:"#50c850",addBg:"#022800",delHiFg:"#f8f8f2",delHiBg:"#5c0200",addHiFg:"#ffffff",addHiBg:"#044700",codeFg:"#f8f8f2",gutter:"#787878",kind:"#c099ff",kw:"#66d9ef",fn:"#a6e22e",str:"#e6db74",num:"#ae81ff",comment:"#75715e"},KEYWORDS=new Set(["const","let","var","function","return","if","else","for","while","do","switch","case","break","continue","import","export","from","default","class","extends","new","try","catch","finally","throw","async","await","yield","static","typeof","instanceof","in","of","delete","this","super","null","undefined","true","false","def","elif","lambda","pass","raise","with","as","not","and","or","is","None","True","False","self","fn","mut","pub","impl","struct","enum","trait","match","package","func","defer","chan","nil","echo","local","then","fi","esac"]);function highlightLine(e,t){const n=t||DIFF_COLORS,i=[],d=String(null==e?"":e),l=/(\/\/[^\n]*|#[^\n]*|\/\*[\s\S]*?\*\/)|('(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|`(?:\\.|[^`\\])*`)|(0[xX][0-9a-fA-F]+|\d+(?:\.\d+)?)|([A-Za-z_$][A-Za-z0-9_$]*)/g,a=(e,t)=>{e&&i.push({t:e,c:t})};let o,s=0;for(;o=l.exec(d);){if(o.index>s&&a(d.slice(s,o.index),n.codeFg),o[1])a(o[1],n.comment);else if(o[2])a(o[2],n.str);else if(o[3])a(o[3],n.num);else{const e=o[4],t=/^\s*\(/.test(d.slice(o.index+e.length));a(e,KEYWORDS.has(e)?n.kw:t?n.fn:n.codeFg)}s=o.index+o[0].length}return s<d.length&&a(d.slice(s),n.codeFg),i}function markIntraLine(e){for(let t=0;t<e.length;t++){if("-"!==e[t].sign)continue;let n=t;for(;n<e.length&&"-"===e[n].sign;)n++;let i=n;for(;i<e.length&&"+"===e[i].sign;)i++;const d=n-t;if(d&&d===i-n)for(let i=0;i<d;i++){const d=intraLine(e[t+i].text,e[n+i].text);d&&(e[t+i].hi={start:d.delStart,end:d.delEnd,side:"del"},e[n+i].hi={start:d.addStart,end:d.addEnd,side:"add"})}t=i-1}return e}function intraLine(e,t){const n=[...String(null==e?"":e)],i=[...String(null==t?"":t)];let d=0;for(;d<n.length&&d<i.length&&n[d]===i[d];)d++;let l=0;for(;l<n.length-d&&l<i.length-d&&n[n.length-1-l]===i[i.length-1-l];)l++;return d+l<.4*(Math.max(n.length,i.length)||1)?null:{delStart:d,delEnd:n.length-l,addStart:d,addEnd:i.length-l}}function defaultOpen(e){return!(!e||!e.rows)&&e.rows.length<=AUTO_OPEN_ROWS}function tokenSpan(e,t,n,i,d){const l=e.createElement("span");return i?(l.style.background=i,l.style.color=d):l.style.color=n,l.textContent=String(t),l}function appendCode(e,t,n,i){const d=String(null==n?"":n);let l=0;for(const n of highlightLine(d,DIFF_COLORS)){const d=[...n.t],a=l,o=l+d.length;if(l=o,!i||o<=i.start||a>=i.end){t.appendChild(tokenSpan(e,n.t,n.c));continue}const s=Math.max(i.start,a)-a,r=Math.min(i.end,o)-a;if(s>0&&t.appendChild(tokenSpan(e,d.slice(0,s).join(""),n.c)),r>s){const n="del"===i.side?DIFF_COLORS.delHiBg:DIFF_COLORS.addHiBg,l="del"===i.side?DIFF_COLORS.delHiFg:DIFF_COLORS.addHiFg;t.appendChild(tokenSpan(e,d.slice(s,r).join(""),null,n,l))}r<d.length&&t.appendChild(tokenSpan(e,d.slice(r).join(""),n.c))}}function renderRow(e,t,n){const i="-"===t.sign?"del":"+"===t.sign?"add":"ctx",d=e.createElement("div");d.className=`diff-row diff-${i}`;const l=e.createElement("span");l.className="diff-gutter",l.textContent=`${String(null==t.no?"":t.no).padStart(n)} `,d.appendChild(l);const a=e.createElement("span");a.className="diff-sign",a.textContent=" "===t.sign?" ":t.sign,d.appendChild(a);const o=e.createElement("span");return o.className="diff-code",appendCode(e,o,t.text,t.hi),d.appendChild(o),d}function markerRow(e,t){const n=e.createElement("div");n.className="diff-row diff-marker";const i=e.createElement("span");return i.className="diff-code",i.textContent=String(null==t?"":t),n.appendChild(i),n}function renderDiffBlock(e,t,n={}){const i=t||(void 0!==i?i:null);if(!i||!e||!e.rows)return null;let d=null==n.open?defaultOpen(e):!!n.open;const l=i.createElement("div");l.className="diff-block";const a=i.createElement("div");a.className="diff-summary","function"==typeof a.setAttribute&&(a.setAttribute("role","button"),a.setAttribute("aria-expanded",String(d)));const o=i.createElement("div");function s(){a.textContent="";const t=[{t:"⎿ ",c:DIFF_COLORS.gutter},{t:`${e.kind}(${e.short})`,c:DIFF_COLORS.kind}];e.adds&&t.push({t:` +${e.adds}`,c:DIFF_COLORS.addFg}),e.dels&&t.push({t:` -${e.dels}`,c:DIFF_COLORS.delFg}),e.adds||e.dels||t.push({t:" no line changes",c:DIFF_COLORS.gutter}),e.misses&&t.push({t:` ${e.misses} edit(s) not applied`,c:"#ffd166"}),
|
|
3
|
+
"use strict";const AUTO_OPEN_ROWS=30,MAX_BLOCK_ROWS=200,DIFF_COLORS={delFg:"#dc5a5a",delBg:"#3d0100",addFg:"#50c850",addBg:"#022800",delHiFg:"#f8f8f2",delHiBg:"#5c0200",addHiFg:"#ffffff",addHiBg:"#044700",codeFg:"#f8f8f2",gutter:"#787878",kind:"#c099ff",kw:"#66d9ef",fn:"#a6e22e",str:"#e6db74",num:"#ae81ff",comment:"#75715e"},KEYWORDS=new Set(["const","let","var","function","return","if","else","for","while","do","switch","case","break","continue","import","export","from","default","class","extends","new","try","catch","finally","throw","async","await","yield","static","typeof","instanceof","in","of","delete","this","super","null","undefined","true","false","def","elif","lambda","pass","raise","with","as","not","and","or","is","None","True","False","self","fn","mut","pub","impl","struct","enum","trait","match","package","func","defer","chan","nil","echo","local","then","fi","esac"]);function highlightLine(e,t){const n=t||DIFF_COLORS,i=[],d=String(null==e?"":e),l=/(\/\/[^\n]*|#[^\n]*|\/\*[\s\S]*?\*\/)|('(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|`(?:\\.|[^`\\])*`)|(0[xX][0-9a-fA-F]+|\d+(?:\.\d+)?)|([A-Za-z_$][A-Za-z0-9_$]*)/g,a=(e,t)=>{e&&i.push({t:e,c:t})};let o,s=0;for(;o=l.exec(d);){if(o.index>s&&a(d.slice(s,o.index),n.codeFg),o[1])a(o[1],n.comment);else if(o[2])a(o[2],n.str);else if(o[3])a(o[3],n.num);else{const e=o[4],t=/^\s*\(/.test(d.slice(o.index+e.length));a(e,KEYWORDS.has(e)?n.kw:t?n.fn:n.codeFg)}s=o.index+o[0].length}return s<d.length&&a(d.slice(s),n.codeFg),i}function markIntraLine(e){for(let t=0;t<e.length;t++){if("-"!==e[t].sign)continue;let n=t;for(;n<e.length&&"-"===e[n].sign;)n++;let i=n;for(;i<e.length&&"+"===e[i].sign;)i++;const d=n-t;if(d&&d===i-n)for(let i=0;i<d;i++){const d=intraLine(e[t+i].text,e[n+i].text);d&&(e[t+i].hi={start:d.delStart,end:d.delEnd,side:"del"},e[n+i].hi={start:d.addStart,end:d.addEnd,side:"add"})}t=i-1}return e}function intraLine(e,t){const n=[...String(null==e?"":e)],i=[...String(null==t?"":t)];let d=0;for(;d<n.length&&d<i.length&&n[d]===i[d];)d++;let l=0;for(;l<n.length-d&&l<i.length-d&&n[n.length-1-l]===i[i.length-1-l];)l++;return d+l<.4*(Math.max(n.length,i.length)||1)?null:{delStart:d,delEnd:n.length-l,addStart:d,addEnd:i.length-l}}function defaultOpen(e){return!(!e||!e.rows)&&e.rows.length<=AUTO_OPEN_ROWS}function tokenSpan(e,t,n,i,d){const l=e.createElement("span");return i?(l.style.background=i,l.style.color=d):l.style.color=n,l.textContent=String(t),l}function appendCode(e,t,n,i){const d=String(null==n?"":n);let l=0;for(const n of highlightLine(d,DIFF_COLORS)){const d=[...n.t],a=l,o=l+d.length;if(l=o,!i||o<=i.start||a>=i.end){t.appendChild(tokenSpan(e,n.t,n.c));continue}const s=Math.max(i.start,a)-a,r=Math.min(i.end,o)-a;if(s>0&&t.appendChild(tokenSpan(e,d.slice(0,s).join(""),n.c)),r>s){const n="del"===i.side?DIFF_COLORS.delHiBg:DIFF_COLORS.addHiBg,l="del"===i.side?DIFF_COLORS.delHiFg:DIFF_COLORS.addHiFg;t.appendChild(tokenSpan(e,d.slice(s,r).join(""),null,n,l))}r<d.length&&t.appendChild(tokenSpan(e,d.slice(r).join(""),n.c))}}function renderRow(e,t,n){const i="-"===t.sign?"del":"+"===t.sign?"add":"ctx",d=e.createElement("div");d.className=`diff-row diff-${i}`;const l=e.createElement("span");l.className="diff-gutter",l.textContent=`${String(null==t.no?"":t.no).padStart(n)} `,d.appendChild(l);const a=e.createElement("span");a.className="diff-sign",a.textContent=" "===t.sign?" ":t.sign,d.appendChild(a);const o=e.createElement("span");return o.className="diff-code",appendCode(e,o,t.text,t.hi),d.appendChild(o),d}function markerRow(e,t){const n=e.createElement("div");n.className="diff-row diff-marker";const i=e.createElement("span");return i.className="diff-code",i.textContent=String(null==t?"":t),n.appendChild(i),n}function renderDiffBlock(e,t,n={}){const i=t||(void 0!==i?i:null);if(!i||!e||!e.rows)return null;let d=null==n.open?defaultOpen(e):!!n.open;const l=i.createElement("div");l.className="diff-block";const a=i.createElement("div");a.className="diff-summary","function"==typeof a.setAttribute&&(a.setAttribute("role","button"),a.setAttribute("aria-expanded",String(d)));const o=i.createElement("div");function s(){a.textContent="";const t=[{t:"⎿ ",c:DIFF_COLORS.gutter},{t:`${e.kind}(${e.short})`,c:DIFF_COLORS.kind}];if(e.adds&&t.push({t:` +${e.adds}`,c:DIFF_COLORS.addFg}),e.dels&&t.push({t:` -${e.dels}`,c:DIFF_COLORS.delFg}),e.adds||e.dels||t.push({t:" no line changes",c:DIFF_COLORS.gutter}),e.misses&&t.push({t:` ${e.misses} edit(s) not applied`,c:"#ffd166"}),e.rows&&e.rows.length){const n=d?"· click to collapse":e.adds||e.dels?"· click to view diff":"· click to view file";t.push({t:` ${n}`,c:DIFF_COLORS.comment})}for(const e of t){const t=i.createElement("span");t.style.color=e.c,t.textContent=e.t,a.appendChild(t)}"function"==typeof a.setAttribute&&a.setAttribute("aria-expanded",String(d))}function r(){if(o.textContent="",!d)return;const t=markIntraLine(e.rows.slice(0,200).map((e=>Object.assign({},e))));let n=1;for(const e of t)e.no&&e.no>n&&(n=e.no);const l=Math.max(2,String(n).length);for(const e of t)e.marker?o.appendChild(markerRow(i,e.note)):o.appendChild(renderRow(i,e,l));const a=e.rows.length-200;a>0&&o.appendChild(markerRow(i,`… ${a} more diff lines`)),e.truncated&&o.appendChild(markerRow(i,"… diff truncated (file too large to compare in full)"))}function c(){d=!d,s(),r()}return o.className="diff-body","function"==typeof a.addEventListener&&(a.addEventListener("click",c),a.addEventListener("keydown",(e=>{!e||"Enter"!==e.key&&" "!==e.key||("function"==typeof e.preventDefault&&e.preventDefault(),c())}))),s(),r(),l.appendChild(a),l.appendChild(o),l}"undefined"!=typeof module&&module.exports&&(module.exports={AUTO_OPEN_ROWS:AUTO_OPEN_ROWS,MAX_BLOCK_ROWS:200,DIFF_COLORS:DIFF_COLORS,defaultOpen:defaultOpen,highlightLine:highlightLine,markIntraLine:markIntraLine,renderDiffBlock:renderDiffBlock});
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aegiscode",
|
|
3
3
|
"productName": "AEGIS Code",
|
|
4
|
-
"version": "7.0.
|
|
4
|
+
"version": "7.0.34",
|
|
5
5
|
"description": "aegiscode — the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "AEGIS Code",
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
3
|
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execSync:execSync}=require("node:child_process"),{span:span}=require("./screen.js"),{C:C,BOLD:BOLD,BOLD_OFF:BOLD_OFF,THEME_TABLE:THEME_TABLE,themeContradicts:themeContradicts}=require("./theme.js"),{caps:caps,setCaps:setCaps,resetCaps:resetCaps,describe:describe,probeTerminalBackground:probeTerminalBackground}=require("./caps.js"),panels=require("./panels.js"),overlays=require("./overlays.js"),{updateConfig:updateConfig,loadConfig:loadConfig,loadPermissions:loadPermissions,savePermissions:savePermissions,addPermissionRule:addPermissionRule,DEFAULT_PERMISSIONS:DEFAULT_PERMISSIONS,permissionsPath:permissionsPath,configPath:configPath,aegisDir:aegisDir,setConfirmPosture:setConfirmPosture,setPermissionDefaultMode:setPermissionDefaultMode,confirmPosture:confirmPosture,permissionMode:permissionMode,setPermissionMode:setPermissionMode,PERMISSION_MODES_LOCAL:PERMISSION_MODES_LOCAL,memoryPersistState:memoryPersistState,setMemoryPersist:setMemoryPersist}=require("./config.js"),{auditExposure:auditExposure,repairExposure:repairExposure}=require("./securefs.js"),{copyToClipboard:copyToClipboard}=require("./clipboard.js"),{snapshotCheckpoint:snapshotCheckpoint,listCheckpoints:listCheckpoints,loadCheckpoint:loadCheckpoint}=require("./checkpoint.js"),{signupUrl:signupUrl,goUrl:goUrl}=require("./signup.js"),screens=require("./screens.js"),{summarizeTranscript:summarizeTranscript,recapLine:recapLine}=require("./summarize.js"),{sessionAccounting:sessionAccounting,accountingFromUsage:accountingFromUsage,estimateTokens:estimateTokens}=require("./tokens.js"),{effortRung:effortRung}=require("./engine.js"),{transcriptToMarkdown:transcriptToMarkdown,transcriptToJSON:transcriptToJSON,writeExportFile:writeExportFile,lastAssistantText:lastAssistantText}=require("./export.js"),{detectDevCommand:detectDevCommand,runDevServer:runDevServer}=require("./devrun.js"),{PING_MODES:PING_MODES,DEFAULT_PING_MODE:DEFAULT_PING_MODE,normalizePingMode:normalizePingMode,normalizePingSeconds:normalizePingSeconds,buildPing:buildPing,writePing:writePing}=require("./ping.js"),{addTodo:addTodo,completeTodo:completeTodo,clearTodos:clearTodos,formatTodos:formatTodos,todosFile:todosFile}=require("./todos.js"),{configRows:configRows,formatConfigRows:formatConfigRows,setConfigValue:setConfigValue,resetConfigValue:resetConfigValue,fullValue:fullValue,summarizeValue:summarizeValue,configStore:configStore}=require("./settings.js"),credentials=require("./credentials.js"),cloudsync=require("./cloudsync.js"),{maskKey:maskKey,fmtTokens:fmtTokens,shortCwd:shortCwd}=require("./format.js"),{pickerEntries:pickerEntries}=require("./models.js"),{resolveShared:resolveShared}=require("./sharedpaths.js"),sandboxLib=require(resolveShared(path.join("desktop","lib","local","sandbox.js"))),{createCliEntitlement:createCliEntitlement,paymentView:paymentView,probeFee:probeFee}=require("./entitlement.js"),{openUrl:openUrl,URLS:URLS}=require("./system.js"),sysdiag=require("./sysdiag.js"),{sniffProject:sniffProject,buildAegisMd:buildAegisMd}=require("./init.js"),{upgradeAdvice:upgradeAdvice,latestPublishedVersion:latestPublishedVersion,applyUpgrade:applyUpgrade,installMethod:installMethod}=require("./update.js"),{AGENT_PRESETS:AGENT_PRESETS,agentRoles:agentRoles,composeAgentPrompt:composeAgentPrompt,composeResearchPrompt:composeResearchPrompt,composeDebatePrompt:composeDebatePrompt}=require("./agents.js"),{aggregateSessionUsage:aggregateSessionUsage,pruneSessionHistory:pruneSessionHistory,readResumeList:readResumeList}=require("./history.js"),naming=require("./naming.js"),{sessionStore:sessionStore}=require("./shared.js"),RESUME_SEARCH_LIMIT=200,namingBackfillAttempted=new Set,NAMING_BACKFILL_MAX=3;function backfillSessionNames(e){let t,n=3;try{t=sessionStore.listSessions(aegisDir())}catch{return}for(const o of t){if(n<=0)break;if(!o||!o.id||!0===o.named||namingBackfillAttempted.has(o.id))continue;const t=(Array.isArray(o.messages)?o.messages:[]).find((e=>e&&"user"===e.role&&e.content));t&&(namingBackfillAttempted.add(o.id),n-=1,naming.nameSession(sessionStore,aegisDir(),o.id,t.content,{callModel:(t,n)=>e.ask(t,{system:n&&n.system||naming.TITLE_SYSTEM,maxTokens:64,signal:n&&n.signal}).then((e=>e&&e.text||null)).catch((()=>null))}).catch((()=>{})))}}let markdownModule=null;try{markdownModule=require("./markdown.js")}catch{markdownModule=null}const VERSION=require("../package.json").version,CATEGORIES=[{id:"session",label:"Session & context"},{id:"workspace",label:"Workspace"},{id:"model",label:"Model & behavior"},{id:"data",label:"Data"},{id:"auth",label:"Auth"},{id:"support",label:"Support"},{id:"fun",label:"Fun"},{id:"aegis",label:"Aegis plugin"},{id:"custom",label:"Custom"}],categoryLabel=e=>(CATEGORIES.find((t=>t.id===e))||{}).label||e,EFFORT_LEVELS=overlays.EFFORT_VALUES,note=(e,t)=>e.push({role:"note",text:t}),panel=(e,t)=>e.push({role:"panel",lines:t}),tip=(e,t)=>e.push({role:"tip",text:t}),done=(e,t)=>e.push({role:"done",text:t});function composeMultiFanoutPrompt(e){return["Execute this task as a multi-agent fan-out.","",`Task: ${e}`,"",`Workspace: ${process.cwd()}`,"","Use the task tool to delegate the independent parts to specialist subagents. Delegations run CONCURRENTLY when you emit them as multiple task calls in ONE assistant message, so put independent ones in the same message rather than one per message:","- reconnaissance first (scanner for secrets/unsafe patterns, analyzer for refactor targets),","- then design (architect, or planner when the work is a change to existing code),","- then an implementer subagent to make the change.","Finally review the result (reviewer subagent), fix what it finds, and verify with the repository's real commands.","","Return one consolidated report: what each subagent found, the files you changed, the exact commands you ran and their real output, and anything still blocked. No preamble."].join("\n")}async function multiData(e,t){const n=composeMultiFanoutPrompt(t),o=e&&e.withWorking?t=>e.withWorking(t):e=>e();if(!e||"function"!=typeof e.ask&&"function"!=typeof e.runPrompt)return{error:"No agent loop in this context — the fan-out prompt was composed, not run."};try{if("function"==typeof e.ask){const t=await o((t=>e.ask(n,{signal:t}))),r=t&&t.text||"";return t&&t.interrupted&&!r?{cancelled:!0}:r?{result:r,model:t&&t.model||e.ctx&&e.ctx.model||null,provider:"aegis"}:{error:"The multi-agent fan-out returned nothing (the turn failed before it could delegate)."}}return await o((()=>e.runPrompt(n))),{streamed:!0}}catch(e){return{error:`ÆGIS multi failed — ${e&&e.message||e}`}}}async function runMultiCommand(e,t,{yolo:n=!1,title:o="ÆGIS Multi"}={}){n&&(setConfirmPosture(!1),panel(e,panels.buildAutomode(e.state(),e.ctx))),note(e,"Running the multi-agent fan-out — the engine delegates to specialist subagents (headless: this skips aegis-cli's own confirmation step)."),e.render();const r=await multiData(e,t);return r.cancelled?(note(e,"ÆGIS multi cancelled."),e.render(),!0):r.error?(note(e,r.error),panel(e,panels.buildAegisMulti(t,e.ctx)),e.render(),!0):(r.streamed||(panel(e,panels.buildAegisPrint(o,r,e.ctx)),e.render()),!0)}const upgradePanelLines=e=>e.map((e=>[span(C.white,e)]));async function billingPayment(e){if(!e||!e.client)return;let t;try{t=createCliEntitlement({aegis:e.client})}catch{return}const n=e.withWorking?t=>e.withWorking(t):e=>e();try{await n((()=>t.refresh({force:!0})))}catch{}const o=await probeFee();return paymentView(t.current(),{host:"cli",fee:o})}async function loadModels(e){try{return await e.loadModels()||[]}catch{return[]}}async function mergedPickerModels(e){const t=e.ctx&&e.ctx.modelClass||"aegis",n=pickerEntries(await loadModelsFor(e,"aegis",t)).map((e=>({...e,cls:"aegis"}))),o=pickerEntries(await loadModelsFor(e,"byok",t)).map((e=>({...e,cls:e.cls||"byok"}))),r=pickerEntries(await loadModelsFor(e,"pro",t)).map((e=>({...e,cls:"pro"}))),s=[],a=new Set;for(const e of[...n,...o,...r]){const t=String(e&&e.id||"");t&&!a.has(t)&&(a.add(t),s.push(e))}return s}async function loadModelsFor(e,t,n){if("function"==typeof e.listModelsFor)try{return await e.listModelsFor(t)||[]}catch{return[]}if(t!==n||"function"!=typeof e.loadModels)return[];try{return await e.loadModels()||[]}catch{return[]}}const cloudReady=()=>credentials.hasApiKey(),{withByokAdditions:withByokAdditions}=require(resolveShared(path.join("client","byok-catalog.js"))),{withUserModels:withUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel,userModelIdsFor:userModelIdsFor,userModelsPath:userModelsPath}=require(resolveShared(path.join("client","user-models.js"))),catalogClient=require(resolveShared(path.join("client","catalog-client.js"))),{withCatalog:withCatalog}=catalogClient,{discoverModels:discoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=require(resolveShared(path.join("client","model-discovery.js")));function byokKeyForProvider(e,t){const n=String(t||"").trim().toLowerCase();if(!n)return"";try{const t=e&&e.settings&&e.settings();if(t&&"function"==typeof t.rawKey&&"function"==typeof e.byokNamespace){const o=t.rawKey(e.byokNamespace(n));if("string"==typeof o&&o.trim())return o.trim()}}catch{}try{const{providerKeyFromEnv:e}=require(resolveShared(path.join("client","env-file.js")));return(e(n)||{}).key||""}catch{return""}}async function discoverProviderModels(e,t,n){try{return await discoverVendorModels(t,{key:n,fetchImpl:e&&e.fetchImpl})}catch(e){return{ok:!1,provider:t,supported:!0,error:e&&e.message||String(e)}}}async function offeredModelIds(e,t,n){const o=await discoverProviderModels(e,t,n);return o&&o.ok&&Array.isArray(o.ids)&&o.ids.length?o.ids:void 0}function splitCommandWords(e){const t=[];let n="",o=null,r=!1;for(const s of String(null==e?"":e))o?s===o?o=null:n+=s:'"'!==s&&"'"!==s?/\s/.test(s)?(n||r)&&(t.push(n),n="",r=!1):(n+=s,r=!0):(o=s,r=!0);return(n||r)&&t.push(n),t}function savedByokBaseURL(e,t){try{const n=e&&e.settings&&e.settings();if(!n||"function"!=typeof n.get||"function"!=typeof e.byokNamespace)return"";const o=n.get(e.byokNamespace(t))||{};return String(o.baseURL||"").trim()}catch{return""}}function addManyUserModels(e,t){let n=0,o=0;const r=[],s=[];for(const a of t)try{addUserModel(e,a).added?n+=1:r.push(a)}catch(e){const i=e&&e.message||String(e);if(/the cap/.test(i)){o=t.length-n-r.length-s.length;break}s.push({id:a,reason:i})}return{added:n,already:r,failed:s,capped:o}}async function byokCatalog(e){if(!e||"function"!=typeof e.byokProviders)return null;try{const t=await e.byokProviders();refreshCatalogInBackground(e);const n=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[])));return n.length?n:null}catch{return null}}function refreshCatalogInBackground(e){try{let t=!0;try{const e=catalogClient.read();t=!e||e.stale}catch{t=!0}if(!t)return null;if("function"!=typeof e.catalog)return null;let n=null;try{const e=catalogClient.read();n=e&&e.data&&e.data.snapshot&&e.data.snapshot.etag||null}catch{n=null}const o=catalogClient.refresh((async({cursor:t,limit:n,etag:o})=>{try{return await e.catalog("models",{cursor:t,limit:n},{etag:o||void 0})}catch(e){if(e&&304===e.status)return{notModified:!0};throw e}}),{etag:n});return o&&"function"==typeof o.catch&&o.catch((()=>{})),o}catch{return null}}function findByokProvider(e,t){const n=String(t||"").trim().toLowerCase();if(!e)return{provider:null,exact:!1};const o=e.find((e=>e.id===n));if(o)return{provider:o,exact:!0};const r=e.filter((e=>[e.id,e.label,...e.aliases||[]].filter(Boolean).some((e=>String(e).toLowerCase()===n))));return 1===r.length?{provider:r[0],exact:!1}:r.length>1?{ambiguous:r.map((e=>e.id))}:{provider:null,exact:!1}}function byokProviderLines(e){const t=[];for(const n of e){const e=n.configured?span(C.green,"set"+(n.masked?` (${n.masked})`:"")):span(C.gray,"not set"),o=[span(C.gold+BOLD,` ${n.id}`)];n.label&&o.push(span(C.gray,` — ${n.label}`)),o.push(span(""," "),e),t.push(o);const r=(n.models||[]).map((e=>"string"==typeof e?e:e&&e.id)).filter(Boolean);r.length&&t.push([span(C.gray,` models: ${r.join(", ")}`)]),n.key_prefix&&t.push([span(C.gray,` key starts with ${n.key_prefix}`)]),n.key_url&&t.push([span(C.gray,` ${n.key_url}`)])}return t}function keyPanelLines(e,t="AEGIS account key"){const n=e.keyStatus(),o=[[span(C.gold+BOLD,t),span(BOLD_OFF,"")],[span(C.gray,"─".repeat(34))],[span(n.configured?C.green:C.coral," "+(n.configured?"✔":"⚠")),span(C.white," key: "),span(n.configured?C.white:C.gray,n.configured?maskKey(n.key):"not set"),span(C.gray,` (${credentials.sourceLabel(n.source)})`)],[span(C.gray,` stored in: ${n.path}${n.fileMode?` ${n.fileMode}`:""}`)]];return n.verifiedAt&&o.push([span(C.gray,` verified: ${n.verifiedAt}`)]),n.account&&(n.account.plan||n.account.email)&&o.push([span(C.gray," account: "),span(C.white,[n.account.plan,n.account.email].filter(Boolean).join(" · "))]),o.push([span(C.gray," memory: "),span(n.memoryToken?C.green:C.gray,n.memoryToken?"token held (cloud sync ready)":"no token yet")]),n.configured||(o.push([span(C.gray,"")]),o.push([span(C.white," Set one with /key <api_key>, or press Enter on /key to paste it.")]),o.push([span(C.gray,` Free key: ${signupUrl("key_status")}`)])),n.legacyPlaintext&&(o.push([span(C.gray,"")]),o.push([span(C.coral," ⚠ a plaintext copy of the key is still in config.json (another AEGIS CLI wrote it).")]),o.push([span(C.gray," Re-save with /key <api_key> and delete that block when convenient.")])),o}async function applyAccountKey(e,t,{label:n="AEGIS API key"}={}){let o=String(t||"").trim();if(o||(o=await e.readSecret(`${n} (kept off screen, Enter to cancel): `)),!o)return note(e,"no key given — /key <api_key> takes it inline, or press Enter on a bare /key to paste it"),{ok:!1};const r=await e.setApiKey(o);if(!r.ok)return note(e,r.message||"that key could not be saved"),r;if(r.error)return note(e,`saved, but the account check failed: ${r.error.message}`),note(e,"the key is stored — /key status shows it; re-run /key <api_key> if it was mistyped"),r;const s=r.account&&(r.account.email||r.account.plan)||null;done(e,`AEGIS key saved to ${r.path}${s?` — signed in as ${s}`:" and verified"}`);try{const t=pickerEntries(await loadModels(e)).length;t&¬e(e,`${t} pinnable model${1===t?"":"s"} available — /model to pin one`)}catch{}return r}function fmtQuotaTokens(e){const t=Number(e);return Number.isFinite(t)?t>=1e6?`${(t/1e6).toFixed(t%1e6==0?0:1)}M`:t>=1e4?`${Math.round(t/1e3)}k`:fmtTokens(t):"?"}function memoryGate(e){if(e&&"function"==typeof e.cloudSyncState)try{return e.cloudSyncState()}catch{}return{enabled:!e||"function"!=typeof e.cloudSyncEnabled||!0===e.cloudSyncEnabled(),source:"default"}}function setMemoryGate(e,t){if(e&&"function"==typeof e.setCloudSync)return e.setCloudSync(t);try{return setMemoryPersist(t)}catch{return null}}function memoryStatusLines(e){const t=memoryGate(e),n=cloudsync.status(),o=n.quota,r=o&&null!=o.used?fmtQuotaTokens(o.used):null,s=o&&null!=o.limit?fmtQuotaTokens(o.limit):null,a="legacy"===t.source?" (kept from your old cloudSync setting)":"default"===t.source?" (default)":"",i=[[span(C.white+BOLD,"Persisting memory"),span(C.gray," · Cloud sync"),span(BOLD_OFF,"")],[span(C.gray,"─".repeat(34))],[span(C.white," "+(t.enabled?"on":"off")),span(C.gray,`${a} · ${t.enabled?"each session is stored so an interrupted turn can be resumed":"nothing new is stored"}`)]];return s?i.push([span(C.gray," quota: "),span(C.white,`${r} of ${s} tokens synced`),span(C.gray," (aegis1 charges writes; reads are always served)")]):i.push([span(C.gray," quota: not reported yet — /sync now asks the server for the current numbers")]),n.overQuota&&(i.push([span(C.coral," writes: paused — the plan’s ceiling is reached, so new memory is not being stored")]),i.push([span(C.green," reads: still work — everything already stored stays readable (/aegis-recall <topic>)")]),i.push([span(C.gray,` free room at ${goUrl("upgrade","cloud_quota")}`)]),i.push([span(C.gray," or /cloud memory off to stop trying")])),t.enabled&&n.pending>0&&i.push([span(C.gray,` pending: ${n.pending} session(s) waiting to sync`)]),i.push([span(C.gray," /cloud memory on | off · /sync now pushes once by hand")]),i}async function runCloudSync(e,t={}){if(!e.client.apiKey)return note(e,`no key — ${credentials.HOW_TO_SET}`),null;const n=await e.withWorking((()=>cloudsync.syncNow(e.client,t))),o=n.push&&n.push.pushed||[],r=[...n.push&&n.push.failed||[],...n.pull&&n.pull.failed||[]],s=n.pull&&n.pull.imported||0;o.length?done(e,`pushed ${o.length} session${1===o.length?"":"s"} (${o[0].messages} messages in the first)`):n.push&&n.push.skipped&&n.push.skipped.length?note(e,`${n.push.skipped.length} session(s) had nothing to send`):note(e,"nothing to push — every local session is already in the cloud"),s?done(e,`pulled ${s} record${1===s?"":"s"} into the local store — /resume lists them`):n.pull&&n.pull.ok&¬e(e,`cloud has ${n.pull.remote||0} session(s); nothing newer locally`);for(const t of r)note(e,`${"quota"===t.kind?"quota":"failed"}: ${t.message}`),t.hint&¬e(e,t.hint);return n}const hooksLib=require(resolveShared(path.join("client","hooks.js")));function loadCredits(){try{return require(resolveShared(path.join("client","credits.js"))).creditsFromDisk()}catch(e){return{program:{licence:"AGPL-3.0-or-later",name:"GNU Affero General Public License v3.0 or later",url:"https://www.gnu.org/licenses/agpl-3.0.html",source:"https://github.com/aegisinfo/aegiscode-plugin",copyright:"Copyright (C) 2026 Niklas Borneklint",notice:null},documents:[],code:[],fonts:[],missing:["licensing","vendor","fonts"],error:String(e&&e.message||e)}}}function readHooks(){return hooksLib.readHookConfig()}function hookStats(e){return hooksLib.hookStats(e)}function scanSkills(){const e=[path.join(os.homedir(),".aegis","skills"),path.join(process.cwd(),".aegis","skills"),path.join(os.homedir(),".aegiscode","skills"),path.join(process.cwd(),".aegiscode","skills"),path.join(os.homedir(),".claude","skills")],t=[];for(const n of e){const e=n.startsWith(process.cwd())?"project":"user";let o=[];try{o=fs.readdirSync(n,{withFileTypes:!0}).filter((e=>e.isDirectory())).map((e=>e.name))}catch{continue}for(const r of o){const o=path.join(n,r,"SKILL.md");try{const n=fs.readFileSync(o,"utf8"),s=(/^description:\s*(.+)$/m.exec(n)||[])[1]||"";t.push({source:e,name:r,namespace:null,description:s.trim(),path:o,content:n})}catch{}}}return t}const COMMANDS=[{name:"run",hint:"",category:"workspace",desc:"Launch and drive this project's app to see a change working",handler:async e=>{const t=detectDevCommand(process.cwd());if(!t)return note(e,"No dev command detected (no package.json scripts, go.mod, Cargo.toml or Makefile). Try /init first."),e.render(),!0;note(e,`Running ${t} in ${shortCwd()} — output streams below, Esc stops it.`);const n=runDevServer(t,{cwd:process.cwd(),onLine:t=>e.push({role:"note",text:` ${t}`})});return n.label||(n.label=t),e.openStream(n),n.done.then((({code:o,stopped:r})=>{e.closeStream(n),done(e,r?`${t} stopped`:`${t} exited (code ${o})`),e.render()})),e.render(),!0}},{name:"schedule",hint:"",category:"session",desc:"Create, update, list, or run scheduled cloud agents (routines)",handler:async e=>(note(e,"Scheduled routines run on the AEGIS cloud. Sign in with `aegis login`, then manage routines at aegiscloud.org."),e.render(),!0)},{name:"build",aliases:["forge"],args:["task"],hint:"<description>",category:"workspace",desc:"Build an app with the agent loop — /build <what to build>",handler:async(e,t)=>{const n=(t._rest||t.task||"").trim();return n?(note(e,"⬡ AEGIS BUILD"),note(e,`Task: ${n}`),e.render(),await e.runPrompt(`Build the following, creating every file it needs and running the build to verify it works: ${n}`),!0):(note(e,"Usage: /build <what to build>"),note(e,"Example: /build a REST API for a todo app"),e.render(),!0)}},{name:"cd",args:["path"],hint:"<path>",category:"workspace",desc:"Move this session to a new working directory",handler:async(e,t)=>{const n=t.path||(t._rest||"").trim();if(!n)return note(e,"Usage: /cd <path>"),e.render(),!0;try{process.chdir(n),e.ctx.cwd=process.cwd(),updateConfig({lastCwd:process.cwd()}),note(e,`Changed directory to ${process.cwd()}`)}catch(t){note(e,`/cd: ${t.message}`)}return e.render(),!0}},{name:"copy",aliases:["cp"],args:["n"],hint:"[N]",category:"data",desc:"Copy the last response to the clipboard",handler:async(e,t)=>{const n=parseInt(t.n||"1",10)||1,o=lastAssistantText(e.transcript,n);if(!o)return note(e,"Nothing to copy yet."),e.render(),!0;const r=copyToClipboard(o);return r.ok?note(e,r.via.startsWith("tool:")?`Copied the last response to the clipboard (${r.via.split(":")[1]}).`:`No clipboard tool found — response saved to ${r.path}`):note(e,"Clipboard unavailable; nothing copied."),e.render(),!0}},{name:"clear",aliases:["cls"],hint:"",category:"session",desc:"Start a new session with empty context",handler:async e=>(e.transcript.length=0,pruneSessionHistory(e.sessionId),"function"==typeof e.clearConversationMemory&&e.clearConversationMemory(),note(e,"Session cleared — transcript empty."),e.render(),!0)},{name:"undo",args:["which"],hint:"[list|<id>]",category:"session",desc:"Reverse a file edit the agent made this conversation",handler:async(e,t)=>{const n=(t._rest||"").trim();if("list"===n){const t="function"==typeof e.listUndoable?e.listUndoable():[];if(!t.length)return note(e,"Nothing to undo in this conversation."),e.render(),!0;note(e,`${t.length} undoable mutation${1===t.length?"":"s"}, newest first:`);for(const n of t){const t=Math.max(0,Math.round((Date.now()-n.at)/1e3));note(e,` ${n.id.slice(0,8)} ${n.tool} ${path.relative(process.cwd(),n.path)||n.path} (${t}s ago)`)}return note(e,"Undo one with: /undo <id> (first 8 characters are enough), or /undo for the most recent."),e.render(),!0}if("function"!=typeof e.undoMutation)return note(e,"Undo is not available on this engine."),e.render(),!0;let o=n||void 0;if(o){const t=("function"==typeof e.listUndoable?e.listUndoable():[]).find((e=>e.id===o||e.id.startsWith(o)));if(!t)return note(e,`No undo record starts with "${o}". Try /undo list.`),e.render(),!0;o=t.id}const r=e.undoMutation(o);return note(e,r.ok?`Undone — ${path.relative(process.cwd(),r.path)||r.path} ${"deleted"===r.restored?"deleted (it was a new file)":"restored to its prior content"}.`:r.error),e.render(),!0}},{name:"compact",hint:"",category:"session",desc:"Compact the conversation history",handler:async e=>{if(!e.transcript.some((e=>"user"===e.role||"assistant"===e.role)))return note(e,"Nothing to compact yet."),e.render(),!0;note(e,"Compacting conversation history…"),e.render();const t=await e.withWorking((t=>summarizeTranscript(e.transcript,{callModel:(t,n)=>e.ask(t,n).then((e=>e.text)),model:e.ctx.model,signal:t})));return null===t?(note(e,"Compaction cancelled."),e.render(),!0):(e.transcript.length=0,note(e,"Compacted. Earlier context summarized into the message below."),e.transcript.push({role:"user",text:t}),e.render(),!0)}},{name:"cost",hint:"",category:"data",desc:"Show the cost of the current session",handler:async e=>{const t=aggregateSessionUsage(e.sessionId),n=t.entries?accountingFromUsage(t.usage,e.ctx.model,{exchanges:t.entries,real:t.real,costUsd:t.real&&t.costUsd?t.costUsd:void 0}):sessionAccounting(e.transcript,e.ctx.model);return panel(e,panels.buildCost({...e.state(),contextWindow:n.contextWindow,costEur:n.cost},e.ctx)),e.render(),!0}},{name:"context",hint:"",category:"session",desc:"Show context usage for the current session",handler:async e=>{const t=sessionAccounting(e.transcript,e.ctx.model);return panel(e,panels.buildContext({...e.state(),contextWindow:t.contextWindow},e.ctx)),e.render(),!0}},{name:"ping",args:["mode","seconds"],hint:"[off|bell|notify|both] [seconds] | test",category:"model",desc:"Alert me when a long turn finishes, if I am looking elsewhere",handler:async(e,t)=>{const n=loadConfig(),o=(t._rest||"").trim().split(/\s+/).filter(Boolean),r=(o[0]||"").toLowerCase(),s=normalizePingMode(n.ping),a=normalizePingSeconds(n.pingMinSeconds);if(!r)return note(e,`[ping] ${s} — a turn longer than ${a}s raises a terminal notification.`),note(e,` /ping ${PING_MODES.filter((e=>e!==s)).join("|")} ${"off"===s?"turn it back on":"change the channel"}`),note(e," /ping <mode> <seconds> move the threshold (0 pings every turn)"),note(e," /ping test fire one now, to check this terminal supports it"),e.render(),!0;if("test"===r){const t=buildPing({mode:"off"===s?DEFAULT_PING_MODE:s}),n=!!process.stdout.isTTY&&writePing(process.stdout,t);return note(e,n?"[ping] sent one just now. If nothing appeared or sounded, this terminal implements neither OSC 9 nor OSC 777 — /ping bell is the fallback.":"[ping] nothing sent: stdout is not a TTY (a piped or headless run has no one to notify)."),e.render(),!0}if(!PING_MODES.includes(r))return note(e,`Unknown ping mode "${o[0]}". Use ${PING_MODES.join(", ")}.`),e.render(),!0;const i={ping:r};if(null!=o[1]){const t=Number(o[1]);if(!Number.isFinite(t)||t<0)return note(e,`"${o[1]}" is not a number of seconds. Use /ping ${r} 30.`),e.render(),!0;i.pingMinSeconds=normalizePingSeconds(t)}return updateConfig(i),"off"===r?note(e,"[ping] off — no notice will be raised, and nothing is reported as sent."):(note(e,`[ping] ${r} — turns longer than ${normalizePingSeconds(i.pingMinSeconds??n.pingMinSeconds)}s will notify you.`),note(e," Escape never pings (you were watching), and neither does a piped or headless run.")),e.render(),!0}},{name:"todos",aliases:["todo"],args:["sub","text"],hint:"[add <text> | done <n|text> | clear]",category:"session",desc:"A session todo list that survives compaction",handler:async(e,t)=>{const n=(t.sub||"").toLowerCase(),o=(t._rest||"").trim().replace(/^\S+\s*/,"");if(!n)return panel(e,formatTodos()),note(e,` ${todosFile()}`),note(e," /todos add <text> · /todos done <n|text> · /todos clear"),e.render(),!0;if("add"===n){const t=addTodo(o);return t.error?(note(e,t.error),e.render(),!0):(panel(e,formatTodos(t.list)),e.render(),!0)}if("done"===n||"do"===n){const t=completeTodo(o);return t.error?(note(e,t.error),e.render(),!0):(note(e,`[todos] "${t.item.text}" is now ${t.item.done?"done":"open"}.`),panel(e,formatTodos(t.list)),e.render(),!0)}return"clear"===n?(clearTodos(),note(e,"[todos] cleared."),e.render(),!0):(note(e,`Unknown /todos subcommand "${t.sub}". Use add, done or clear.`),e.render(),!0)}},{name:"config",args:["key","value"],hint:"[<key> | <key> <value> | reset <key>]",category:"session",desc:"Show or change any setting, and say which store holds it",handler:async(e,t)=>{const n=(t._rest||"").trim(),o=(t.key||"").trim(),r=n.replace(/^\S+\s*/,"");if(!o)return panel(e,formatConfigRows(configRows())),note(e," /config <key> show one value in full"),note(e," /config <key> <value> set it (true/false/null, numbers, JSON, or text)"),note(e," /config reset <key> back to the shipped value"),note(e,' "shared" keys live in the store AEGIS Desktop writes too; "host" keys are this shell\'s own.'),e.render(),!0;if("reset"===o){const t=resetConfigValue(r);return t.error?(note(e,t.error),e.render(),!0):(note(e,`[config] ${t.key} reset to ${summarizeValue(t.value)} (${t.store}).`),e.render(),!0)}if(!r){const t=loadConfig();return Object.prototype.hasOwnProperty.call(t,o)?(note(e,`${o} (${configStore(o)}):`),e.push({role:"panel",lines:fullValue(t[o]).split("\n").map((e=>` ${e}`))}),e.render(),!0):(note(e,`unknown config key "${o}" — run /config to list the keys`),e.render(),!0)}const s=setConfigValue(o,r);return s.error?(note(e,s.error),e.render(),!0):(note(e,`[config] ${s.key} = ${summarizeValue(s.value)} (${s.store}).`),["model","currentModelId","modelClass","effort","themeIndex","vim"].includes(s.key)&&("effort"===s.key&&(e.ctx.effort=effortRung(s.value),e.ctx.effort!==String(s.value).toLowerCase()&&(e.saveConfig({effort:e.ctx.effort}),note(e,` "${s.value}" is not a level this build sends — recorded as ${e.ctx.effort}.`))),note(e,` This takes effect on the next turn; /${"currentModelId"===s.key?"model":s.key} shows the live session value.`)),e.render(),!0)}},{name:"effort",args:["level"],hint:"[low|medium|high]",category:"model",desc:"Set the token budget the pool sizes each turn from",handler:async(e,t)=>{const n=(t.level||"").toLowerCase();if(n&&"auto"!==n&&!EFFORT_LEVELS.includes(n))return note(e,`Unknown effort level "${t.level}". Use ${EFFORT_LEVELS.join(", ")}.`),e.render(),!0;if(!n)return e.openOverlay({type:"effort",sel:Math.max(0,EFFORT_LEVELS.indexOf(e.ctx.effort||"high"))}),!0;const o="auto"===n?"high":n;return e.ctx.effort=o,e.saveConfig({effort:o}),note(e,"auto"===n?"effort: auto is retired — high is the default, and it is what this session now sends":`Effort level: ${o} — the pool sizes this turn's token budget from it`),e.render(),!0}},{name:"sandbox",args:["sub","value"],hint:"[on|off|read-only|workspace-write | network <open|restricted> | allow <path> | deny <path> | clear]",category:"workspace",desc:"Confine shell commands to a kernel-enforced policy",handler:async(e,t)=>{const n=e.settings&&e.settings(),o=n&&"function"==typeof n.getSandboxPolicy,r=n&&"function"==typeof n.setSandboxPolicy,s=()=>o?n.getSandboxPolicy():null,a=t=>r?n.setSandboxPolicy(t):(e.push({role:"error",text:"this client has no settings store to hold a sandbox policy."}),null),i=process.cwd(),d=(t.sub||"").toLowerCase(),l=t.value;if(!d){const t=s(),n=sandboxLib.detect({appDir:void 0});if(t){note(e,sandboxLib.describe(n,t));const o=t.fileSystem&&t.fileSystem.entries||[],r=t.fileSystem&&t.fileSystem.denies||[];for(const t of o){const n=t&&t.path;n&&"path"===n.type&¬e(e,` ${t.access.padEnd(5)} ${n.path}`)}for(const t of r)note(e,` deny ${t.path}`);note(e," network restricted is skipped for local models — a local turn cannot reach ollama from a fresh netns.")}else note(e,"sandbox: not configured — shell commands run with your full user access."),note(e,`Turn it on with: /sandbox on (or pick a mode: ${sandboxLib.MODES.filter((e=>"off"!==e)).join(", ")})`);return e.render(),!0}if("clear"===d||"off"===d)return a(null),note(e,"off"===d?"sandbox: off — policy cleared; shell commands run unconfined.":"sandbox: policy cleared — shell commands run unconfined."),e.render(),!0;if("on"===d)return a(sandboxLib.defaultPolicy(i)),note(e,`sandbox: workspace-write in ${shortCwd()} — check the shell row says "via bwrap" when a command runs.`),e.render(),!0;const c=s();if(!c)return note(e,"No sandbox policy is set — run /sandbox on first (or /sandbox <mode>)."),e.render(),!0;if(sandboxLib.MODES.includes(d)&&"off"!==d)return a({...c,mode:d}),note(e,`sandbox mode: ${d}`),e.render(),!0;if("network"===d){const t=String(l||"").toLowerCase();return"open"!==t&&"restricted"!==t?(note(e,"usage: /sandbox network <open|restricted>"),e.render(),!0):(a({...c,network:t}),note(e,`sandbox network: ${t}${"restricted"===t?" — note that local models still run with the network open, since a fresh netns cannot reach the ollama daemon":""}`),e.render(),!0)}if("allow"===d||"deny"===d){const t=String(l||"").trim();if(!t)return note(e,`usage: /sandbox ${d} <path>`),e.render(),!0;const n=path.resolve(t);if("deny"===d){let t=null;try{t=fs.statSync(n)}catch{return note(e,`No such path: ${n}`),e.render(),!0}if(!t.isDirectory())return note(e,`A deny must name a directory, not a file: ${n}`),e.render(),!0}const o=Array.isArray(c.fileSystem&&c.fileSystem.entries)?c.fileSystem.entries.slice():[],r=Array.isArray(c.fileSystem&&c.fileSystem.denies)?c.fileSystem.denies.slice():[];return"deny"===d?r.push({path:n}):o.push({path:{type:"path",path:n},access:"write",missingPathBehavior:"skip"}),a({...c,fileSystem:{entries:o,denies:r}}),note(e,"deny"===d?`sandbox: denying ${n} — emptied inside the sandbox, unchanged outside it`:`sandbox: write granted on ${n}`),e.render(),!0}return note(e,`Unknown /sandbox argument "${t.sub}". Try: on, off, ${sandboxLib.MODES.filter((e=>"off"!==e)).join(", ")}, network, allow, deny, clear`),e.render(),!0}},{name:"exit",aliases:["quit"],hint:"",category:"session",desc:"Exit the CLI",handler:async()=>!1},{name:"export",args:["format","target"],hint:"[markdown|json] [file|clipboard]",category:"data",desc:"Export the current conversation to a file or clipboard",handler:async(e,t)=>{const n=(t.format||"markdown").toLowerCase(),o=(t.target||"file").toLowerCase();if(!["markdown","md","json"].includes(n)||!["file","clipboard"].includes(o))return note(e,"Usage: /export [markdown|json] [file|clipboard]"),e.render(),!0;const r="json"===n,s=r?transcriptToJSON(e.transcript):transcriptToMarkdown(e.transcript);if("clipboard"===o){const t=copyToClipboard(s);note(e,t.ok?`Exported conversation (${r?"json":"markdown"}) to the clipboard.`:"Clipboard unavailable; nothing copied.")}else try{const t=writeExportFile(s,r?"json":"md",e.ctx.cwd||process.cwd());note(e,`Exported conversation to ${t}`)}catch(t){note(e,`/export: ${t.message}`)}return e.render(),!0}},{name:"help",aliases:["?","h"],hint:"",category:"support",desc:"Show help",handler:async e=>(panel(e,panels.buildHelp(visibleCommands(),e.ctx)),e.render(),!0)},{name:"init",args:["file"],hint:"[file]",category:"workspace",desc:"Create an AEGIS.md file in the project",handler:async(e,t)=>{const n=(t.file||"AEGIS.md").trim(),o=e.ctx.cwd||process.cwd(),r=path.resolve(o,n),s=o.endsWith(path.sep)?o:o+path.sep;if(r!==o&&!r.startsWith(s))return note(e,`/init: refusing to write outside the project directory (${r}).`),e.render(),!0;if(fs.existsSync(r))return note(e,`${n} already exists — not overwriting.`),e.render(),!0;const a=sniffProject(o);try{fs.writeFileSync(r,buildAegisMd(a)+"\n")}catch(t){return note(e,`/init: ${t.message}`),e.render(),!0}return note(e,`Created ${r} (${a.lang})`),fs.existsSync(path.join(o,"node_modules"))&&!fs.existsSync(path.join(o,".gitignore"))&&tip(e,'Add "node_modules/" to a .gitignore before committing.'),e.render(),!0}},{name:"login",aliases:["signin"],args:["value"],hint:"[<api_key>]",category:"auth",desc:"Save your AEGIS API key",handler:async(e,t)=>{const n=String(t.value||t._rest||"").trim();return await applyAccountKey(e,n,{label:"AEGIS API key"}),e.render(),!0}},{name:"logout",args:[],hint:"",category:"auth",desc:"Remove the saved AEGIS API key",handler:async e=>{const t=e.forgetApiKey();return done(e,t.cleared?`key removed from ${t.path}`:"there was no saved key to remove"),credentials.legacyKeyOnDisk()&¬e(e,`a copy is still in ${configPath()} (another AEGIS CLI wrote it) — delete its "aegiscloud" block too`),e.render(),!0}},{name:"model",aliases:["m"],args:["sub"],hint:"[id|-]",category:"model",desc:'Switch AI model — pin an id ("-" clears it)',handler:async(e,t)=>{const n=(t.sub||"").trim(),o=e.ctx&&e.ctx.modelClass||"aegis",r="byok"===o;if(!n){note(e,`model: ${e.ctx.model||"server default"}`);const t=await mergedPickerModels(e);return t.length?(t.some((e=>"aegis"===e.cls||"byok"===e.cls))||note(e,e.state().online?"Could not read the AEGIS Cloud catalog (offline, or the server refused it) — showing Claude Code Pro only; /models retries.":`No AEGIS API key set, so the AEGIS Cloud catalog cannot be read (free key: ${signupUrl("model_blocked")}) — showing Claude Code Pro only.`),e.ctx.model&&!t.some((t=>t.id===e.ctx.model))&¬e(e,r?`pinned model "${e.ctx.model}" is not one this machine can relay — pick from the list below.`:`pinned model "${e.ctx.model}" is not in the catalog — the pool will answer with its own default; pick one below.`),note(e,"/model <id> pins one for this session; picking a direct-provider row prompts for its key if this machine has none saved."),e.openOverlay({type:"model",items:t,sel:0,current:e.ctx.model,cls:o}),!0):(note(e,e.state().online?"Could not read the model catalog (offline, or the server refused it) — /models retries.":`No API key set, so the model catalog cannot be read — export AEGIS_API_KEY (free key: ${signupUrl("model_blocked")}), then retry /model.`),e.render(),!0)}if("list"===n){const t=await mergedPickerModels(e);return t.length?panel(e,panels.buildModelList(e.ctx.model,t,e.ctx)):note(e,"No pinnable models advertised — /models lists the server's ids."),e.render(),!0}if("-"===n)return e.ctx.model=null,e.saveConfig({model:null,currentModelId:null}),note(e,r?"Model pin cleared. The byok class has no server default — the next turn needs <provider>:<model>, so pin one from /models before sending.":"Model pin cleared — the server will choose."),e.render(),!0;e.ctx.model=n,e.saveConfig({model:n,currentModelId:n}),note(e,`Pinned model: ${n}`);const s=await loadModels(e)||[];return s.length&&!s.some((e=>e.id===n))&¬e(e,r?`"${n}" is not one this machine can relay — a byok id is "<provider>:<model>", and the relay will refuse anything else. /models lists the real ids.`:`"${n}" is not in the AEGIS Cloud catalog — the pool will answer with its own default. /models lists the real ids.`),e.render(),!0}},{name:"radio",hint:"",category:"fun",desc:"Listen to AEGIS FM lo-fi radio",handler:async e=>(note(e,"Opening AEGIS FM lo-fi radio in your browser…"),openUrl(URLS.radio)||note(e,`AEGIS FM: ${URLS.radio}`),e.render(),!0)},{name:"recap",hint:"",category:"session",desc:"Generate a one-line session recap now",handler:async e=>{if(!e.transcript.some((e=>"user"===e.role||"assistant"===e.role)))return note(e,"No exchanges yet — send a prompt first."),e.render(),!0;note(e,"Recapping session…"),e.render();const t=await e.withWorking((t=>recapLine(e.transcript,{callModel:(t,n)=>e.ask(t,n).then((e=>e.text)),model:e.ctx.model,signal:t})));return null===t?(note(e,"Recap cancelled."),e.render(),!0):(e.ctx.lastRecap={sessionId:e.sessionId,ts:(new Date).toISOString(),text:t},e.saveConfig({lastRecap:e.ctx.lastRecap}),note(e,`Session recap: ${t}`),e.render(),!0)}},{name:"resume",args:["query"],hint:"[query]",category:"session",desc:"Switch to a previous session — /resume <text> searches titles, paths and what you typed",handler:async(e,t)=>{const n=readResumeList(200,200,200);if(!n.length)return note(e,"No previous sessions found — conversations from this host and from AEGIS Desktop both land in ~/.aegiscode/sessions.json"),e.render(),!0;backfillSessionNames(e);const o=String(t&&t.query?t.query:"").trim(),r=require(resolveShared(path.join("client","session-search.js"))).rankSessions(o,n);return o&&!r.length?(note(e,`No session matches “${o}” — /resume with no argument lists them all.`),e.render(),!0):(e.openOverlay({type:"resume",items:r,all:n,query:o,sel:0}),!0)}},{name:"rewind",args:["n"],hint:"[N]",category:"session",desc:"Revert the conversation to a checkpoint",handler:async(e,t)=>{const n=listCheckpoints(e.sessionId);if(!t.n)return n.length?(panel(e,panels.buildRewindList(n,e.ctx)),e.render(),!0):(note(e,"No checkpoints yet — snapshots are taken after each exchange."),e.render(),!0);const o=parseInt(t.n,10);if(Number.isNaN(o)||o<0||o>=n.length)return note(e,`Unknown checkpoint ${t.n}. /rewind shows the list (indices 0..${Math.max(0,n.length-1)}).`),e.render(),!0;snapshotCheckpoint(e.sessionId,e.transcript);const r=loadCheckpoint(e.sessionId,o);if(!r)return note(e,"Checkpoint unreadable — nothing restored."),e.render(),!0;e.transcript.length=0;for(const t of r)e.transcript.push(t);return note(e,`Rewound to checkpoint ${o} (${r.length} messages). /rewind N again to undo.`),e.render(),!0}},{name:"agents",aliases:["sessions"],args:["role","task"],hint:"[role] [task]",category:"session",desc:"Show the agents panel, or run a sub-agent role preset — /agents <role> <task>",handler:async(e,t)=>{const n=(t.role||"").trim().toLowerCase();if(n){const o=(t._rest||"").trim().replace(/^\S+\s*/,"").trim();if(!o)return note(e,`Usage: /agents <role> <task> — roles: ${agentRoles().join(", ")}`),e.render(),!0;if(!AGENT_PRESETS[n])return note(e,`Unknown agent role "${n}". Roles: ${agentRoles().join(", ")}`),e.render(),!0;const r=composeAgentPrompt(n,o);return e.runPrompt?(await e.runPrompt(r),!0):(note(e,`Composed ${n} prompt (${r.length} chars) — run in the TUI to send it.`),e.render(),!0)}return panel(e,panels.buildAgents(e.state(),e.ctx)),e.render(),!0}},{name:"status",aliases:["st"],hint:"",category:"session",desc:"Show account and session status",handler:async e=>(await e.runTool("aegis_status",{}),panel(e,panels.buildStatus(e.state(),Object.assign({},e.ctx,{caps:describe()}))),e.render(),!0)},{name:"teleport",hint:"",category:"session",desc:"Resume a session from aegiscloud.org",handler:async e=>(note(e,"Teleport requires an AEGIS cloud account with sessions. Sign in with `aegis login`, then run aegiscloud.org/teleport."),e.render(),!0)},{name:"theme",aliases:["t"],args:["mode"],hint:"[dark|light]",category:"model",desc:"Change the color theme",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if("dark"===n||"light"===n){const t="light"===n?2:1;screens.applyTheme(e.ctx,t)}else await e.showThemePicker();if(e.saveConfig({themeIndex:e.ctx.themeIndex}),note(e,"Theme: "+(e.ctx.light?"light":"dark")),themeContradicts(e.ctx.themeIndex)){const t=caps().background;note(e,`warning: this ${t} terminal is not what "${THEME_TABLE[e.ctx.themeIndex].name}" is drawn for — body text may be unreadable.`),note(e,` /terminal background ${t} pins the palette to this terminal, or /terminal background ${"dark"===t?"light":"dark"} if it reads you wrong.`)}return e.render(),!0}},{name:"terminal",aliases:["tty"],args:["mode","mode2"],hint:"[ascii|unicode|color|no-color|background <dark|light>|probe|star <native|narrow>|width <cols>|auto|status]",category:"model",desc:"Show or override how this terminal is drawn (mark, colour, width)",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase(),o=null!=t.mode2?String(t.mode2).trim():"";if(""===n||"status"===n)return panel(e,panels.buildTerminalCaps(describe(),{pinned:!!caps().pinned})),e.render(),!0;const r=caps(),s={glyphs:r.glyphs,face:r.face,star:r.star,depth:r.depth,vt:r.vt,wideRunes:r.wideRunes,background:r.background,backgroundKnown:r.backgroundKnown,reasons:Object.assign({},r.reasons)};if("auto"===n)return resetCaps(),note(e,"Terminal: auto — capabilities re-probed from the environment."),e.render(),!0;if("probe"===n){const t=await probeTerminalBackground();return screens.applyTheme(e.ctx,e.ctx.themeIndex),note(e,t.known?`Terminal: background ${t.background} (${t.reason}) — /theme auto follows it.`:`Terminal: no answer to the background query (${t.reason}).`),note(e," /terminal background dark|light pins it without asking."),panel(e,panels.buildTerminalCaps(describe(),{pinned:!!caps().pinned})),e.render(),!0}if("ascii"===n||"unicode"===n)s.glyphs="ascii"===n?"ascii":"unicode",s.face="ascii"===n?"edges":"native",s.star="ascii"===n?"narrow":"native",s.reasons&&(s.reasons.glyphs=`/terminal ${n}`);else if("color"===n||"no-color"===n||"nocolor"===n)s.depth="color"===n?24:0,s.reasons&&(s.reasons.depth=`/terminal ${n}`);else{if("star"!==n){if("background"===n||"bg"===n){const t=o.toLowerCase();return["dark","light"].includes(t)?(s.background=t,s.backgroundKnown=!0,s.reasons&&(s.reasons.background=`/terminal background ${t}`),setCaps(Object.assign({},s)),screens.applyTheme(e.ctx,e.ctx.themeIndex),note(e,`Terminal: background pinned to ${t} — /theme auto follows it.`),panel(e,panels.buildTerminalCaps(describe(),{pinned:!!caps().pinned})),e.render(),!0):(note(e,"Usage: /terminal background <dark|light>"),e.render(),!0)}if("width"===n){const t=Number(o);return!Number.isFinite(t)||t<20?(note(e,"Usage: /terminal width <cols> (>= 20)"),e.render(),!0):(setCaps(Object.assign({},s,{cols:Math.round(t)})),note(e,`Terminal: width pinned to ${Math.round(t)} columns.`),panel(e,panels.buildTerminalCaps(describe(),{pinned:!!caps().pinned})),e.render(),!0)}return note(e,"Usage: /terminal [ascii|unicode|color|no-color|background <dark|light>|probe|star <native|narrow>|width <cols>|auto|status]"),e.render(),!0}{const t=o.toLowerCase();if(!["native","narrow"].includes(t))return note(e,"Usage: /terminal star <native|narrow>"),e.render(),!0;s.star=t,s.reasons&&(s.reasons.star=`/terminal star ${t}`)}}return setCaps(s),panel(e,panels.buildTerminalCaps(describe(),{pinned:!!caps().pinned})),note(e,"Terminal updated — the current viewport is redrawn; text already scrolled past keeps its old glyphs."),e.render(),!0}},{name:"version",aliases:["v"],hint:"",category:"session",desc:"Show version",handler:async e=>(note(e,`aegiscode v${VERSION}`),e.render(),!0)},{
|
|
4
4
|
// The licence surface this face did not have. `AGPL-3.0-or-later` was in the
|
|
5
|
-
name:"license",aliases:["licence"],hint:"",category:"support",desc:"Show this program's licence (AGPL-3.0-or-later) and where to read it",handler:async e=>{const t=loadCredits(),n=t.program||{},o=[];if(o.push("Licence"),o.push(" "+(n.name||"GNU Affero General Public License v3.0 or later")),o.push(" "+(n.licence||"AGPL-3.0-or-later")),o.push(""),n.copyright&&o.push(" "+n.copyright),n.url&&o.push(" Full text: "+n.url),n.source&&o.push(" Source: "+n.source),o.push(""),o.push(" /credits lists the vendored third-party code and fonts."),n.notice){o.push("");for(const e of String(n.notice).split("\n"))o.push(e?" "+e:"")}Array.isArray(t.missing)&&t.missing.length&&(o.push(""),o.push(" Could not read: "+t.missing.join(", ")));for(const t of o)note(e,t);return e.render(),!0}},{name:"credits",hint:"",category:"support",desc:"Show third-party attributions and the licence the bundled fonts carry",handler:async e=>{const t=loadCredits(),n=[],o=Array.isArray(t.code)?t.code:[],r=Array.isArray(t.fonts)?t.fonts:[];if(n.push("Credits"),n.push(" "+(t.program&&t.program.copyright||"")),o.length){n.push(""),n.push(" Vendored third-party code");for(const e of o)n.push(" "+e.name+(e.version?" v"+e.version:"")+(e.licence?" "+e.licence:"")),e.url&&n.push(" "+e.url)}if(r.length){n.push(""),n.push(" Vendored webfonts");for(const e of r)n.push(" "+e.name+" "+(e.copyright||"")+(e.licence?" "+e.licence:"")),e.url&&n.push(" "+e.url)}o.length||r.length||(n.push(""),n.push(" No attribution files could be read from this installation.")),n.push(""),n.push(" /license shows the licence this program itself is under.");for(const t of n)note(e,t);return e.render(),!0}},{name:"doctor",args:["action"],hint:"[fix|system]",category:"support",desc:"Run diagnostic checks on this environment",handler:async(e,t)=>{const n=(t&&t.action||"").toLowerCase();if(n&&"fix"!==n&&"system"!==n)return note(e,'Usage: /doctor [fix|system] — "fix" re-tightens the data dir to 0700/0600, "system" checks the machine itself'),e.render(),!0;const o=[],r=(e,t,n)=>o.push([t,e,n]);r("Node",!0,process.version),r("CWD",fs.existsSync(process.cwd()),process.cwd());let s=!1;try{execSync("git rev-parse --git-dir",{cwd:process.cwd(),stdio:["ignore","ignore","ignore"],timeout:4e3}),s=!0}catch{}r("git repo",s,s?"inside a work tree":"not a git repository");const a=credentials.keyStatus();r("AEGIS key",a.configured,a.configured?`${maskKey(a.key)} via ${credentials.sourceLabel(a.source)}`:`not set — ${credentials.HOW_TO_SET} (free key: ${signupUrl("doctor")})`),r("credentials",!0,`${a.path}${a.fileMode?` (${a.fileMode})`:""}`),r("cloud memory",a.memoryToken,a.memoryToken?"token held":"no memory token — /cloud activate"),a.legacyPlaintext&&r("plaintext key",!1,`a copy also sits in ${configPath()} (another AEGIS CLI) — /key re-saves it to ${a.path}`),r("config path",!0,configPath());const i=aegisDir();let d=null;"fix"===n&&(d=repairExposure(i));const l=auditExposure(i);if(l.exists)if(l.modesMeaningful){const e=l.exposed.slice(0,4).map((e=>`${e.rel} ${e.mode}`)).join(", ");r("data dir",0===l.exposed.length,0===l.exposed.length?`${i} (${l.rootMode}, all private)`:`${i} (${l.rootMode}) — ${l.exposed.length} path(s) group/world-accessible: ${e}${l.exposed.length>4?", …":""} — run /doctor fix`)}else r("data dir",!0,`${i} (${l.total} path(s)) — this filesystem has no POSIX permission bits; access is governed by the profile directory's own ACL`);else r("data dir",!0,`${i} (not created yet)`);if(d&&!d.modesMeaningful)r("repair",!0,"nothing to tighten — this filesystem has no POSIX permission bits");else if(d){const e=d.fixed.slice(0,3).map((e=>`${e.rel} ${e.from}→${e.to}`)).join(", ");r("repair",0===d.remaining.length,0===d.remaining.length?d.fixed.length?`tightened ${d.fixed.length} path(s) — ${e}${d.fixed.length>3?", …":""}`:"already private, nothing to tighten":`${d.remaining.length} path(s) still exposed — `+d.failed.map((e=>`${e.rel}: ${e.reason}`)).join(", "))}let c=null;if("system"===n){const e=sysdiag.collect();if(e.ok){c=sysdiag.assess(e.data);for(const e of c.findings)r(`${e.title} (${e.severity})`,!1,`${e.detail} → ${e.remedyText}`);for(const e of c.clean)r(e.title,!0,e.detail);for(const e of c.unassessed)r(`${e.title} (unassessed)`,!1,e.reason)}else r("machine checks",!1,"not-windows"===e.reason?"not available on this platform — the machine audit is Windows-only (cli/src/sysdiag.js)":`could not run: ${e.reason}`)}const u=[[span(C.gold+BOLD,"Doctor"),span(BOLD_OFF,"")],[span(C.gray,"─".repeat(30))]];for(const[e,t,n]of o)u.push([span(e?C.green:C.coral," "+(e?"✔":"⚠")),span(C.white,` ${t}: `),span(C.gray,String(n))]);if(c&&c.findings.length){const e=c.summary;u.push([span(C.gold," Remedy"),span(C.gray,` — ${e.findings} finding(s) across ${e.assessed}/${e.total} measured checks.`)]),u.push([span(C.gray," Run in an ELEVATED PowerShell. AEGIS diagnoses this; it does not change your machine.")]);for(const e of sysdiag.remedyScript().split("\n"))u.push([span(C.gray,` ${e}`)])}return panel(e,u),e.render(),!0}},{name:"upgrade",args:["action"],hint:"[check|apply]",category:"support",desc:"Check for a newer published version (apply: install it now)",handler:async(e,t)=>{const n=String(t&&t.action||"check").toLowerCase();if(!["check","apply"].includes(n))return note(e,"Usage: /upgrade [check|apply]"),e.render(),!0;const o=installMethod();note(e,"Checking the npm registry…"),e.render();const r=e&&e.withWorking?t=>e.withWorking(t):e=>e(),s=e.ctx&&e.ctx.demo?null:await r((()=>Promise.resolve(latestPublishedVersion()))),a=upgradeAdvice({latest:s,method:o});if(panel(e,a.lines.map((e=>[span(C.white,e)]))),e.render(),"apply"!==n)return!0;if(!a.plan||!a.plan.apply)return note(e,a.plan?`Nothing to install: ${a.plan.instruction}`:"Nothing to install."),e.render(),!0;note(e,`Running: ${a.plan.instruction}`),e.render();const i=applyUpgrade({method:o,latest:s,current:a.plan.current});if(i.ok&&!i.skipped){if(note(e,`Installed ${a.plan.latest}. Restart aegiscode to use it.`),i.output)for(const t of i.output.split("\n").slice(-6))note(e,` ${t}`)}else i.skipped?note(e,`Not applied: ${i.instruction}`):(note(e,`Upgrade failed: ${i.error}`),note(e,`Run it yourself: ${i.command}`));return e.render(),!0}},{name:"vim",args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle vim keymap",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if(n&&!["on","off"].includes(n))return note(e,"Usage: /vim [on|off]"),e.render(),!0;const o="on"===n||"off"!==n&&!e.ctx.vim;return e.ctx.vim=o,e.saveConfig({vim:o}),note(e,"Vim keymap: "+(o?"on":"off")),e.render(),!0}},{name:"permissions",args:["mode","pattern"],hint:'[allow|deny|ask "<pattern>" | default <ask|allow|deny> | mode <m> | clear]',category:"model",desc:"Set permissions for tool use",handler:async(e,t)=>{const n=loadPermissions(),o=(t.mode||"").toLowerCase(),r=t.pattern;if(!o){const t=permissionMode();return panel(e,panels.buildPermissions({...n,_path:permissionsPath(),_permissionMode:t},null,e.ctx)),e.render(),!0}if("mode"===o){const t=(r||"").toLowerCase();if(!t){const t=permissionMode();return note(e,`Child permission mode: ${t||"unset (no --permission-mode is passed)"}`),note(e,`Set with: /permissions mode <${PERMISSION_MODES_LOCAL.join("|")}|off>`),e.render(),!0}if("off"===t||"none"===t)return setPermissionMode(null),note(e,"Child permission mode cleared — the child is spawned with no --permission-mode."),e.render(),!0;try{const n=setPermissionMode(t);note(e,`Child permission mode: ${n}`),confirmPosture().enabled||note(e,"Note: confirmations are OFF, so --dangerously-skip-permissions wins and the mode is recorded but not passed. Run /confirm to let the mode take effect.")}catch(t){note(e,t&&t.message||String(t))}return e.render(),!0}if("clear"===o)return setPermissionDefaultMode(DEFAULT_PERMISSIONS.defaultMode),savePermissions({...DEFAULT_PERMISSIONS,allow:[],deny:[],ask:[]}),note(e,"Permissions reset to defaults (no rules)."),e.render(),!0;if("default"===o&&["ask","allow","deny"].includes(r))return setPermissionDefaultMode(r),note(e,`Default permission mode: ${r}`),e.render(),!0;if(["allow","deny","ask"].includes(o)&&r){const{added:t,rules:s}=addPermissionRule(o,r,n);return savePermissions(s),note(e,t?`Added ${o} rule: ${r}`:`Rule already present: ${r}`),e.render(),!0}return note(e,'Usage: /permissions [allow|deny|ask "<pattern>" | default <ask|allow|deny> | mode <m> | clear]'),e.render(),!0}},{name:"hooks",args:["sub"],hint:"[status|list|install]",category:"model",desc:"View hooks configuration status, list configured hooks, or install this repo's guard hooks",handler:async(e,t)=>{const n=(t.sub||"").toLowerCase();if("install"===n){const n=/--dry-run|\bdry-?run\b/.test(String(t._rest||"")),o=hooksLib.installRepoHooks({cwd:process.cwd(),dryRun:n});if(o.ok)if(n){note(e,`would install the guard hooks in ${o.status.repo}`);for(const t of o.actions)note(e,` ${t}`);o.status.installed&¬e(e,"core.hooksPath is already .githooks — nothing to change")}else if(o.changed){done(e,"installed the guard hooks — core.hooksPath = .githooks (verified)");for(const t of o.actions)note(e,` ${t}`)}else done(e,"guard hooks already installed (core.hooksPath = .githooks)");else if(note(e,o.error),o.actions.length)for(const t of o.actions)note(e,` ${t}`);return o.ok&¬e(e,o.status.execNote),e.render(),!0}const{hooks:o,from:r}=readHooks();return"list"===n?(panel(e,panels.buildHooksList({hooks:o},e.ctx)),e.render(),!0):""===n||"status"===n?(panel(e,panels.buildHooksStatus({...hookStats(o),fromPaths:r},e.ctx)),e.render(),!0):(note(e,`unknown subcommand: ${t.sub}`),note(e,"available: status, list, install [--dry-run]"),e.render(),!0)}},{name:"credentials",hint:"",category:"model",desc:"Show where credentials are stored",handler:async e=>{const t=path.join(os.homedir(),".claude",".credentials.json"),n=t.replace(os.homedir(),"~");return fs.existsSync(t)?note(e,`Credentials live in ${n} (managed by the Claude Code CLI). aegiscode reads them but never writes them.`):note(e,"No credential file found. The Claude Code CLI manages auth (OS keychain or ~/.claude/.credentials.json)."),e.render(),!0}},{name:"install-github-app",hint:"",category:"model",desc:"Install the GitHub App for PR workflows",handler:async e=>(note(e,"The GitHub App is installed through the Claude Code CLI: run `claude --install-github-app` once."),e.render(),!0)},{name:"troubleshooting",hint:"",category:"support",desc:"Troubleshoot common issues",handler:async e=>(panel(e,panels.buildTroubleshooting(e.state(),e.ctx)),e.render(),!0)},{name:"feedback",hint:"",category:"support",desc:"Send feedback to the AEGIS team",handler:async e=>(note(e,"Opening the feedback form…"),openUrl(URLS.feedback)||note(e,`Feedback: ${URLS.feedback}`),e.render(),!0)},{name:"bug",hint:"",category:"support",desc:"Report a bug (opens a GitHub issue)",handler:async e=>(note(e,`Opening a GitHub issue… (aegiscode v${VERSION}, ${process.version}, ${os.platform()})`),openUrl(URLS.issues)||note(e,`Issues: ${URLS.issues}`),e.render(),!0)},{name:"issue",aliases:["bugs"],hint:"",category:"support",desc:"Report an issue",handler:async e=>(note(e,"Opening a GitHub issue…"),openUrl(URLS.issues)||note(e,`Issues: ${URLS.issues}`),e.render(),!0)},{name:"onboarding",hint:"",category:"support",desc:"Show getting-started tips",handler:async e=>(panel(e,panels.buildOnboarding(e.state(),e.ctx)),e.render(),!0)},{name:"shell-completion",hint:"",category:"support",desc:"Set up shell completion",handler:async e=>(panel(e,panels.buildShellCompletion(e.state(),e.ctx)),e.render(),!0)},{name:"terminal-setup",hint:"",category:"support",desc:"Check and fix terminal setup",handler:async e=>(panel(e,panels.buildTerminalSetup(e.state(),e.ctx)),e.render(),!0)},{name:"pr-comments",hint:"",category:"support",desc:"Review and reply to pull request comments",handler:async e=>(note(e,"PR comments need GitHub auth. Run /prs to check connectivity, then use the `gh` CLI or the GitHub web UI."),e.render(),!0)},{name:"prs",hint:"",category:"support",desc:"List pull requests in this repo",handler:async e=>{try{const t=execSync("gh pr list --limit 8",{encoding:"utf8",timeout:15e3,stdio:["ignore","pipe","ignore"]});panel(e,panels.buildPRs(t.toString(),e.ctx))}catch{note(e,"gh not authenticated (or not installed) — run `gh auth login` first.")}return e.render(),!0}},{name:"review",hint:"",category:"support",desc:"Review a pull request",handler:async e=>(note(e,"/review needs GitHub auth via gh. Run /prs to list open PRs, then open one in the browser."),e.render(),!0)},{name:"benchmark",hint:"",category:"support",desc:"Run in-app micro-benchmarks",handler:async e=>{const t=e=>{const t=process.hrtime.bigint();return e(),(Number(process.hrtime.bigint()-t)/1e6).toFixed(2)},n=[["2,000 span() calls",t((()=>{for(let e=0;e<2e3;e++)span(C.white,"x")}))],["estimateTokens × 20 (500 chars)",t((()=>{for(let e=0;e<20;e++)estimateTokens("x".repeat(500))}))]];return markdownModule&&"function"==typeof markdownModule.renderMarkdown&&n.push(["renderMarkdown × 200",t((()=>{for(let e=0;e<200;e++)markdownModule.renderMarkdown("# Heading\n\nSome **bold** and `code` with a [link](https://x.test).\n\n- a\n- b\n- c\n",80)}))]),panel(e,panels.buildBenchmark(n,e.ctx)),e.render(),!0}},{name:"waifu",hint:"",category:"fun",desc:"Summon a waifu",handler:async e=>(panel(e,panels.buildWaifu(e.ctx)),e.render(),!0)},{name:"new",aliases:["start"],hint:"",category:"session",desc:"Start a new session (clears the transcript, fresh session id)",handler:async e=>{e.transcript.length=0,"function"==typeof e.clearConversationMemory&&e.clearConversationMemory();const t="aegis-"+Math.random().toString(36).slice(2,10);return e.sessionId=t,e.ctx.sessionId=t,note(e,`New session started (${t}) — earlier context cleared.`),e.render(),!0}},{name:"tokens",aliases:["tok"],hint:"",category:"data",desc:"Show token usage breakdown and estimated spend",handler:async e=>{const t=sessionAccounting(e.transcript,e.ctx.model);return panel(e,panels.buildTokens({...e.state(),contextWindow:t.contextWindow,costEur:t.cost},e.ctx)),e.render(),!0}},{name:"skills",aliases:["sk"],args:["sub"],hint:"[name|refresh]",category:"session",desc:"List skills (SKILL.md in the standard skill dirs)",handler:async(e,t)=>{const n=(t.sub||"").trim().toLowerCase(),o=scanSkills(),r=[path.join(os.homedir(),".aegis","skills"),path.join(process.cwd(),".aegis","skills"),path.join(os.homedir(),".aegiscode","skills"),path.join(process.cwd(),".aegiscode","skills"),path.join(os.homedir(),".claude","skills")].map((e=>e.replace(os.homedir(),"~")));if("refresh"===n||"reload"===n)return note(e,`Skills refreshed — ${o.length} found (${r.length} dirs scanned).`),e.render(),!0;if(n){const t=o.find((e=>e.name===n));return t?(panel(e,panels.buildSkillDetail(t,e.ctx)),e.render(),!0):(note(e,`Unknown skill "${n}". /skills lists what exists on disk.`),e.render(),!0)}return panel(e,panels.buildSkills(o,r,e.ctx)),e.render(),!0}},{name:"thinking",args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle thinking blocks expanded/collapsed",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if(n&&!["on","off"].includes(n))return note(e,"Usage: /thinking [on|off]"),e.render(),!0;const o="on"===n||"off"!==n&&!(!0===e.ctx.thinking);return e.ctx.thinking=o,e.saveConfig({thinking:o}),note(e,"Thinking blocks: "+(o?"expanded":"collapsed")),e.render(),!0}},{name:"mcp",args:["sub","name","command"],hint:"[add <name> <command> [args…]|remove <name>|<name>]",category:"model",desc:"Show MCP server configuration",handler:async(e,t)=>{const n=loadConfig().mcpServers||{},o=(t.sub||"").toLowerCase();if("add"===o){const o=(t.name||"").trim(),r=(t.command||"").trim();if(!o||!r)return note(e,'Usage: /mcp add <name> "<command with args>"'),e.render(),!0;const s=r.split(/\s+/).filter(Boolean);return updateConfig({mcpServers:{...n,[o]:{command:s[0],args:s.slice(1)}}}),note(e,`Added MCP server "${o}" (${s[0]}). Configuration only — this build has no MCP runtime.`),e.render(),!0}if("remove"===o||"rm"===o){const o=(t.name||"").trim();if(!o)return note(e,"Usage: /mcp remove <name>"),e.render(),!0;if(!n[o])return note(e,`No MCP server "${o}". /mcp lists the configured ones.`),e.render(),!0;const r={...n};return delete r[o],updateConfig({mcpServers:r}),note(e,`Removed MCP server "${o}".`),e.render(),!0}if(o&&n[o]){const t=n[o];return panel(e,[[span(C.gold,`MCP server: ${o}`)],[span(C.gray,"─".repeat(30))],[span(C.white,` command: ${`${t.command||""} ${(t.args||[]).join(" ")}`.trim()}`)],[span("","")],[span(C.gray,"Configuration only — this build has no MCP runtime.")]]),e.render(),!0}return panel(e,panels.buildMcp(n,[configPath(),permissionsPath()],e.ctx)),e.render(),!0}},{name:"memory",aliases:["memories"],hint:"",category:"model",desc:"List the most recent AEGIS cloud-memory entries",tool:"aegis_memory_list",build:()=>({})},{name:"memory-deep",aliases:["recall-deep"],args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle DEEP recall for this session — brain corrections + cached answers (metered: one embedding per turn)",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if(n&&!["on","off"].includes(n))return note(e,"Usage: /memory-deep [on|off]"),e.render(),!0;const o="on"===n||"off"!==n&&!(!0===e.ctx.recallDeep);return e.ctx.recallDeep=o,note(e,`Deep recall: ${o?"on — brain corrections + cached answers, one embedding per turn":"off (only the cheap recall read)"}${o?" · this session only":""}`),e.render(),!0}},{name:"confirm",aliases:["confirmations"],args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle tool-call confirmation prompts",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if(n&&!["on","off"].includes(n))return note(e,"Usage: /confirm [on|off]"),e.render(),!0;const o="on"===n||"off"!==n&&!confirmPosture().enabled;return setConfirmPosture(o),note(e,`Confirmation prompts: ${o?"on":"off"} (default permission mode: ${o?"ask":"allow"})`),e.render(),!0}},{name:"automode",aliases:["yolo"],args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle automode — auto-approve all tool executions",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if(n&&!["on","off"].includes(n))return note(e,"Usage: /automode [on|off]"),e.render(),!0;const o="on"===n||"off"!==n&&confirmPosture().enabled;return setConfirmPosture(!o),"function"==typeof e.setAutoRounds&&e.setAutoRounds(o),o?panel(e,panels.buildAutomode(e.state(),e.ctx)):note(e,"automode off — confirmations restored."),e.render(),!0}},{name:"multiyolo",aliases:["multiauto"],args:["task"],hint:"<task>",category:"session",desc:"Multi-agent orchestration with automode — /multiyolo <task>",handler:async(e,t)=>{const n=(t._rest||t.task||"").trim();return n?runMultiCommand(e,n,{yolo:!0}):(note(e,"Usage: /multiyolo <task>"),e.render(),!0)}},{name:"router",args:["sub","tier","modelId"],hint:"[on|off|set <tier> <modelId>|stats]",category:"model",desc:"Show or manage the model router config",handler:async(e,t)=>{const n=loadConfig(),o=n.autoRouter||{enabled:!1,tiers:{}},r=(t.sub||"").toLowerCase(),s=e=>updateConfig({autoRouter:e});if("on"===r)return s({...o,enabled:!0}),note(e,"Auto-router: on."),e.render(),!0;if("off"===r)return s({...o,enabled:!1}),note(e,"Auto-router: off."),e.render(),!0;if("set"===r){const n=(t.tier||"").toLowerCase(),r=(t.modelId||"").trim();return["simple","medium","complex"].includes(n)&&r?(s({...o,tiers:{...o.tiers||{},[n]:r}}),note(e,`Auto-router: ${n} -> ${r}`),e.render(),!0):(note(e,"Usage: /router set <simple|medium|complex> <modelId>"),e.render(),!0)}return"stats"===r?(panel(e,[[span(C.gold+BOLD,"Router stats"),span(BOLD_OFF,"")],[span(C.gray,"─".repeat(30))],[span(C.gray,"No learned outcomes yet — this build does not auto-route.")],[span(C.gray,"Tiers: simple/medium/complex via /router set.")]]),e.render(),!0):(panel(e,panels.buildRouter(n,e.ctx)),e.render(),!0)}},{name:"multi",args:["task","mode"],hint:"<task> [run]",category:"session",desc:'Compose a multi-agent task (add "run" to execute)',handler:async(e,t)=>{let n=(t._rest||t.task||"").trim(),o=(t.mode||"").toLowerCase();return"run"!==o&&/\s+run$/i.test(n)&&(o="run",n=n.replace(/\s+run$/i,"").trim()),n?"run"!==o?(panel(e,panels.buildAegisMulti(n,e.ctx)),e.render(),!0):runMultiCommand(e,n):(note(e,"Usage: /multi <task> [run]"),e.render(),!0)}},{name:"research",args:["question"],hint:"<question>",category:"session",desc:"Research a topic with a multi-perspective council prompt",handler:async(e,t)=>{const n=(t._rest||t.question||"").trim();if(!n)return note(e,"Usage: /research <question>"),e.render(),!0;const o=composeResearchPrompt(n,process.cwd());return e.runPrompt?(await e.runPrompt(o),!0):(note(e,`Composed research prompt (${o.length} chars) — run in the TUI to send it.`),e.render(),!0)}},{name:"debate",aliases:["db"],args:["topic"],hint:"<topic>",category:"session",desc:"Run a structured debate on the current model",handler:async(e,t)=>{const n=(t._rest||t.topic||"").trim();if(!n)return note(e,"Usage: /debate <topic>"),e.render(),!0;const o=composeDebatePrompt(n,e.ctx.model||"");return e.runPrompt?(await e.runPrompt(o),!0):(note(e,`Composed debate prompt (${o.length} chars) — run in the TUI to send it.`),e.render(),!0)}},{name:"billing",aliases:["balance","spend"],hint:"",category:"support",desc:"Show billing info — token-bank balance and recent spend",handler:async e=>{await e.runTool("aegis_balance",{});const t=await e.refreshSpend(),n=e.state();return panel(e,panels.buildBilling({...n,balance:t&&null!=t.balance?t.balance:n.balance,payment:await billingPayment(e)},e.ctx)),e.render(),!0}},{name:"topup",aliases:["fund"],args:["amount"],hint:"[EUR]",category:"support",desc:"Top up the token bank — opens the payment page and confirms the credit here",handler:async(e,t)=>{const n=String(t.amount||t._rest||"").trim();let o;try{o=require(require("./sharedpaths.js").resolveShared("client/topup.js"))}catch(t){return note(e,`top-up is unavailable in this build — ${t.message}`),e.render(),!0}const r=o.parseTopupAmount(n);if(!r.ok)return note(e,r.message),e.render(),!0;if(!e.client.apiKey)return note(e,`no AEGIS key on this machine — ${credentials.HOW_TO_SET}, then /topup ${r.amount}`),e.render(),!0;const s=e.withWorking?await e.withWorking((()=>o.startTopup(e.client,r.amount))):await o.startTopup(e.client,r.amount);if(!s.ok)return note(e,`the top-up could not be started — ${s.message}`),s.hint&¬e(e,s.hint),e.render(),!0;note(e,`opening the payment page — ${r.amount} EUR`),note(e,s.url);const a=Math.round(o.TOPUP_POLL_MS*o.TOPUP_POLL_TRIES/1e3);note(e,`watching this account's bank for up to ${a}s; the credit is confirmed here, not in the browser`),e.render(),openUrl(s.url)||note(e,"could not open a browser — use the URL above");const i=o.createCreditWatch(e.client);let d=null,l=!1;const c=()=>{l=!0,d&&clearTimeout(d)},u=async()=>{if(l)return;const t=await i.tick();return"credited"===t.state?(c(),note(e,`credit confirmed — the bank is now ${t.amount.toFixed(2)} EUR`),void e.render()):"expired"===t.state?(c(),note(e,"no credit observed within the watch window — if you completed the payment it may still land; /billing shows the bank"),void e.render()):(d=setTimeout(u,o.TOPUP_POLL_MS),void(d&&"function"==typeof d.unref&&d.unref()))};return d=setTimeout(u,o.TOPUP_POLL_MS),d&&"function"==typeof d.unref&&d.unref(),!0}},{name:"cloud",args:["sub","value"],hint:"[status|key <api_key>|activate|deactivate|memory [on|off]|sync [on|off|now]]",category:"support",desc:"Show and control ÆGIS cloud sync",handler:async(e,t)=>{const n=(t.sub||"").toLowerCase(),o=(t.value||t._rest||"").trim();if("key"===n)return await applyAccountKey(e,o),e.render(),!0;if("activate"===n){if(!e.client.apiKey)return note(e,`no key — ${credentials.HOW_TO_SET}`),e.render(),!0;try{const t=await e.withWorking((()=>e.client.memoryActivate())),n=await e.client.getMemoryToken();n&&credentials.saveMemoryToken(n,{memorySubscribed:!0}),done(e,t&&!1===t.ok?"the server refused activation":"cloud memory activated for this account"),t&&t.token_limit&¬e(e,`quota: ${t.tokens_used||0} / ${t.token_limit} synced tokens`)}catch(t){note(e,`activation failed: ${t.message}`)}return e.render(),!0}if("deactivate"===n)return credentials.clearMemoryToken(),e.client.setApiKey(e.client.apiKey),note(e,"cloud memory token cleared locally — sync stops until /cloud activate re-issues one"),note(e,"the account itself is still subscribed; manage the subscription here:"),note(e,goUrl("upgrade","cloud_deactivate")),e.render(),!0;if("memory"===n||"persist"===n||"memory-persist"===n){const t=(o||"status").toLowerCase();if("on"===t||"off"===t){const n="on"===t;return setMemoryGate(e,n),n?(done(e,"persisting memory on — sessions are stored to your account so an interrupted turn can be resumed"),note(e,"/cloud memory shows the quota; past the plan’s ceiling reads keep working and only new writes pause")):(note(e,"persisting memory off — nothing new is stored"),note(e,"everything already in the cloud stays readable (/aegis-recall <topic>), and /sync now still pushes once by hand")),e.render(),!0}return panel(e,memoryStatusLines(e)),e.render(),!0}if("sync"===n||"push"===n||"pull"===n){const t="sync"===n?(o||"status").toLowerCase():n;if("on"===t||"off"===t){const n="on"===t;return setMemoryGate(e,n),note(e,n?'persisting memory on — sessions are stored after each turn (this is the old "cloud sync")':"persisting memory off — nothing new is stored; /sync now still runs a manual pass"),e.render(),!0}if("now"===t)return await runCloudSync(e),e.render(),!0;const r=cloudsync.status();panel(e,[...memoryStatusLines(e),[span(C.gray,"")],[span(C.white+BOLD,"Sync ledger"),span(BOLD_OFF,"")],[span(C.gray,` local sessions: ${r.local} · pending push: ${r.pending} · in sync: ${r.synced}`)],[span(C.gray,` last push: ${r.lastPushAt?new Date(r.lastPushAt).toLocaleString():"never"} · last pull: ${r.lastPullAt?new Date(r.lastPullAt).toLocaleString():"never"}`)],[span(C.gray,` state: ${r.path}`)]]);for(const t of r.errors.slice(0,3))panel(e,[[span(C.coral,` ⚠ ${t.error}`)]]);return e.render(),!0}const r=cloudsync.status();return panel(e,[...keyPanelLines(e,"AEGIS cloud"),[span(C.gray,"")],...memoryStatusLines(e),[span(C.gray,"")],[span(C.white+BOLD," Sync"),span(BOLD_OFF,"")],[span(C.gray,` ${r.pending} pending · ${r.synced} in sync · ${r.importedRemote} pulled from cloud`)],[span(C.gray," /cloud memory on | off · /cloud sync on | off · /sync now")]]),e.render(),!0}},{name:"key",aliases:["apikey","api-key"],args:["value"],hint:"[<api_key>|status|clear|register]",category:"auth",desc:"Save or show the AEGIS account key",handler:async(e,t)=>{const n=String(t.value||t._rest||"").trim(),o=n.toLowerCase();if("status"===o)return panel(e,keyPanelLines(e)),e.render(),!0;if("register"===o){const t=await e.registerAccount();return t.alreadyKeyed?note(e,"this machine already has an AEGIS key — /key status shows it. Re-registering cannot mint a new welcome trial: that is granted once per machine, ever. For a fresh trial, sign up at aegiscloud.org; to point this session at a different key, /key clear first."):t.key&&t.ok?done(e,"AEGIS account key provisioned and saved"):t.key?note(e,"the account was created but its key could not be saved — run /key <api_key> with the key from aegiscloud.org"):note(e,`could not register this machine: ${t.error?t.error.message:"the server returned no account key"}`),e.render(),!0}if("clear"===o||"remove"===o||"rm"===o){const t=e.forgetApiKey();return done(e,t.cleared?`key removed from ${t.path}`:"there was no saved key to remove"),credentials.legacyKeyOnDisk()&¬e(e,`a copy is still in ${configPath()} (written by another AEGIS CLI) — delete the "aegiscloud" block to finish the job`),e.render(),!0}return await applyAccountKey(e,n),e.render(),!0}},{name:"sync",aliases:["cloudsync","cloud-sync"],args:["mode"],hint:"[now|on|off|status]",category:"data",desc:"Store sessions in AEGIS Cloud (cross-session memory)",hidden:e=>!cloudReady(),handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if("on"===n||"off"===n)return setMemoryGate(e,"on"===n),note(e,"on"===n?"persisting memory on — sessions are stored so an interrupted turn can be resumed":"persisting memory off — nothing new is stored; /sync now still runs a manual pass"),e.render(),!0;if("status"===n){const t=cloudsync.status(),n=memoryStatusLines(e);return n.push([span(C.gray,"")]),n.push([span(C.gray,` local ${t.local} · pending ${t.pending} · in sync ${t.synced}`)]),panel(e,n),e.render(),!0}return await runCloudSync(e),e.render(),!0}},{name:"gmail",hint:"",category:"support",desc:"Link Gmail to conversations",handler:async e=>(note(e,"Gmail integration needs Google OAuth — not available in this build. Use /export to save conversations to files instead."),e.render(),!0)},{name:"clone",aliases:["fetch-site","websnap"],args:["url"],hint:"<url>",category:"workspace",desc:"Clone a website into a local project",handler:async(e,t)=>{const n=(t._rest||t.url||"").trim();return n?(note(e,`/clone needs a web-fetch tool and a chat service — not available in this build. Use /init to scaffold a fresh project instead of ${n}.`),e.render(),!0):(note(e,"Usage: /clone <url>"),e.render(),!0)}},{name:"release-notes",hint:"",category:"support",desc:"What's new",handler:async e=>(panel(e,panels.buildReleaseNotes(e.state(),e.ctx)),e.render(),!0)},{name:"aegis-status",hint:"",category:"aegis",desc:"Show account status — API key, plan, account and cloud memory",tool:"aegis_status",build:()=>({})},{name:"aegis-ask",aliases:["ask"],args:["question"],hint:"<question>",category:"aegis",desc:"Ask ÆGIS pooled inference a question (auto-routed)",tool:"aegis_ask",build:e=>({prompt:e})},{name:"aegis-recall",aliases:["recall"],args:["topic"],hint:"<topic>",category:"aegis",desc:"Recall cross-session memory about a topic (cloud)",tool:"aegis_memory_search",build:e=>({query:e})},{name:"aegis-remember",aliases:["remember"],args:["note"],hint:"<note>",category:"aegis",desc:"Save a note or decision to cross-session memory",tool:"aegis_memory_save",build:e=>({content:e})},{name:"aegis-council",aliases:["council"],args:["question"],hint:"<question>",category:"aegis",desc:"Put a question to the ÆGIS council (multi-perspective deliberation)",hidden:()=>!cloudReady(),handler:async(e,t)=>{const n=(t._rest||t.question||"").trim();if(!n)return note(e,"Usage: /aegis-council <question>"),e.render(),!0;const o=composeResearchPrompt(`Deliberate as a council and vote on: ${n}`,process.cwd());return e.runPrompt?(await e.runPrompt(o),!0):(note(e,`Composed council prompt (${o.length} chars) — run in the TUI to send it.`),e.render(),!0)}},{name:"aegis-print",args:["question"],hint:"<question>",category:"aegis",desc:"Ask pooled inference and print the answer cleanly",hidden:()=>!cloudReady(),handler:async(e,t)=>{const n=(t._rest||t.question||"").trim();if(!n)return note(e,"Usage: /aegis-print <question>"),e.render(),!0;const o=await e.ask(n);return panel(e,panels.buildAegisPrint("ÆGIS",{result:o.text,model:o.model,provider:"aegis"},e.ctx)),e.render(),!0}},{name:"aegis-multi",args:["task","mode"],hint:"<task> [run]",category:"aegis",desc:'Compose an ÆGIS /multi multi-agent task (add "run" to execute)',hidden:()=>!cloudReady(),handler:async(e,t)=>{let n=(t._rest||t.task||"").trim(),o=(t.mode||"").toLowerCase();return"run"!==o&&/\s+run$/i.test(n)&&(o="run",n=n.replace(/\s+run$/i,"").trim()),n?"run"!==o?(panel(e,panels.buildAegisMulti(n,e.ctx)),e.render(),!0):runMultiCommand(e,n):(note(e,"Usage: /aegis-multi <task> [run]"),e.render(),!0)}},{name:"byok",hint:"",category:"auth",desc:"List every provider you can bring your own key for, and which are set",handler:async e=>{const t=await byokCatalog(e.client);if(!t)return await e.runTool("aegis_byok_status",{}),!0;const n=t.filter((e=>e.configured)).length,o=[[span(C.gold+BOLD,"Bring your own key"),span(BOLD_OFF,"")],[span(C.gray,"─".repeat(34))],[span(n?C.green:C.gray,` ${n} of ${t.length} providers set`),span(C.gray," — /byok-list picks one, or /byok-key <provider>")],"",...byokProviderLines(t)];return panel(e,o),e.render(),!0}},{name:"byok-set",args:["provider"],hint:"<provider>",category:"auth",desc:"Store your provider key on your AEGIS ACCOUNT (pooled route) — for the byok class use /byok-key",tool:"aegis_byok_set",secret:"key",build:e=>({provider:String(e||"").trim()}),async secretDescribe(e,t){const n=String(e.provider||"").trim(),o=await byokCatalog(t);if(!o)return n?null:{note:"Usage: /byok-set <provider> — /byok lists them.",prompt:"provider key: "};const r=findByokProvider(o,n);if(r.ambiguous)return{note:`"${n}" matches ${r.ambiguous.join(", ")} — retype the exact id. Nothing was sent.`,prompt:null};const s=r.provider;if(!s)return{note:`unknown provider "${n}". Known ids: ${o.map((e=>e.id)).join(", ")}`,prompt:null};if(s.configured)return{note:`${s.id} already has a key${s.masked?` (${s.masked})`:""} — pasting a new one replaces it.`,prompt:`new ${s.label||s.id} key: `,provider:s.id};const a=[`${s.label||s.id}`],i=(s.models||[]).map((e=>"string"==typeof e?e:e&&e.id)).filter(Boolean);return i.length&&a.push(`unlocks ${i.join(", ")}`),s.key_prefix&&a.push(`key starts with ${s.key_prefix}`),s.key_url&&a.push(`create one at ${s.key_url}`),{note:a.join(" · "),prompt:`${s.id} key: `,provider:s.id}}},{name:"byok-rm",args:["provider"],hint:"<provider>",category:"auth",desc:"Remove a stored provider key",tool:"aegis_byok_set",build:e=>({provider:String(e||"").trim()})},{name:"class",args:["class","mode"],hint:"[aegis|byok|local|pro [on|off]]",category:"model",desc:'Show or switch which class turns run on; pro (your Claude subscription) needs a one-time "on"',handler:async(e,t)=>{const n=t||{},o=e.ctx&&e.ctx.modelClass||"aegis",r=t=>e.classLabel?e.classLabel(t):t,s=String(n.class||"").trim().toLowerCase();if("pro"===s&&n.mode){const t=String(n.mode).trim().toLowerCase();if("on"!==t&&"off"!==t)return e.push({role:"error",text:`usage: /class pro [on|off] — got "${n.mode}"`}),!0;const s="on"===t;if(e.saveConfig({proEnabled:s}),e.push({role:s?"done":"note",text:s?"pro class enabled — /class pro switches to your Claude Code subscription. It runs only if that subscription has Claude Code access.":"pro class disabled — it is no longer offered by /class or the model picker."}),!s&&"pro"===o){const t=e.switchClass("aegis");t.ok&&e.push({role:"note",text:`class: ${t.class} — ${r(t.class)}`})}return!0}if(!s){const t=await Promise.resolve(e.classes?e.classes():[]).catch((()=>[])),n=t.length?t:[{class:"aegis"},{class:"byok"}],r=n.findIndex((e=>e.class===o));return e.openOverlay({type:"class",items:n,sel:r<0?0:r,current:o}),!0}const a=e.switchClass(s);if(!a.ok)return e.push({role:"error",text:a.error}),!0;if(e.push({role:"done",text:`class: ${a.class} — ${r(a.class)}`}),a.cleared&&e.push({role:"note",text:`cleared the pin "${a.cleared}" — it does not belong to this class. /models lists what fits.`}),!("byok"!==a.class||e.ctx&&e.ctx.model)){const t=(await e.listModelsFor("byok")||[]).filter((e=>!e.cls||"byok"===e.cls)),n=t.find((e=>e.configured))||t[0];n?(e.ctx.model=n.id,e.saveConfig({model:n.id,currentModelId:n.id}),e.push({role:"note",text:n.configured?`using ${n.id} — /models lists the rest.`:`using ${n.id}, but no ${n.provider} key is saved yet — /byok-key ${n.provider}.`})):0===t.length&&e.push({role:"note",text:"nothing to relay yet — save a provider key with /byok-key <provider>, then /models."})}return!0}},{name:"models",aliases:["model-list"],hint:"",category:"model",desc:"Pick a model to pin, for the class you are on — opens the same picker as /model",handler:async e=>{const t=e.ctx&&e.ctx.modelClass||"aegis",n=await e.listModelsFor(t)||[];if(!n.length)return note(e,"byok"===t?"nothing to relay yet — save a provider key with /byok-key <provider>":"no models advertised — check the account with /status, then retry"),e.render(),!0;const o=e.ctx&&e.ctx.model,r=n.map((e=>e.cls&&e.cls!==t?{...e,note:`${e.note||e.label||""} · pooled lane — /class ${e.cls}`}:e)),s=r.findIndex((e=>e.id===o));return e.openOverlay({type:"model",items:r,sel:s<0?0:s,current:o,cls:t}),!0}},{name:"byok-list",aliases:["byok-pick"],hint:"",category:"auth",desc:"Pick a provider to set a key for, then its models appear in /model",handler:async e=>{const t=await byokCatalog(e.client);if(!t||!t.length)return e.push({role:"error",text:"Could not read the provider catalog (offline, or no AEGIS key) — /byok lists what is known."}),!0;if("function"!=typeof e.openOverlay)return e.push({role:"note",text:"/byok-key <provider> — /byok lists the providers."}),!0;const n=(t.find((e=>e.configured))||{}).id||null,o=Math.max(0,t.findIndex((e=>e.configured)));return e.openOverlay({type:"provider",command:"byok-key",items:t,sel:o,current:n,hint:"↑↓ or tab move · enter picks · the key is stored on this machine"}),!0}},{name:"byok-key",args:["provider"],hint:"<provider> [key]",category:"auth",desc:"Save YOUR provider key on THIS MACHINE — the key the byok class sends",handler:async(e,t)=>{const n=t||{},o=String(n.provider||"").trim().toLowerCase();if(!o){const t=await byokCatalog(e.client);if(!t||!t.length)return e.push({role:"error",text:"Usage: /byok-key <provider> — /byok lists the providers."}),!0;if("function"!=typeof e.openOverlay)return e.push({role:"error",text:"Usage: /byok-key <provider> — /byok lists the providers."}),!0;const n=(t.find((e=>e.configured))||{}).id||null,o=Math.max(0,t.findIndex((e=>e.configured)));return e.openOverlay({type:"provider",command:"byok-key",items:t,sel:o,current:n,hint:"↑↓ or tab move · enter picks · the key is stored on this machine"}),!0}const r=e.settings&&e.settings();if(!r||"function"!=typeof r.set)return e.push({role:"error",text:"this client has no provider-key store."}),!0;const s=await byokCatalog(e.client),a=s?findByokProvider(s,o):null;if(a&&a.ambiguous)return e.push({role:"error",text:`"${o}" matches ${a.ambiguous.join(", ")} — retype the exact id.`}),!0;if(s&&!a?.provider){const t=s.map((e=>e.id)).join(", ");return e.push({role:"error",text:`unknown provider "${o}". Known ids: ${t} — nothing was saved.`}),!0}const i=a&&a.provider,d=i&&i.id||o,l=String(n._rest||"").trim(),c=l.indexOf(" ");let u=-1===c?"":l.slice(c+1).trim();if(u||(i&&i.key_url&&e.push({role:"note",text:`create a ${i.label||d} key at ${i.key_url}`}),u=String(await e.readSecret(`${d} key: `)||"").trim()),!u)return e.push({role:"note",text:"nothing saved."}),!0;if(i&&i.key_prefix&&!u.startsWith(i.key_prefix)&&e.push({role:"note",text:`heads up: ${d} keys normally start with "${i.key_prefix}" — saved anyway.`}),"custom"===d&&!savedByokBaseURL(e,d))return e.push({role:"error",text:`the "custom" provider needs an endpoint as well as a key — a key alone dials nothing. Use: /model-add custom <https-base-url> ${u} <model-id> (saves endpoint, key and model together) — nothing was saved.`}),!0;r.set(e.byokNamespace(d),{key:u});let p="";try{const{envVarFor:t,setEnvValue:n}=require(resolveShared(path.join("client","env-file.js"))),o=t(d);if(o){const t=n(o,u);t.ok?p=o:e.push({role:"note",text:`heads up: could not write ${o} to ~/.aegiscode/.env (${t.error}).`})}}catch{}let h=[];if("function"==typeof e.refreshByokModels)try{h=await e.refreshByokModels()||[]}catch{h=[]}if(!h.length&&"function"==typeof e.listModelsFor)try{h=(await e.listModelsFor("byok")||[]).filter((e=>!e.cls||"byok"===e.cls))}catch{h=[]}const m=h.filter((e=>e&&(e.provider===d||String(e.id||"").startsWith(`${d}:`)))),g=e.ctx&&e.ctx.modelClass||"aegis";let y="byok"===g;if(!y&&"aegis"===g&&"function"==typeof e.switchClass){const t=e.switchClass("byok");t&&t.ok&&(y=!0,e.push({role:"note",text:`class: byok — ${e.classLabel?e.classLabel("byok"):"your own key"}`}))}y||"aegis"===g||e.push({role:"note",text:`staying on class: ${g} — the ${d} key is saved, and /class byok spends it.`});const f=y&&m.length?String(m[0].id):"";return f&&e.ctx&&(e.ctx.model=f,e.saveConfig({model:f,currentModelId:f,modelClass:"byok"})),e.push({role:"done",text:f?`saved a ${d} key on this machine${p?` (${p} in ~/.aegiscode/.env, so it is there next time)`:""} — model ${f} pinned, /model lists the rest.`:y||"aegis"===g?`saved a ${d} key on this machine${p?` (${p} in ~/.aegiscode/.env, so it is there next time)`:""} — /models lists its models, /class byok runs on it.`:`saved a ${d} key on this machine${p?` (${p} in ~/.aegiscode/.env, so it is there next time)`:""} — class is still ${g}; /class byok switches to it whenever you want.`}),!0}},{name:"byok-rm-key",args:["provider"],hint:"<provider>",category:"auth",desc:"Forget the provider key saved on this machine",handler:async(e,t)=>{const n=String((t||{}).provider||"").trim().toLowerCase();if(!n)return e.push({role:"error",text:"Usage: /byok-rm-key <provider> — /byok lists the providers."}),!0;const o=e.settings&&e.settings();if(!o||"function"!=typeof o.remove)return e.push({role:"error",text:"this client has no provider-key store."}),!0;const r=e.byokNamespace(n),s="function"==typeof o.rawKey?o.rawKey(r):null;return o.remove(r),e.push({role:s?"done":"note",text:s?`removed the ${n} key from this machine.`:`no ${n} key was saved on this machine.`}),!0}},{name:"model-add",aliases:["add-model"],args:["provider"],hint:"<provider> [api-key] [model-id|*] (custom: <base-url> <api-key> [model-id|*])",category:"model",desc:"Save a provider key and offer a model id in one step (asks the vendor when it can)",handler:async(e,t)=>{const n=t||{},o=String(n.provider||"").trim();if(!o)return e.push({role:"error",text:"Usage: /model-add <provider> [api-key] <model-id> — /byok lists the providers. A vendor this catalog does not name yet: /model-add custom <https-base-url> <api-key> <model-id>. Example: /model-add deepseek sk-xxxxxxxx deepseek-v4.3-preview"}),!0;const r=splitCommandWords(String(n._rest||"").trim());let s=r.length&&r[0].toLowerCase()===o.toLowerCase()?r.slice(1):r;const a=await byokCatalog(e.client),i=a?findByokProvider(a,o):null;if(i&&i.ambiguous)return e.push({role:"error",text:`"${o}" matches ${i.ambiguous.join(", ")} — retype the exact id.`}),!0;if(a&&(!i||!i.provider))return e.push({role:"error",text:`no provider "${o}" in the relay's catalog — /byok lists the ones it takes a key for.`}),!0;const d=i&&i.provider&&i.provider.id||o.toLowerCase();let l="",c="";if("custom"===d){if(1===s.length&&!savedByokBaseURL(e,d))return e.push({role:"error",text:"one word cannot say whether it is the URL or the model id — nothing was saved. Type the endpoint first: /model-add custom <https-base-url> <api-key> [model-id]"}),!0;s.length>=2&&(l=s.shift(),c=s.shift())}else s.length>=2&&(c=s.shift());let u=s.join(" ").trim();if(c){const t=e.settings&&e.settings();if(!t||"function"!=typeof t.set)return e.push({role:"error",text:"this client has no provider-key store."}),!0;const n=i&&i.provider;n&&n.key_prefix&&!c.startsWith(n.key_prefix)&&e.push({role:"note",text:`heads up: ${d} keys normally start with "${n.key_prefix}" — saved anyway.`}),l&&!/^https:\/\//i.test(l)&&e.push({role:"note",text:"heads up: aegis1 only dials an https:// base_url — saved anyway, but calls on it will be refused."}),t.set(e.byokNamespace(d),{key:c,...l?{baseURL:l}:{}});try{const{envVarFor:t,setEnvValue:n}=require(resolveShared(path.join("client","env-file.js"))),o=t(d);if(o){const t=n(o,c);t.ok||e.push({role:"note",text:`heads up: could not mirror the key into ~/.aegiscode/.env (${t.error}).`})}}catch{}e.push({role:"done",text:l?`saved a ${d} key and base URL (${l}) on this machine.`:`saved a ${d} key on this machine.`})}const p=byokKeyForProvider(e,d),h=await offeredModelIds(e,d,p);if("*"===u){if(!h){const t=await discoverProviderModels(e,d,p);return e.push({role:"error",text:`cannot list ${d}: ${t&&t.error||"no list available"} — type the ids instead: /model-add ${d} <model-id>`}),!0}const t=addManyUserModels(d,h);if("function"==typeof e.refreshByokModels)try{await e.refreshByokModels()}catch{}return e.push({role:"done",text:`added ${t.added} of the ${h.length} model ids ${d} serves${t.already.length?` (${t.already.length} were already declared)`:""}.`}),t.capped&&e.push({role:"note",text:`stopped at the store's per-provider cap (32) — ${t.capped} more id(s) were left out; /model-add ${d} <model-id> stores a specific one, /model-rm frees a slot.`}),t.failed.length&&e.push({role:"note",text:`${t.failed.length} id(s) were refused: ${t.failed.map((e=>e.id)).join(", ")}`}),e.push({role:"note",text:`stored in ${userModelsPath()} — the desktop reads the same file. /model-discover ${d} lists what the vendor serves.`}),!0}if(!u){h&&e.push({role:"note",text:`${d} serves ${h.length} model ids — ${h.slice(0,12).join(", ")}${h.length>12?", …":""}`});const t=String(await e.askInput(h?`model id for ${d} (1-${h.length}, or type one): `:`model id for ${d}: `)||"").trim(),n=h&&/^\d+$/.test(t)?Number(t):0;u=h&&n>=1&&n<=h.length?h[n-1]:t}if(!u)return e.push({role:"note",text:"nothing saved."}),!0;let m;try{m=addUserModel(d,u)}catch(t){return e.push({role:"error",text:t&&t.message||String(t)}),!0}if("function"==typeof e.refreshByokModels)try{await e.refreshByokModels()}catch{}const g=(("function"==typeof e.listModelsFor?await e.listModelsFor("byok"):[])||[]).find((e=>e&&e.id===`${d}:${u}`));return e.push({role:m.added?"done":"note",text:m.added?`added ${d}:${u} — offered on this machine now, in the CLI and the desktop.`:`${d}:${u} was already declared.`}),a||e.push({role:"note",text:`the relay's catalog could not be read, so "${d}" is unverified — if it does not appear in /models, /byok lists the provider ids it takes.`}),m.added&&!g&&e.push({role:"note",text:`saved, but no row will be offered for "${d}" yet — the relay lists no provider of that id (or that provider lists no models).`}),m.added&&h&&e.push({role:"note",text:`${d} currently serves ${h.length} model ids — /model-discover ${d} lists them, /model-add ${d} '*' takes them all.`}),e.push({role:"note",text:`stored in ${m.file} — the desktop reads the same file.`}),!0}},{name:"model-discover",aliases:["discover-models","vendor-models"],args:["provider"],hint:"<provider>",category:"model",desc:"List the model ids your provider's own API serves",handler:async(e,t)=>{const n=String((t||{}).provider||"").trim();if(!n)return e.push({role:"error",text:`Usage: /model-discover <provider> — this client can ask: ${discoverableProviders().join(", ")}`}),!0;const o=await byokCatalog(e.client),r=o?findByokProvider(o,n):null,s=(r&&r.provider&&r.provider.id||n).toLowerCase(),a=vendorEndpointFor(s);if(!a)return e.push({role:"error",text:`no list endpoint for "${s}" in this client — /model-add ${s} <model-id> stores an id you already know. Providers it can ask: ${discoverableProviders().join(", ")}`}),!0;const i=byokKeyForProvider(e,s);if(!i)return e.push({role:"error",text:`no ${s} key on this machine — /byok-key ${s} saves one (or put it in ~/.aegiscode/.env), then this lists what the key reaches.`}),!0;const d=await discoverProviderModels(e,s,i);if(!d||!d.ok)return e.push({role:"error",text:`could not list ${s}: ${d&&d.error||"no answer"}`}),!0;const l=new Set(userModelIdsFor(s)),c=new Set((r&&r.provider&&r.provider.models||[]).map((e=>String(e))));e.push({role:"note",text:`${s} at ${a.url}${a.note?` (${a.note})`:""}`}),e.push({role:"note",text:`${d.count} chat model id(s) the vendor serves — mark: [seen] the relay already lists it, [your] you declared it, [new] this machine does not offer it yet.`});const u=d.ids.map(((e,t)=>{const n=l.has(e)?"[your]":c.has(e)?"[seen]":"[new]";return`${String(t+1).padStart(3)}. ${n} ${e}`}));u.length&&e.push({role:"panel",lines:u}),u.length||e.push({role:"note",text:`the vendor answered with no chat models — /model-add ${s} <model-id> stores one by hand.`}),d.others.length&&e.push({role:"note",text:`${d.others.length} id(s) are not chat models (embeddings, audio, moderation or an unsupported method) and are left out: ${d.others.slice(0,8).join(", ")}${d.others.length>8?", …":""}`});const p=d.ids.filter((e=>!l.has(e)&&!c.has(e)));return p.length&&e.push({role:"note",text:`${p.length} of them are not offered on this machine yet — /model-add ${s} '<model-id>' stores one, /model-add ${s} '*' stores every chat model the vendor serves.`}),!0}},{name:"model-rm",aliases:["rm-model"],args:["provider"],hint:"<provider> <model-id>",category:"model",desc:"Forget a model id you added with /model-add",handler:async(e,t)=>{const n=t||{},o=String(n.provider||"").trim(),r=String(n._rest||"").trim(),s=r.indexOf(" "),a=-1===s?"":r.slice(s+1).trim();if(!o||!a)return e.push({role:"error",text:"Usage: /model-rm <provider> <model-id> — /model-add lists what you added."}),!0;let i;try{i=removeUserModel(o,a)}catch(t){return e.push({role:"error",text:t&&t.message||String(t)}),!0}if("function"==typeof e.refreshByokModels)try{await e.refreshByokModels()}catch{}return e.push({role:i.removed?"done":"note",text:i.removed?`removed ${i.provider}:${i.model} — the picker stops offering it on the next refresh.`:`${i.provider}:${i.model} was not declared on this machine.`}),!0}},{name:"tool",args:["name","json"],hint:"<name> [json]",category:"aegis",desc:"Call any registry tool directly (escape hatch for new tools)",generic:!0,build:e=>{const t=String(e||""),n=t.indexOf(" "),o=(-1===n?t:t.slice(0,n)).trim(),r=-1===n?"":t.slice(n+1).trim();let s={};if(r)try{s=JSON.parse(r)}catch(e){throw new Error(`/tool: arguments must be JSON — ${e.message}`)}return{tool:o,args:s}}},{name:"aegis-import",aliases:["import"],hint:"[--confirm]",category:"aegis",desc:"Import memory from other AI tools on this machine (dry run unless --confirm)",tool:"aegis_memory_import",build:e=>({confirm:/--confirm\b/.test(String(e||""))})}],BY_NAME=new Map;for(const e of COMMANDS)for(const t of[e.name,...e.aliases||[]]){if(BY_NAME.has(t))throw new Error(`aegiscode: command name or alias /${t} is registered twice`);BY_NAME.set(t,e)}function allCommands(){return COMMANDS.map((e=>({...e,categoryLabel:categoryLabel(e.category)})))}function visibleCommands(){return allCommands().filter((e=>!("function"==typeof e.hidden?e.hidden():e.hidden)))}function findCommand(e){return BY_NAME.get(String(e||"").toLowerCase())||null}function canonicalName(e){const t=findCommand(e);return t?t.name:e}function parseLine(e){const t=String(null==e?"":e).trim();if(!t)return{kind:"empty"};if("/"!==t[0])return{kind:"prompt",text:t};const n=t.indexOf(" "),o=(-1===n?t.slice(1):t.slice(1,n)).trim(),r=-1===n?"":t.slice(n+1).trim(),s=findCommand(o);return s?s.unavailable?{kind:"unavailable",command:s,arg:r}:{kind:"command",command:s,arg:r}:{kind:"unknown",name:o,text:t}}function toolBackedCommands(){return COMMANDS.filter((e=>e.tool))}module.exports={CATEGORIES:CATEGORIES,categoryLabel:categoryLabel,EFFORT_LEVELS:EFFORT_LEVELS,COMMANDS:COMMANDS,allCommands:allCommands,visibleCommands:visibleCommands,findCommand:findCommand,canonicalName:canonicalName,parseLine:parseLine,toolBackedCommands:toolBackedCommands,backfillSessionNames:backfillSessionNames};
|
|
5
|
+
name:"license",aliases:["licence"],hint:"",category:"support",desc:"Show this program's licence (AGPL-3.0-or-later) and where to read it",handler:async e=>{const t=loadCredits(),n=t.program||{},o=[];if(o.push("Licence"),o.push(" "+(n.name||"GNU Affero General Public License v3.0 or later")),o.push(" "+(n.licence||"AGPL-3.0-or-later")),o.push(""),n.copyright&&o.push(" "+n.copyright),n.url&&o.push(" Full text: "+n.url),n.source&&o.push(" Source: "+n.source),o.push(""),o.push(" /credits lists the vendored third-party code and fonts."),n.notice){o.push("");for(const e of String(n.notice).split("\n"))o.push(e?" "+e:"")}Array.isArray(t.missing)&&t.missing.length&&(o.push(""),o.push(" Could not read: "+t.missing.join(", ")));for(const t of o)note(e,t);return e.render(),!0}},{name:"credits",hint:"",category:"support",desc:"Show third-party attributions and the licence the bundled fonts carry",handler:async e=>{const t=loadCredits(),n=[],o=Array.isArray(t.code)?t.code:[],r=Array.isArray(t.fonts)?t.fonts:[];if(n.push("Credits"),n.push(" "+(t.program&&t.program.copyright||"")),o.length){n.push(""),n.push(" Vendored third-party code");for(const e of o)n.push(" "+e.name+(e.version?" v"+e.version:"")+(e.licence?" "+e.licence:"")),e.url&&n.push(" "+e.url)}if(r.length){n.push(""),n.push(" Vendored webfonts");for(const e of r)n.push(" "+e.name+" "+(e.copyright||"")+(e.licence?" "+e.licence:"")),e.url&&n.push(" "+e.url)}o.length||r.length||(n.push(""),n.push(" No attribution files could be read from this installation.")),n.push(""),n.push(" /license shows the licence this program itself is under.");for(const t of n)note(e,t);return e.render(),!0}},{name:"doctor",args:["action"],hint:"[fix|system]",category:"support",desc:"Run diagnostic checks on this environment",handler:async(e,t)=>{const n=(t&&t.action||"").toLowerCase();if(n&&"fix"!==n&&"system"!==n)return note(e,'Usage: /doctor [fix|system] — "fix" re-tightens the data dir to 0700/0600, "system" checks the machine itself'),e.render(),!0;const o=[],r=(e,t,n)=>o.push([t,e,n]);r("Node",!0,process.version),r("CWD",fs.existsSync(process.cwd()),process.cwd());let s=!1;try{execSync("git rev-parse --git-dir",{cwd:process.cwd(),stdio:["ignore","ignore","ignore"],timeout:4e3}),s=!0}catch{}r("git repo",s,s?"inside a work tree":"not a git repository");const a=credentials.keyStatus();r("AEGIS key",a.configured,a.configured?`${maskKey(a.key)} via ${credentials.sourceLabel(a.source)}`:`not set — ${credentials.HOW_TO_SET} (free key: ${signupUrl("doctor")})`),r("credentials",!0,`${a.path}${a.fileMode?` (${a.fileMode})`:""}`),r("cloud memory",a.memoryToken,a.memoryToken?"token held":"no memory token — /cloud activate"),a.legacyPlaintext&&r("plaintext key",!1,`a copy also sits in ${configPath()} (another AEGIS CLI) — /key re-saves it to ${a.path}`),r("config path",!0,configPath());const i=aegisDir();let d=null;"fix"===n&&(d=repairExposure(i));const l=auditExposure(i);if(l.exists)if(l.modesMeaningful){const e=l.exposed.slice(0,4).map((e=>`${e.rel} ${e.mode}`)).join(", ");r("data dir",0===l.exposed.length,0===l.exposed.length?`${i} (${l.rootMode}, all private)`:`${i} (${l.rootMode}) — ${l.exposed.length} path(s) group/world-accessible: ${e}${l.exposed.length>4?", …":""} — run /doctor fix`)}else r("data dir",!0,`${i} (${l.total} path(s)) — this filesystem has no POSIX permission bits; access is governed by the profile directory's own ACL`);else r("data dir",!0,`${i} (not created yet)`);if(d&&!d.modesMeaningful)r("repair",!0,"nothing to tighten — this filesystem has no POSIX permission bits");else if(d){const e=d.fixed.slice(0,3).map((e=>`${e.rel} ${e.from}→${e.to}`)).join(", ");r("repair",0===d.remaining.length,0===d.remaining.length?d.fixed.length?`tightened ${d.fixed.length} path(s) — ${e}${d.fixed.length>3?", …":""}`:"already private, nothing to tighten":`${d.remaining.length} path(s) still exposed — `+d.failed.map((e=>`${e.rel}: ${e.reason}`)).join(", "))}let c=null;if("system"===n){const e=sysdiag.collect();if(e.ok){c=sysdiag.assess(e.data);for(const e of c.findings)r(`${e.title} (${e.severity})`,!1,`${e.detail} → ${e.remedyText}`);for(const e of c.clean)r(e.title,!0,e.detail);for(const e of c.unassessed)r(`${e.title} (unassessed)`,!1,e.reason)}else r("machine checks",!1,"not-windows"===e.reason?"not available on this platform — the machine audit is Windows-only (cli/src/sysdiag.js)":`could not run: ${e.reason}`)}const u=[[span(C.gold+BOLD,"Doctor"),span(BOLD_OFF,"")],[span(C.gray,"─".repeat(30))]];for(const[e,t,n]of o)u.push([span(e?C.green:C.coral," "+(e?"✔":"⚠")),span(C.white,` ${t}: `),span(C.gray,String(n))]);if(c&&c.findings.length){const e=c.summary;u.push([span(C.gold," Remedy"),span(C.gray,` — ${e.findings} finding(s) across ${e.assessed}/${e.total} measured checks.`)]),u.push([span(C.gray," Run in an ELEVATED PowerShell. AEGIS diagnoses this; it does not change your machine.")]);for(const e of sysdiag.remedyScript().split("\n"))u.push([span(C.gray,` ${e}`)])}return panel(e,u),e.render(),!0}},{name:"upgrade",args:["action"],hint:"[check|apply]",category:"support",desc:"Check for a newer published version (apply: install it now)",handler:async(e,t)=>{const n=String(t&&t.action||"check").toLowerCase();if(!["check","apply"].includes(n))return note(e,"Usage: /upgrade [check|apply]"),e.render(),!0;const o=installMethod();note(e,"Checking the npm registry…"),e.render();const r=e&&e.withWorking?t=>e.withWorking(t):e=>e(),s=e.ctx&&e.ctx.demo?null:await r((()=>Promise.resolve(latestPublishedVersion()))),a=upgradeAdvice({latest:s,method:o});if(panel(e,a.lines.map((e=>[span(C.white,e)]))),e.render(),"apply"!==n)return!0;if(!a.plan||!a.plan.apply)return note(e,a.plan?`Nothing to install: ${a.plan.instruction}`:"Nothing to install."),e.render(),!0;note(e,`Running: ${a.plan.instruction}`),e.render();const i=applyUpgrade({method:o,latest:s,current:a.plan.current});if(i.ok&&!i.skipped){if(note(e,`Installed ${a.plan.latest}. Restart aegiscode to use it.`),i.output)for(const t of i.output.split("\n").slice(-6))note(e,` ${t}`)}else i.skipped?note(e,`Not applied: ${i.instruction}`):(note(e,`Upgrade failed: ${i.error}`),note(e,`Run it yourself: ${i.command}`));return e.render(),!0}},{name:"vim",args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle vim keymap",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if(n&&!["on","off"].includes(n))return note(e,"Usage: /vim [on|off]"),e.render(),!0;const o="on"===n||"off"!==n&&!e.ctx.vim;return e.ctx.vim=o,e.saveConfig({vim:o}),note(e,"Vim keymap: "+(o?"on":"off")),e.render(),!0}},{name:"permissions",args:["mode","pattern"],hint:'[allow|deny|ask "<pattern>" | default <ask|allow|deny> | mode <m> | clear]',category:"model",desc:"Set permissions for tool use",handler:async(e,t)=>{const n=loadPermissions(),o=(t.mode||"").toLowerCase(),r=t.pattern;if(!o){const t=permissionMode();return panel(e,panels.buildPermissions({...n,_path:permissionsPath(),_permissionMode:t},null,e.ctx)),e.render(),!0}if("mode"===o){const t=(r||"").toLowerCase();if(!t){const t=permissionMode();return note(e,`Child permission mode: ${t||"unset (no --permission-mode is passed)"}`),note(e,`Set with: /permissions mode <${PERMISSION_MODES_LOCAL.join("|")}|off>`),e.render(),!0}if("off"===t||"none"===t)return setPermissionMode(null),note(e,"Child permission mode cleared — the child is spawned with no --permission-mode."),e.render(),!0;try{const n=setPermissionMode(t);note(e,`Child permission mode: ${n}`),confirmPosture().enabled||note(e,"Note: confirmations are OFF, so --dangerously-skip-permissions wins and the mode is recorded but not passed. Run /confirm to let the mode take effect.")}catch(t){note(e,t&&t.message||String(t))}return e.render(),!0}if("clear"===o)return setPermissionDefaultMode(DEFAULT_PERMISSIONS.defaultMode),savePermissions({...DEFAULT_PERMISSIONS,allow:[],deny:[],ask:[]}),note(e,"Permissions reset to defaults (no rules)."),e.render(),!0;if("default"===o&&["ask","allow","deny"].includes(r))return setPermissionDefaultMode(r),note(e,`Default permission mode: ${r}`),e.render(),!0;if(["allow","deny","ask"].includes(o)&&r){const{added:t,rules:s}=addPermissionRule(o,r,n);return savePermissions(s),note(e,t?`Added ${o} rule: ${r}`:`Rule already present: ${r}`),e.render(),!0}return note(e,'Usage: /permissions [allow|deny|ask "<pattern>" | default <ask|allow|deny> | mode <m> | clear]'),e.render(),!0}},{name:"hooks",args:["sub"],hint:"[status|list|install]",category:"model",desc:"View hooks configuration status, list configured hooks, or install this repo's guard hooks",handler:async(e,t)=>{const n=(t.sub||"").toLowerCase();if("install"===n){const n=/--dry-run|\bdry-?run\b/.test(String(t._rest||"")),o=hooksLib.installRepoHooks({cwd:process.cwd(),dryRun:n});if(o.ok)if(n){note(e,`would install the guard hooks in ${o.status.repo}`);for(const t of o.actions)note(e,` ${t}`);o.status.installed&¬e(e,"core.hooksPath is already .githooks — nothing to change")}else if(o.changed){done(e,"installed the guard hooks — core.hooksPath = .githooks (verified)");for(const t of o.actions)note(e,` ${t}`)}else done(e,"guard hooks already installed (core.hooksPath = .githooks)");else if(note(e,o.error),o.actions.length)for(const t of o.actions)note(e,` ${t}`);return o.ok&¬e(e,o.status.execNote),e.render(),!0}const{hooks:o,from:r}=readHooks();return"list"===n?(panel(e,panels.buildHooksList({hooks:o},e.ctx)),e.render(),!0):""===n||"status"===n?(panel(e,panels.buildHooksStatus({...hookStats(o),fromPaths:r},e.ctx)),e.render(),!0):(note(e,`unknown subcommand: ${t.sub}`),note(e,"available: status, list, install [--dry-run]"),e.render(),!0)}},{name:"credentials",hint:"",category:"model",desc:"Show where credentials are stored",handler:async e=>{const t=path.join(os.homedir(),".claude",".credentials.json"),n=t.replace(os.homedir(),"~");return fs.existsSync(t)?note(e,`Credentials live in ${n} (managed by the Claude Code CLI). aegiscode reads them but never writes them.`):note(e,"No credential file found. The Claude Code CLI manages auth (OS keychain or ~/.claude/.credentials.json)."),e.render(),!0}},{name:"install-github-app",hint:"",category:"model",desc:"Install the GitHub App for PR workflows",handler:async e=>(note(e,"The GitHub App is installed through the Claude Code CLI: run `claude --install-github-app` once."),e.render(),!0)},{name:"troubleshooting",hint:"",category:"support",desc:"Troubleshoot common issues",handler:async e=>(panel(e,panels.buildTroubleshooting(e.state(),e.ctx)),e.render(),!0)},{name:"feedback",hint:"",category:"support",desc:"Send feedback to the AEGIS team",handler:async e=>(note(e,"Opening the feedback form…"),openUrl(URLS.feedback)||note(e,`Feedback: ${URLS.feedback}`),e.render(),!0)},{name:"bug",hint:"",category:"support",desc:"Report a bug (opens a GitHub issue)",handler:async e=>(note(e,`Opening a GitHub issue… (aegiscode v${VERSION}, ${process.version}, ${os.platform()})`),openUrl(URLS.issues)||note(e,`Issues: ${URLS.issues}`),e.render(),!0)},{name:"issue",aliases:["bugs"],hint:"",category:"support",desc:"Report an issue",handler:async e=>(note(e,"Opening a GitHub issue…"),openUrl(URLS.issues)||note(e,`Issues: ${URLS.issues}`),e.render(),!0)},{name:"onboarding",hint:"",category:"support",desc:"Show getting-started tips",handler:async e=>(panel(e,panels.buildOnboarding(e.state(),e.ctx)),e.render(),!0)},{name:"shell-completion",hint:"",category:"support",desc:"Set up shell completion",handler:async e=>(panel(e,panels.buildShellCompletion(e.state(),e.ctx)),e.render(),!0)},{name:"terminal-setup",hint:"",category:"support",desc:"Check and fix terminal setup",handler:async e=>(panel(e,panels.buildTerminalSetup(e.state(),e.ctx)),e.render(),!0)},{name:"pr-comments",hint:"",category:"support",desc:"Review and reply to pull request comments",handler:async e=>(note(e,"PR comments need GitHub auth. Run /prs to check connectivity, then use the `gh` CLI or the GitHub web UI."),e.render(),!0)},{name:"prs",hint:"",category:"support",desc:"List pull requests in this repo",handler:async e=>{try{const t=execSync("gh pr list --limit 8",{encoding:"utf8",timeout:15e3,stdio:["ignore","pipe","ignore"]});panel(e,panels.buildPRs(t.toString(),e.ctx))}catch{note(e,"gh not authenticated (or not installed) — run `gh auth login` first.")}return e.render(),!0}},{name:"review",hint:"",category:"support",desc:"Review a pull request",handler:async e=>(note(e,"/review needs GitHub auth via gh. Run /prs to list open PRs, then open one in the browser."),e.render(),!0)},{name:"benchmark",hint:"",category:"support",desc:"Run in-app micro-benchmarks",handler:async e=>{const t=e=>{const t=process.hrtime.bigint();return e(),(Number(process.hrtime.bigint()-t)/1e6).toFixed(2)},n=[["2,000 span() calls",t((()=>{for(let e=0;e<2e3;e++)span(C.white,"x")}))],["estimateTokens × 20 (500 chars)",t((()=>{for(let e=0;e<20;e++)estimateTokens("x".repeat(500))}))]];return markdownModule&&"function"==typeof markdownModule.renderMarkdown&&n.push(["renderMarkdown × 200",t((()=>{for(let e=0;e<200;e++)markdownModule.renderMarkdown("# Heading\n\nSome **bold** and `code` with a [link](https://x.test).\n\n- a\n- b\n- c\n",80)}))]),panel(e,panels.buildBenchmark(n,e.ctx)),e.render(),!0}},{name:"waifu",hint:"",category:"fun",desc:"Summon a waifu",handler:async e=>(panel(e,panels.buildWaifu(e.ctx)),e.render(),!0)},{name:"new",aliases:["start"],hint:"",category:"session",desc:"Start a new session (clears the transcript, fresh session id)",handler:async e=>{e.transcript.length=0,"function"==typeof e.clearConversationMemory&&e.clearConversationMemory();const t="aegis-"+Math.random().toString(36).slice(2,10);return e.sessionId=t,e.ctx.sessionId=t,note(e,`New session started (${t}) — earlier context cleared.`),e.render(),!0}},{name:"tokens",aliases:["tok"],hint:"",category:"data",desc:"Show token usage breakdown and estimated spend",handler:async e=>{const t=sessionAccounting(e.transcript,e.ctx.model);return panel(e,panels.buildTokens({...e.state(),contextWindow:t.contextWindow,costEur:t.cost},e.ctx)),e.render(),!0}},{name:"skills",aliases:["sk"],args:["sub"],hint:"[name|refresh]",category:"session",desc:"List skills (SKILL.md in the standard skill dirs)",handler:async(e,t)=>{const n=(t.sub||"").trim().toLowerCase(),o=scanSkills(),r=[path.join(os.homedir(),".aegis","skills"),path.join(process.cwd(),".aegis","skills"),path.join(os.homedir(),".aegiscode","skills"),path.join(process.cwd(),".aegiscode","skills"),path.join(os.homedir(),".claude","skills")].map((e=>e.replace(os.homedir(),"~")));if("refresh"===n||"reload"===n)return note(e,`Skills refreshed — ${o.length} found (${r.length} dirs scanned).`),e.render(),!0;if(n){const t=o.find((e=>e.name===n));return t?(panel(e,panels.buildSkillDetail(t,e.ctx)),e.render(),!0):(note(e,`Unknown skill "${n}". /skills lists what exists on disk.`),e.render(),!0)}return panel(e,panels.buildSkills(o,r,e.ctx)),e.render(),!0}},{name:"thinking",args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle thinking blocks expanded/collapsed",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if(n&&!["on","off"].includes(n))return note(e,"Usage: /thinking [on|off]"),e.render(),!0;const o="on"===n||"off"!==n&&!(!0===e.ctx.thinking);return e.ctx.thinking=o,e.saveConfig({thinking:o}),note(e,"Thinking blocks: "+(o?"expanded":"collapsed")),e.render(),!0}},{name:"mcp",args:["sub","name","command"],hint:"[add <name> <command> [args…]|remove <name>|<name>]",category:"model",desc:"Show MCP server configuration",handler:async(e,t)=>{const n=loadConfig().mcpServers||{},o=(t.sub||"").toLowerCase();if("add"===o){const o=(t.name||"").trim(),r=(t.command||"").trim();if(!o||!r)return note(e,'Usage: /mcp add <name> "<command with args>"'),e.render(),!0;const s=r.split(/\s+/).filter(Boolean);return updateConfig({mcpServers:{...n,[o]:{command:s[0],args:s.slice(1)}}}),note(e,`Added MCP server "${o}" (${s[0]}). Configuration only — this build has no MCP runtime.`),e.render(),!0}if("remove"===o||"rm"===o){const o=(t.name||"").trim();if(!o)return note(e,"Usage: /mcp remove <name>"),e.render(),!0;if(!n[o])return note(e,`No MCP server "${o}". /mcp lists the configured ones.`),e.render(),!0;const r={...n};return delete r[o],updateConfig({mcpServers:r}),note(e,`Removed MCP server "${o}".`),e.render(),!0}if(o&&n[o]){const t=n[o];return panel(e,[[span(C.gold,`MCP server: ${o}`)],[span(C.gray,"─".repeat(30))],[span(C.white,` command: ${`${t.command||""} ${(t.args||[]).join(" ")}`.trim()}`)],[span("","")],[span(C.gray,"Configuration only — this build has no MCP runtime.")]]),e.render(),!0}return panel(e,panels.buildMcp(n,[configPath(),permissionsPath()],e.ctx)),e.render(),!0}},{name:"memory",aliases:["memories"],hint:"",category:"model",desc:"List the most recent AEGIS cloud-memory entries",tool:"aegis_memory_list",build:()=>({})},{name:"memory-deep",aliases:["recall-deep"],args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle DEEP recall for this session — brain corrections + cached answers (metered: one embedding per turn)",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if(n&&!["on","off"].includes(n))return note(e,"Usage: /memory-deep [on|off]"),e.render(),!0;const o="on"===n||"off"!==n&&!(!0===e.ctx.recallDeep);return e.ctx.recallDeep=o,note(e,`Deep recall: ${o?"on — brain corrections + cached answers, one embedding per turn":"off (only the cheap recall read)"}${o?" · this session only":""}`),e.render(),!0}},{name:"confirm",aliases:["confirmations"],args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle tool-call confirmation prompts",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if(n&&!["on","off"].includes(n))return note(e,"Usage: /confirm [on|off]"),e.render(),!0;const o="on"===n||"off"!==n&&!confirmPosture().enabled;return setConfirmPosture(o),note(e,`Confirmation prompts: ${o?"on":"off"} (default permission mode: ${o?"ask":"allow"})`),e.render(),!0}},{name:"automode",aliases:["yolo"],args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle automode — auto-approve all tool executions",handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if(n&&!["on","off"].includes(n))return note(e,"Usage: /automode [on|off]"),e.render(),!0;const o="on"===n||"off"!==n&&confirmPosture().enabled;return setConfirmPosture(!o),"function"==typeof e.setAutoRounds&&e.setAutoRounds(o),o?panel(e,panels.buildAutomode(e.state(),e.ctx)):note(e,"automode off — confirmations restored."),e.render(),!0}},{name:"multiyolo",aliases:["multiauto"],args:["task"],hint:"<task>",category:"session",desc:"Multi-agent orchestration with automode — /multiyolo <task>",handler:async(e,t)=>{const n=(t._rest||t.task||"").trim();return n?runMultiCommand(e,n,{yolo:!0}):(note(e,"Usage: /multiyolo <task>"),e.render(),!0)}},{name:"router",args:["sub","tier","modelId"],hint:"[on|off|set <tier> <modelId>|stats]",category:"model",desc:"Show or manage the model router config",handler:async(e,t)=>{const n=loadConfig(),o=n.autoRouter||{enabled:!1,tiers:{}},r=(t.sub||"").toLowerCase(),s=e=>updateConfig({autoRouter:e});if("on"===r)return s({...o,enabled:!0}),note(e,"Auto-router: on."),e.render(),!0;if("off"===r)return s({...o,enabled:!1}),note(e,"Auto-router: off."),e.render(),!0;if("set"===r){const n=(t.tier||"").toLowerCase(),r=(t.modelId||"").trim();return["simple","medium","complex"].includes(n)&&r?(s({...o,tiers:{...o.tiers||{},[n]:r}}),note(e,`Auto-router: ${n} -> ${r}`),e.render(),!0):(note(e,"Usage: /router set <simple|medium|complex> <modelId>"),e.render(),!0)}return"stats"===r?(panel(e,[[span(C.gold+BOLD,"Router stats"),span(BOLD_OFF,"")],[span(C.gray,"─".repeat(30))],[span(C.gray,"No learned outcomes yet — this build does not auto-route.")],[span(C.gray,"Tiers: simple/medium/complex via /router set.")]]),e.render(),!0):(panel(e,panels.buildRouter(n,e.ctx)),e.render(),!0)}},{name:"multi",args:["task","mode"],hint:"<task> [run]",category:"session",desc:'Compose a multi-agent task (add "run" to execute)',handler:async(e,t)=>{let n=(t._rest||t.task||"").trim(),o=(t.mode||"").toLowerCase();return"run"!==o&&/\s+run$/i.test(n)&&(o="run",n=n.replace(/\s+run$/i,"").trim()),n?"run"!==o?(panel(e,panels.buildAegisMulti(n,e.ctx)),e.render(),!0):runMultiCommand(e,n):(note(e,"Usage: /multi <task> [run]"),e.render(),!0)}},{name:"research",args:["question"],hint:"<question>",category:"session",desc:"Research a topic with a multi-perspective council prompt",handler:async(e,t)=>{const n=(t._rest||t.question||"").trim();if(!n)return note(e,"Usage: /research <question>"),e.render(),!0;const o=composeResearchPrompt(n,process.cwd());return e.runPrompt?(await e.runPrompt(o),!0):(note(e,`Composed research prompt (${o.length} chars) — run in the TUI to send it.`),e.render(),!0)}},{name:"debate",aliases:["db"],args:["topic"],hint:"<topic>",category:"session",desc:"Run a structured debate on the current model",handler:async(e,t)=>{const n=(t._rest||t.topic||"").trim();if(!n)return note(e,"Usage: /debate <topic>"),e.render(),!0;const o=composeDebatePrompt(n,e.ctx.model||"");return e.runPrompt?(await e.runPrompt(o),!0):(note(e,`Composed debate prompt (${o.length} chars) — run in the TUI to send it.`),e.render(),!0)}},{name:"billing",aliases:["balance","spend"],hint:"",category:"support",desc:"Show billing info — token-bank balance and recent spend",handler:async e=>{await e.runTool("aegis_balance",{});const t=await e.refreshSpend(),n=e.state();return panel(e,panels.buildBilling({...n,balance:t&&null!=t.balance?t.balance:n.balance,payment:await billingPayment(e)},e.ctx)),e.render(),!0}},{name:"topup",aliases:["fund"],args:["amount"],hint:"[EUR]",category:"support",desc:"Top up the token bank — opens the payment page and confirms the credit here",handler:async(e,t)=>{const n=String(t.amount||t._rest||"").trim();let o;try{o=require(require("./sharedpaths.js").resolveShared("client/topup.js"))}catch(t){return note(e,`top-up is unavailable in this build — ${t.message}`),e.render(),!0}const r=o.parseTopupAmount(n);if(!r.ok)return note(e,r.message),e.render(),!0;if(!e.client.apiKey)return note(e,`no AEGIS key on this machine — ${credentials.HOW_TO_SET}, then /topup ${r.amount}`),e.render(),!0;const s=e.withWorking?await e.withWorking((()=>o.startTopup(e.client,r.amount))):await o.startTopup(e.client,r.amount);if(!s.ok)return note(e,`the top-up could not be started — ${s.message}`),s.hint&¬e(e,s.hint),e.render(),!0;note(e,`opening the payment page — ${r.amount} EUR`),note(e,s.url);const a=Math.round(o.TOPUP_POLL_MS*o.TOPUP_POLL_TRIES/1e3);note(e,`watching this account's bank for up to ${a}s; the credit is confirmed here, not in the browser`),e.render(),openUrl(s.url)||note(e,"could not open a browser — use the URL above");const i=o.createCreditWatch(e.client);let d=null,l=!1;const c=()=>{l=!0,d&&clearTimeout(d)},u=async()=>{if(l)return;const t=await i.tick();return"credited"===t.state?(c(),note(e,`credit confirmed — the bank is now ${t.amount.toFixed(2)} EUR`),void e.render()):"expired"===t.state?(c(),note(e,"no credit observed within the watch window — if you completed the payment it may still land; /billing shows the bank"),void e.render()):(d=setTimeout(u,o.TOPUP_POLL_MS),void(d&&"function"==typeof d.unref&&d.unref()))};return d=setTimeout(u,o.TOPUP_POLL_MS),d&&"function"==typeof d.unref&&d.unref(),!0}},{name:"cloud",args:["sub","value"],hint:"[status|key <api_key>|activate|deactivate|memory [on|off]|sync [on|off|now]]",category:"support",desc:"Show and control ÆGIS cloud sync",handler:async(e,t)=>{const n=(t.sub||"").toLowerCase(),o=(t.value||t._rest||"").trim();if("key"===n)return await applyAccountKey(e,o),e.render(),!0;if("activate"===n){if(!e.client.apiKey)return note(e,`no key — ${credentials.HOW_TO_SET}`),e.render(),!0;try{const t=await e.withWorking((()=>e.client.memoryActivate())),n=await e.client.getMemoryToken();n&&credentials.saveMemoryToken(n,{memorySubscribed:!0}),done(e,t&&!1===t.ok?"the server refused activation":"cloud memory activated for this account"),t&&t.token_limit&¬e(e,`quota: ${t.tokens_used||0} / ${t.token_limit} synced tokens`)}catch(t){note(e,`activation failed: ${t.message}`)}return e.render(),!0}if("deactivate"===n)return credentials.clearMemoryToken(),e.client.setApiKey(e.client.apiKey),note(e,"cloud memory token cleared locally — sync stops until /cloud activate re-issues one"),note(e,"the account itself is still subscribed; manage the subscription here:"),note(e,goUrl("upgrade","cloud_deactivate")),e.render(),!0;if("memory"===n||"persist"===n||"memory-persist"===n){const t=(o||"status").toLowerCase();if("on"===t||"off"===t){const n="on"===t;return setMemoryGate(e,n),n?(done(e,"persisting memory on — sessions are stored to your account so an interrupted turn can be resumed"),note(e,"/cloud memory shows the quota; past the plan’s ceiling reads keep working and only new writes pause")):(note(e,"persisting memory off — nothing new is stored"),note(e,"everything already in the cloud stays readable (/aegis-recall <topic>), and /sync now still pushes once by hand")),e.render(),!0}return panel(e,memoryStatusLines(e)),e.render(),!0}if("sync"===n||"push"===n||"pull"===n){const t="sync"===n?(o||"status").toLowerCase():n;if("on"===t||"off"===t){const n="on"===t;return setMemoryGate(e,n),note(e,n?'persisting memory on — sessions are stored after each turn (this is the old "cloud sync")':"persisting memory off — nothing new is stored; /sync now still runs a manual pass"),e.render(),!0}if("now"===t)return await runCloudSync(e),e.render(),!0;const r=cloudsync.status();panel(e,[...memoryStatusLines(e),[span(C.gray,"")],[span(C.white+BOLD,"Sync ledger"),span(BOLD_OFF,"")],[span(C.gray,` local sessions: ${r.local} · pending push: ${r.pending} · in sync: ${r.synced}`)],[span(C.gray,` last push: ${r.lastPushAt?new Date(r.lastPushAt).toLocaleString():"never"} · last pull: ${r.lastPullAt?new Date(r.lastPullAt).toLocaleString():"never"}`)],[span(C.gray,` state: ${r.path}`)]]);for(const t of r.errors.slice(0,3))panel(e,[[span(C.coral,` ⚠ ${t.error}`)]]);return e.render(),!0}const r=cloudsync.status();return panel(e,[...keyPanelLines(e,"AEGIS cloud"),[span(C.gray,"")],...memoryStatusLines(e),[span(C.gray,"")],[span(C.white+BOLD," Sync"),span(BOLD_OFF,"")],[span(C.gray,` ${r.pending} pending · ${r.synced} in sync · ${r.importedRemote} pulled from cloud`)],[span(C.gray," /cloud memory on | off · /cloud sync on | off · /sync now")]]),e.render(),!0}},{name:"key",aliases:["apikey","api-key"],args:["value"],hint:"[<api_key>|status|clear|register]",category:"auth",desc:"Save or show the AEGIS account key",handler:async(e,t)=>{const n=String(t.value||t._rest||"").trim(),o=n.toLowerCase();if("status"===o)return panel(e,keyPanelLines(e)),e.render(),!0;if("register"===o){const t=await e.registerAccount();return t.alreadyKeyed?note(e,"this machine already has an AEGIS key — /key status shows it. Re-registering cannot mint a new welcome trial: that is granted once per machine, ever. For a fresh trial, sign up at aegiscloud.org; to point this session at a different key, /key clear first."):t.key&&t.ok?done(e,"AEGIS account key provisioned and saved"):t.key?note(e,"the account was created but its key could not be saved — run /key <api_key> with the key from aegiscloud.org"):note(e,`could not register this machine: ${t.error?t.error.message:"the server returned no account key"}`),e.render(),!0}if("clear"===o||"remove"===o||"rm"===o){const t=e.forgetApiKey();return done(e,t.cleared?`key removed from ${t.path}`:"there was no saved key to remove"),credentials.legacyKeyOnDisk()&¬e(e,`a copy is still in ${configPath()} (written by another AEGIS CLI) — delete the "aegiscloud" block to finish the job`),e.render(),!0}return await applyAccountKey(e,n),e.render(),!0}},{name:"sync",aliases:["cloudsync","cloud-sync"],args:["mode"],hint:"[now|on|off|status]",category:"data",desc:"Store sessions in AEGIS Cloud (cross-session memory)",hidden:e=>!cloudReady(),handler:async(e,t)=>{const n=(t.mode||"").toLowerCase();if("on"===n||"off"===n)return setMemoryGate(e,"on"===n),note(e,"on"===n?"persisting memory on — sessions are stored so an interrupted turn can be resumed":"persisting memory off — nothing new is stored; /sync now still runs a manual pass"),e.render(),!0;if("status"===n){const t=cloudsync.status(),n=memoryStatusLines(e);return n.push([span(C.gray,"")]),n.push([span(C.gray,` local ${t.local} · pending ${t.pending} · in sync ${t.synced}`)]),panel(e,n),e.render(),!0}return await runCloudSync(e),e.render(),!0}},{name:"drive",aliases:["gdrive","google-drive"],args:["mode"],hint:"[status|connect]",category:"data",desc:"Connect Google Drive as a memory store, alongside AEGIS Cloud",handler:async(e,t)=>{const n=String(t&&t.mode||"").toLowerCase();if(!e.client)return note(e,"Google Drive needs an AEGIS account — this client has none."),e.render(),!0;if("function"!=typeof e.client.driveToken)return note(e,"Google Drive is not reachable from this client — it needs an AEGIS API key and a build with drive-connect support."),e.render(),!0;const o=require(resolveShared(path.join("client","drive-connect.js"))),r=async()=>{const t=await o.driveStatus(e.client),n=[];return n.push([span(C.gray," Google Drive — memory you can hold yourself")]),n.push([span(t.connected?C.green:C.gray,` ${t.connected?"connected":"not connected"}${t.email&&t.connected?` as ${t.email}`:""}`)]),t.connected||(n.push([span(C.gray,` connect: /drive connect (opens ${o.driveConnectUrl(e.client.apiBase)})`)]),t.googleLinkedKnown&&!t.googleLinked&&n.push([span(C.gold," this account has no Google identity yet — sign in with Google first, or the consent screen will attach Drive elsewhere")])),panel(e,n),t};if(!n||"status"===n)return await r(),e.render(),!0;if("connect"===n){const t=await o.driveStatus(e.client);if(t.connected)return note(e,`Google Drive is already connected${t.email?` as ${t.email}`:""}.`),await r(),e.render(),!0;const n=o.driveConnectUrl(e.client.apiBase),s=openUrl(n);note(e,s?`Opening Google's consent screen — finish it in the browser: ${n}`:`Open this in a browser: ${n}`),note(e,"Waiting for the account to report connected (3 minutes)…"),e.render();try{const t=await o.waitForDriveConnected(e.client,{timeoutMs:18e4,pollMs:2e3});note(e,`Google Drive connected${t.email?` as ${t.email}`:""} — /sync now stores sessions in AEGIS Cloud, Drive is the alternative store.`)}catch(t){note(e,t&&"AbortError"===t.name?"cancelled — nothing was changed.":`not connected: ${t&&t.message||t}. If you finished the consent screen, check that the browser's Google account is the one this AEGIS account was linked to.`)}return e.render(),!0}return note(e,"Usage: /drive [status|connect] — status is the default."),e.render(),!0}},{name:"gmail",hint:"",category:"support",desc:"Link Gmail to conversations",handler:async e=>(note(e,"Gmail integration needs Google OAuth — not available in this build. Use /export to save conversations to files instead."),e.render(),!0)},{name:"clone",aliases:["fetch-site","websnap"],args:["url"],hint:"<url>",category:"workspace",desc:"Clone a website into a local project",handler:async(e,t)=>{const n=(t._rest||t.url||"").trim();return n?(note(e,`/clone needs a web-fetch tool and a chat service — not available in this build. Use /init to scaffold a fresh project instead of ${n}.`),e.render(),!0):(note(e,"Usage: /clone <url>"),e.render(),!0)}},{name:"release-notes",hint:"",category:"support",desc:"What's new",handler:async e=>(panel(e,panels.buildReleaseNotes(e.state(),e.ctx)),e.render(),!0)},{name:"aegis-status",hint:"",category:"aegis",desc:"Show account status — API key, plan, account and cloud memory",tool:"aegis_status",build:()=>({})},{name:"aegis-ask",aliases:["ask"],args:["question"],hint:"<question>",category:"aegis",desc:"Ask ÆGIS pooled inference a question (auto-routed)",tool:"aegis_ask",build:e=>({prompt:e})},{name:"aegis-recall",aliases:["recall"],args:["topic"],hint:"<topic>",category:"aegis",desc:"Recall cross-session memory about a topic (cloud)",tool:"aegis_memory_search",build:e=>({query:e})},{name:"aegis-remember",aliases:["remember"],args:["note"],hint:"<note>",category:"aegis",desc:"Save a note or decision to cross-session memory",tool:"aegis_memory_save",build:e=>({content:e})},{name:"aegis-council",aliases:["council"],args:["question"],hint:"<question>",category:"aegis",desc:"Put a question to the ÆGIS council (multi-perspective deliberation)",hidden:()=>!cloudReady(),handler:async(e,t)=>{const n=(t._rest||t.question||"").trim();if(!n)return note(e,"Usage: /aegis-council <question>"),e.render(),!0;const o=composeResearchPrompt(`Deliberate as a council and vote on: ${n}`,process.cwd());return e.runPrompt?(await e.runPrompt(o),!0):(note(e,`Composed council prompt (${o.length} chars) — run in the TUI to send it.`),e.render(),!0)}},{name:"aegis-print",args:["question"],hint:"<question>",category:"aegis",desc:"Ask pooled inference and print the answer cleanly",hidden:()=>!cloudReady(),handler:async(e,t)=>{const n=(t._rest||t.question||"").trim();if(!n)return note(e,"Usage: /aegis-print <question>"),e.render(),!0;const o=await e.ask(n);return panel(e,panels.buildAegisPrint("ÆGIS",{result:o.text,model:o.model,provider:"aegis"},e.ctx)),e.render(),!0}},{name:"aegis-multi",args:["task","mode"],hint:"<task> [run]",category:"aegis",desc:'Compose an ÆGIS /multi multi-agent task (add "run" to execute)',hidden:()=>!cloudReady(),handler:async(e,t)=>{let n=(t._rest||t.task||"").trim(),o=(t.mode||"").toLowerCase();return"run"!==o&&/\s+run$/i.test(n)&&(o="run",n=n.replace(/\s+run$/i,"").trim()),n?"run"!==o?(panel(e,panels.buildAegisMulti(n,e.ctx)),e.render(),!0):runMultiCommand(e,n):(note(e,"Usage: /aegis-multi <task> [run]"),e.render(),!0)}},{name:"byok",hint:"",category:"auth",desc:"List every provider you can bring your own key for, and which are set",handler:async e=>{const t=await byokCatalog(e.client);if(!t)return await e.runTool("aegis_byok_status",{}),!0;const n=t.filter((e=>e.configured)).length,o=[[span(C.gold+BOLD,"Bring your own key"),span(BOLD_OFF,"")],[span(C.gray,"─".repeat(34))],[span(n?C.green:C.gray,` ${n} of ${t.length} providers set`),span(C.gray," — /byok-list picks one, or /byok-key <provider>")],"",...byokProviderLines(t)];return panel(e,o),e.render(),!0}},{name:"byok-set",args:["provider"],hint:"<provider>",category:"auth",desc:"Store your provider key on your AEGIS ACCOUNT (pooled route) — for the byok class use /byok-key",tool:"aegis_byok_set",secret:"key",build:e=>({provider:String(e||"").trim()}),async secretDescribe(e,t){const n=String(e.provider||"").trim(),o=await byokCatalog(t);if(!o)return n?null:{note:"Usage: /byok-set <provider> — /byok lists them.",prompt:"provider key: "};const r=findByokProvider(o,n);if(r.ambiguous)return{note:`"${n}" matches ${r.ambiguous.join(", ")} — retype the exact id. Nothing was sent.`,prompt:null};const s=r.provider;if(!s)return{note:`unknown provider "${n}". Known ids: ${o.map((e=>e.id)).join(", ")}`,prompt:null};if(s.configured)return{note:`${s.id} already has a key${s.masked?` (${s.masked})`:""} — pasting a new one replaces it.`,prompt:`new ${s.label||s.id} key: `,provider:s.id};const a=[`${s.label||s.id}`],i=(s.models||[]).map((e=>"string"==typeof e?e:e&&e.id)).filter(Boolean);return i.length&&a.push(`unlocks ${i.join(", ")}`),s.key_prefix&&a.push(`key starts with ${s.key_prefix}`),s.key_url&&a.push(`create one at ${s.key_url}`),{note:a.join(" · "),prompt:`${s.id} key: `,provider:s.id}}},{name:"byok-rm",args:["provider"],hint:"<provider>",category:"auth",desc:"Remove a stored provider key",tool:"aegis_byok_set",build:e=>({provider:String(e||"").trim()})},{name:"class",args:["class","mode"],hint:"[aegis|byok|local|pro [on|off]]",category:"model",desc:'Show or switch which class turns run on; pro (your Claude subscription) needs a one-time "on"',handler:async(e,t)=>{const n=t||{},o=e.ctx&&e.ctx.modelClass||"aegis",r=t=>e.classLabel?e.classLabel(t):t,s=String(n.class||"").trim().toLowerCase();if("pro"===s&&n.mode){const t=String(n.mode).trim().toLowerCase();if("on"!==t&&"off"!==t)return e.push({role:"error",text:`usage: /class pro [on|off] — got "${n.mode}"`}),!0;const s="on"===t;if(e.saveConfig({proEnabled:s}),e.push({role:s?"done":"note",text:s?"pro class enabled — /class pro switches to your Claude Code subscription. It runs only if that subscription has Claude Code access.":"pro class disabled — it is no longer offered by /class or the model picker."}),!s&&"pro"===o){const t=e.switchClass("aegis");t.ok&&e.push({role:"note",text:`class: ${t.class} — ${r(t.class)}`})}return!0}if(!s){const t=await Promise.resolve(e.classes?e.classes():[]).catch((()=>[])),n=t.length?t:[{class:"aegis"},{class:"byok"}],r=n.findIndex((e=>e.class===o));return e.openOverlay({type:"class",items:n,sel:r<0?0:r,current:o}),!0}const a=e.switchClass(s);if(!a.ok)return e.push({role:"error",text:a.error}),!0;if(e.push({role:"done",text:`class: ${a.class} — ${r(a.class)}`}),a.cleared&&e.push({role:"note",text:`cleared the pin "${a.cleared}" — it does not belong to this class. /models lists what fits.`}),!("byok"!==a.class||e.ctx&&e.ctx.model)){const t=(await e.listModelsFor("byok")||[]).filter((e=>!e.cls||"byok"===e.cls)),n=t.find((e=>e.configured))||t[0];n?(e.ctx.model=n.id,e.saveConfig({model:n.id,currentModelId:n.id}),e.push({role:"note",text:n.configured?`using ${n.id} — /models lists the rest.`:`using ${n.id}, but no ${n.provider} key is saved yet — /byok-key ${n.provider}.`})):0===t.length&&e.push({role:"note",text:"nothing to relay yet — save a provider key with /byok-key <provider>, then /models."})}return!0}},{name:"models",aliases:["model-list"],hint:"",category:"model",desc:"Pick a model to pin, for the class you are on — opens the same picker as /model",handler:async e=>{const t=e.ctx&&e.ctx.modelClass||"aegis",n=await e.listModelsFor(t)||[];if(!n.length)return note(e,"byok"===t?"nothing to relay yet — save a provider key with /byok-key <provider>":"no models advertised — check the account with /status, then retry"),e.render(),!0;const o=e.ctx&&e.ctx.model,r=n.map((e=>e.cls&&e.cls!==t?{...e,note:`${e.note||e.label||""} · pooled lane — /class ${e.cls}`}:e)),s=r.findIndex((e=>e.id===o));return e.openOverlay({type:"model",items:r,sel:s<0?0:s,current:o,cls:t}),!0}},{name:"byok-list",aliases:["byok-pick"],hint:"",category:"auth",desc:"Pick a provider to set a key for, then its models appear in /model",handler:async e=>{const t=await byokCatalog(e.client);if(!t||!t.length)return e.push({role:"error",text:"Could not read the provider catalog (offline, or no AEGIS key) — /byok lists what is known."}),!0;if("function"!=typeof e.openOverlay)return e.push({role:"note",text:"/byok-key <provider> — /byok lists the providers."}),!0;const n=(t.find((e=>e.configured))||{}).id||null,o=Math.max(0,t.findIndex((e=>e.configured)));return e.openOverlay({type:"provider",command:"byok-key",items:t,sel:o,current:n,hint:"↑↓ or tab move · enter picks · the key is stored on this machine"}),!0}},{name:"byok-key",args:["provider"],hint:"<provider> [key]",category:"auth",desc:"Save YOUR provider key on THIS MACHINE — the key the byok class sends",handler:async(e,t)=>{const n=t||{},o=String(n.provider||"").trim().toLowerCase();if(!o){const t=await byokCatalog(e.client);if(!t||!t.length)return e.push({role:"error",text:"Usage: /byok-key <provider> — /byok lists the providers."}),!0;if("function"!=typeof e.openOverlay)return e.push({role:"error",text:"Usage: /byok-key <provider> — /byok lists the providers."}),!0;const n=(t.find((e=>e.configured))||{}).id||null,o=Math.max(0,t.findIndex((e=>e.configured)));return e.openOverlay({type:"provider",command:"byok-key",items:t,sel:o,current:n,hint:"↑↓ or tab move · enter picks · the key is stored on this machine"}),!0}const r=e.settings&&e.settings();if(!r||"function"!=typeof r.set)return e.push({role:"error",text:"this client has no provider-key store."}),!0;const s=await byokCatalog(e.client),a=s?findByokProvider(s,o):null;if(a&&a.ambiguous)return e.push({role:"error",text:`"${o}" matches ${a.ambiguous.join(", ")} — retype the exact id.`}),!0;if(s&&!a?.provider){const t=s.map((e=>e.id)).join(", ");return e.push({role:"error",text:`unknown provider "${o}". Known ids: ${t} — nothing was saved.`}),!0}const i=a&&a.provider,d=i&&i.id||o,l=String(n._rest||"").trim(),c=l.indexOf(" ");let u=-1===c?"":l.slice(c+1).trim();if(u||(i&&i.key_url&&e.push({role:"note",text:`create a ${i.label||d} key at ${i.key_url}`}),u=String(await e.readSecret(`${d} key: `)||"").trim()),!u)return e.push({role:"note",text:"nothing saved."}),!0;if(i&&i.key_prefix&&!u.startsWith(i.key_prefix)&&e.push({role:"note",text:`heads up: ${d} keys normally start with "${i.key_prefix}" — saved anyway.`}),"custom"===d&&!savedByokBaseURL(e,d))return e.push({role:"error",text:`the "custom" provider needs an endpoint as well as a key — a key alone dials nothing. Use: /model-add custom <https-base-url> ${u} <model-id> (saves endpoint, key and model together) — nothing was saved.`}),!0;r.set(e.byokNamespace(d),{key:u});let p="";try{const{envVarFor:t,setEnvValue:n}=require(resolveShared(path.join("client","env-file.js"))),o=t(d);if(o){const t=n(o,u);t.ok?p=o:e.push({role:"note",text:`heads up: could not write ${o} to ~/.aegiscode/.env (${t.error}).`})}}catch{}let h=[];if("function"==typeof e.refreshByokModels)try{h=await e.refreshByokModels()||[]}catch{h=[]}if(!h.length&&"function"==typeof e.listModelsFor)try{h=(await e.listModelsFor("byok")||[]).filter((e=>!e.cls||"byok"===e.cls))}catch{h=[]}const m=h.filter((e=>e&&(e.provider===d||String(e.id||"").startsWith(`${d}:`)))),g=e.ctx&&e.ctx.modelClass||"aegis";let y="byok"===g;if(!y&&"aegis"===g&&"function"==typeof e.switchClass){const t=e.switchClass("byok");t&&t.ok&&(y=!0,e.push({role:"note",text:`class: byok — ${e.classLabel?e.classLabel("byok"):"your own key"}`}))}y||"aegis"===g||e.push({role:"note",text:`staying on class: ${g} — the ${d} key is saved, and /class byok spends it.`});const f=y&&m.length?String(m[0].id):"";return f&&e.ctx&&(e.ctx.model=f,e.saveConfig({model:f,currentModelId:f,modelClass:"byok"})),e.push({role:"done",text:f?`saved a ${d} key on this machine${p?` (${p} in ~/.aegiscode/.env, so it is there next time)`:""} — model ${f} pinned, /model lists the rest.`:y||"aegis"===g?`saved a ${d} key on this machine${p?` (${p} in ~/.aegiscode/.env, so it is there next time)`:""} — /models lists its models, /class byok runs on it.`:`saved a ${d} key on this machine${p?` (${p} in ~/.aegiscode/.env, so it is there next time)`:""} — class is still ${g}; /class byok switches to it whenever you want.`}),!0}},{name:"byok-rm-key",args:["provider"],hint:"<provider>",category:"auth",desc:"Forget the provider key saved on this machine",handler:async(e,t)=>{const n=String((t||{}).provider||"").trim().toLowerCase();if(!n)return e.push({role:"error",text:"Usage: /byok-rm-key <provider> — /byok lists the providers."}),!0;const o=e.settings&&e.settings();if(!o||"function"!=typeof o.remove)return e.push({role:"error",text:"this client has no provider-key store."}),!0;const r=e.byokNamespace(n),s="function"==typeof o.rawKey?o.rawKey(r):null;return o.remove(r),e.push({role:s?"done":"note",text:s?`removed the ${n} key from this machine.`:`no ${n} key was saved on this machine.`}),!0}},{name:"model-add",aliases:["add-model"],args:["provider"],hint:"<provider> [api-key] [model-id|*] (custom: <base-url> <api-key> [model-id|*])",category:"model",desc:"Save a provider key and offer a model id in one step (asks the vendor when it can)",handler:async(e,t)=>{const n=t||{},o=String(n.provider||"").trim();if(!o)return e.push({role:"error",text:"Usage: /model-add <provider> [api-key] <model-id> — /byok lists the providers. A vendor this catalog does not name yet: /model-add custom <https-base-url> <api-key> <model-id>. Example: /model-add deepseek sk-xxxxxxxx deepseek-v4.3-preview"}),!0;const r=splitCommandWords(String(n._rest||"").trim());let s=r.length&&r[0].toLowerCase()===o.toLowerCase()?r.slice(1):r;const a=await byokCatalog(e.client),i=a?findByokProvider(a,o):null;if(i&&i.ambiguous)return e.push({role:"error",text:`"${o}" matches ${i.ambiguous.join(", ")} — retype the exact id.`}),!0;if(a&&(!i||!i.provider))return e.push({role:"error",text:`no provider "${o}" in the relay's catalog — /byok lists the ones it takes a key for.`}),!0;const d=i&&i.provider&&i.provider.id||o.toLowerCase();let l="",c="";if("custom"===d){if(1===s.length&&!savedByokBaseURL(e,d))return e.push({role:"error",text:"one word cannot say whether it is the URL or the model id — nothing was saved. Type the endpoint first: /model-add custom <https-base-url> <api-key> [model-id]"}),!0;s.length>=2&&(l=s.shift(),c=s.shift())}else s.length>=2&&(c=s.shift());let u=s.join(" ").trim();if(c){const t=e.settings&&e.settings();if(!t||"function"!=typeof t.set)return e.push({role:"error",text:"this client has no provider-key store."}),!0;const n=i&&i.provider;n&&n.key_prefix&&!c.startsWith(n.key_prefix)&&e.push({role:"note",text:`heads up: ${d} keys normally start with "${n.key_prefix}" — saved anyway.`}),l&&!/^https:\/\//i.test(l)&&e.push({role:"note",text:"heads up: aegis1 only dials an https:// base_url — saved anyway, but calls on it will be refused."}),t.set(e.byokNamespace(d),{key:c,...l?{baseURL:l}:{}});try{const{envVarFor:t,setEnvValue:n}=require(resolveShared(path.join("client","env-file.js"))),o=t(d);if(o){const t=n(o,c);t.ok||e.push({role:"note",text:`heads up: could not mirror the key into ~/.aegiscode/.env (${t.error}).`})}}catch{}e.push({role:"done",text:l?`saved a ${d} key and base URL (${l}) on this machine.`:`saved a ${d} key on this machine.`})}const p=byokKeyForProvider(e,d),h=await offeredModelIds(e,d,p);if("*"===u){if(!h){const t=await discoverProviderModels(e,d,p);return e.push({role:"error",text:`cannot list ${d}: ${t&&t.error||"no list available"} — type the ids instead: /model-add ${d} <model-id>`}),!0}const t=addManyUserModels(d,h);if("function"==typeof e.refreshByokModels)try{await e.refreshByokModels()}catch{}return e.push({role:"done",text:`added ${t.added} of the ${h.length} model ids ${d} serves${t.already.length?` (${t.already.length} were already declared)`:""}.`}),t.capped&&e.push({role:"note",text:`stopped at the store's per-provider cap (32) — ${t.capped} more id(s) were left out; /model-add ${d} <model-id> stores a specific one, /model-rm frees a slot.`}),t.failed.length&&e.push({role:"note",text:`${t.failed.length} id(s) were refused: ${t.failed.map((e=>e.id)).join(", ")}`}),e.push({role:"note",text:`stored in ${userModelsPath()} — the desktop reads the same file. /model-discover ${d} lists what the vendor serves.`}),!0}if(!u){h&&e.push({role:"note",text:`${d} serves ${h.length} model ids — ${h.slice(0,12).join(", ")}${h.length>12?", …":""}`});const t=String(await e.askInput(h?`model id for ${d} (1-${h.length}, or type one): `:`model id for ${d}: `)||"").trim(),n=h&&/^\d+$/.test(t)?Number(t):0;u=h&&n>=1&&n<=h.length?h[n-1]:t}if(!u)return e.push({role:"note",text:"nothing saved."}),!0;let m;try{m=addUserModel(d,u)}catch(t){return e.push({role:"error",text:t&&t.message||String(t)}),!0}if("function"==typeof e.refreshByokModels)try{await e.refreshByokModels()}catch{}const g=(("function"==typeof e.listModelsFor?await e.listModelsFor("byok"):[])||[]).find((e=>e&&e.id===`${d}:${u}`));return e.push({role:m.added?"done":"note",text:m.added?`added ${d}:${u} — offered on this machine now, in the CLI and the desktop.`:`${d}:${u} was already declared.`}),a||e.push({role:"note",text:`the relay's catalog could not be read, so "${d}" is unverified — if it does not appear in /models, /byok lists the provider ids it takes.`}),m.added&&!g&&e.push({role:"note",text:`saved, but no row will be offered for "${d}" yet — the relay lists no provider of that id (or that provider lists no models).`}),m.added&&h&&e.push({role:"note",text:`${d} currently serves ${h.length} model ids — /model-discover ${d} lists them, /model-add ${d} '*' takes them all.`}),e.push({role:"note",text:`stored in ${m.file} — the desktop reads the same file.`}),!0}},{name:"model-discover",aliases:["discover-models","vendor-models"],args:["provider"],hint:"<provider>",category:"model",desc:"List the model ids your provider's own API serves",handler:async(e,t)=>{const n=String((t||{}).provider||"").trim();if(!n)return e.push({role:"error",text:`Usage: /model-discover <provider> — this client can ask: ${discoverableProviders().join(", ")}`}),!0;const o=await byokCatalog(e.client),r=o?findByokProvider(o,n):null,s=(r&&r.provider&&r.provider.id||n).toLowerCase(),a=vendorEndpointFor(s);if(!a)return e.push({role:"error",text:`no list endpoint for "${s}" in this client — /model-add ${s} <model-id> stores an id you already know. Providers it can ask: ${discoverableProviders().join(", ")}`}),!0;const i=byokKeyForProvider(e,s);if(!i)return e.push({role:"error",text:`no ${s} key on this machine — /byok-key ${s} saves one (or put it in ~/.aegiscode/.env), then this lists what the key reaches.`}),!0;const d=await discoverProviderModels(e,s,i);if(!d||!d.ok)return e.push({role:"error",text:`could not list ${s}: ${d&&d.error||"no answer"}`}),!0;const l=new Set(userModelIdsFor(s)),c=new Set((r&&r.provider&&r.provider.models||[]).map((e=>String(e))));e.push({role:"note",text:`${s} at ${a.url}${a.note?` (${a.note})`:""}`}),e.push({role:"note",text:`${d.count} chat model id(s) the vendor serves — mark: [seen] the relay already lists it, [your] you declared it, [new] this machine does not offer it yet.`});const u=d.ids.map(((e,t)=>{const n=l.has(e)?"[your]":c.has(e)?"[seen]":"[new]";return`${String(t+1).padStart(3)}. ${n} ${e}`}));u.length&&e.push({role:"panel",lines:u}),u.length||e.push({role:"note",text:`the vendor answered with no chat models — /model-add ${s} <model-id> stores one by hand.`}),d.others.length&&e.push({role:"note",text:`${d.others.length} id(s) are not chat models (embeddings, audio, moderation or an unsupported method) and are left out: ${d.others.slice(0,8).join(", ")}${d.others.length>8?", …":""}`});const p=d.ids.filter((e=>!l.has(e)&&!c.has(e)));return p.length&&e.push({role:"note",text:`${p.length} of them are not offered on this machine yet — /model-add ${s} '<model-id>' stores one, /model-add ${s} '*' stores every chat model the vendor serves.`}),!0}},{name:"model-rm",aliases:["rm-model"],args:["provider"],hint:"<provider> <model-id>",category:"model",desc:"Forget a model id you added with /model-add",handler:async(e,t)=>{const n=t||{},o=String(n.provider||"").trim(),r=String(n._rest||"").trim(),s=r.indexOf(" "),a=-1===s?"":r.slice(s+1).trim();if(!o||!a)return e.push({role:"error",text:"Usage: /model-rm <provider> <model-id> — /model-add lists what you added."}),!0;let i;try{i=removeUserModel(o,a)}catch(t){return e.push({role:"error",text:t&&t.message||String(t)}),!0}if("function"==typeof e.refreshByokModels)try{await e.refreshByokModels()}catch{}return e.push({role:i.removed?"done":"note",text:i.removed?`removed ${i.provider}:${i.model} — the picker stops offering it on the next refresh.`:`${i.provider}:${i.model} was not declared on this machine.`}),!0}},{name:"tool",args:["name","json"],hint:"<name> [json]",category:"aegis",desc:"Call any registry tool directly (escape hatch for new tools)",generic:!0,build:e=>{const t=String(e||""),n=t.indexOf(" "),o=(-1===n?t:t.slice(0,n)).trim(),r=-1===n?"":t.slice(n+1).trim();let s={};if(r)try{s=JSON.parse(r)}catch(e){throw new Error(`/tool: arguments must be JSON — ${e.message}`)}return{tool:o,args:s}}},{name:"aegis-import",aliases:["import"],hint:"[--confirm]",category:"aegis",desc:"Import memory from other AI tools on this machine (dry run unless --confirm)",tool:"aegis_memory_import",build:e=>({confirm:/--confirm\b/.test(String(e||""))})}],BY_NAME=new Map;for(const e of COMMANDS)for(const t of[e.name,...e.aliases||[]]){if(BY_NAME.has(t))throw new Error(`aegiscode: command name or alias /${t} is registered twice`);BY_NAME.set(t,e)}function allCommands(){return COMMANDS.map((e=>({...e,categoryLabel:categoryLabel(e.category)})))}function visibleCommands(){return allCommands().filter((e=>!("function"==typeof e.hidden?e.hidden():e.hidden)))}function findCommand(e){return BY_NAME.get(String(e||"").toLowerCase())||null}function canonicalName(e){const t=findCommand(e);return t?t.name:e}function parseLine(e){const t=String(null==e?"":e).trim();if(!t)return{kind:"empty"};if("/"!==t[0])return{kind:"prompt",text:t};const n=t.indexOf(" "),o=(-1===n?t.slice(1):t.slice(1,n)).trim(),r=-1===n?"":t.slice(n+1).trim(),s=findCommand(o);return s?s.unavailable?{kind:"unavailable",command:s,arg:r}:{kind:"command",command:s,arg:r}:{kind:"unknown",name:o,text:t}}function toolBackedCommands(){return COMMANDS.filter((e=>e.tool))}module.exports={CATEGORIES:CATEGORIES,categoryLabel:categoryLabel,EFFORT_LEVELS:EFFORT_LEVELS,COMMANDS:COMMANDS,allCommands:allCommands,visibleCommands:visibleCommands,findCommand:findCommand,canonicalName:canonicalName,parseLine:parseLine,toolBackedCommands:toolBackedCommands,backfillSessionNames:backfillSessionNames};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const fs=require("node:fs"),path=require("node:path"),DIFF_LIMITS={fileBytes:262144,lcsCells:25e4,rows:400,context:3};function splitLines(t){const e=String(null==t?"":t).replace(/\r\n?/g,"\n");if(""===e)return[];const n=e.split("\n");return n.length&&""===n[n.length-1]&&n.pop(),n}function lineDiff(t,e){const n=splitLines(t),s=splitLines(e);let i=0;for(;i<n.length&&i<s.length&&n[i]===s[i];)i++;let r=0;for(;r<n.length-i&&r<s.length-i&&n[n.length-1-r]===s[s.length-1-r];)r++;const l=n.slice(i,n.length-r),o=s.slice(i,s.length-r),a=lcsOps(l,o),c=null===a,g=a||[...l.map((t=>({sign:"-",text:t}))),...o.map((t=>({sign:"+",text:t})))];if(!g.some((t=>" "!==t.sign)))return{rows:[],adds:0,dels:0,truncated:c};const u=DIFF_LIMITS.context,p=[];let
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),DIFF_LIMITS={fileBytes:262144,lcsCells:25e4,rows:400,context:3};function splitLines(t){const e=String(null==t?"":t).replace(/\r\n?/g,"\n");if(""===e)return[];const n=e.split("\n");return n.length&&""===n[n.length-1]&&n.pop(),n}function lineDiff(t,e){const n=splitLines(t),s=splitLines(e);let i=0;for(;i<n.length&&i<s.length&&n[i]===s[i];)i++;let r=0;for(;r<n.length-i&&r<s.length-i&&n[n.length-1-r]===s[s.length-1-r];)r++;const l=n.slice(i,n.length-r),o=s.slice(i,s.length-r),a=lcsOps(l,o),c=null===a,g=a||[...l.map((t=>({sign:"-",text:t}))),...o.map((t=>({sign:"+",text:t})))];if(!g.some((t=>" "!==t.sign)))return{rows:[],adds:0,dels:0,truncated:c};const u=DIFF_LIMITS.context,p=[];let d=1,f=1;const h=i>u?i-u:0,x=h;x>0&&p.push({sign:" ",text:"",marker:!0,note:`… ${x} unchanged line${1===x?"":"s"}`});for(let t=h;t<i;t++)p.push({sign:" ",text:n[t],no:f}),f++,d++;for(const t of g)" "===t.sign?(p.push({sign:" ",text:t.text,no:f}),f++,d++):"-"===t.sign?(p.push({sign:"-",text:t.text,no:d}),d++):(p.push({sign:"+",text:t.text,no:f}),f++);const m=s.length-r,I=Math.min(r,u);f=m+1;for(let t=0;t<I;t++)p.push({sign:" ",text:s[m+t],no:f}),f++,d++;if(r>u){const t=r-u;p.push({sign:" ",text:"",marker:!0,note:`… ${t} unchanged line${1===t?"":"s"}`})}const _=p.filter((t=>"+"===t.sign)).length,w=p.filter((t=>"-"===t.sign)).length;let F=p,y=!1;return F.length>DIFF_LIMITS.rows&&(F=F.slice(0,DIFF_LIMITS.rows),F.push({sign:" ",text:"",marker:!0,note:`… ${p.length-DIFF_LIMITS.rows} more diff lines`}),y=!0),{rows:F,adds:_,dels:w,truncated:c||y}}function lcsOps(t,e){const n=t.length,s=e.length;if(!n||!s)return[...t.map((t=>({sign:"-",text:t}))),...e.map((t=>({sign:"+",text:t})))];if(n*s>DIFF_LIMITS.lcsCells)return null;const i=s+1,r=new Int32Array((n+1)*i);for(let l=n-1;l>=0;l--)for(let n=s-1;n>=0;n--)r[l*i+n]=t[l]===e[n]?r[(l+1)*i+(n+1)]+1:Math.max(r[(l+1)*i+n],r[l*i+(n+1)]);const l=[];let o=0,a=0;for(;o<n&&a<s;)t[o]===e[a]?(l.push({sign:" ",text:t[o]}),o++,a++):r[(o+1)*i+a]>=r[o*i+(a+1)]?(l.push({sign:"-",text:t[o]}),o++):(l.push({sign:"+",text:e[a]}),a++);for(;o<n;)l.push({sign:"-",text:t[o++]});for(;a<s;)l.push({sign:"+",text:e[a++]});return l}function fileRows(t){const e=splitLines(t),n=e.slice(0,DIFF_LIMITS.rows),s=n.map(((t,e)=>({sign:" ",text:t,no:e+1}))),i=e.length-n.length;return i>0&&s.push({sign:" ",text:"",marker:!0,note:`… ${i} more lines`}),{rows:s,adds:0,dels:0,truncated:i>0}}function readCapped(t,e={}){const n=null==e.bytes?DIFF_LIMITS.fileBytes:e.bytes;try{const e=fs.statSync(t);if(!e.isFile())return{text:null,missing:!0};const s=fs.readFileSync(t,"utf8");return e.size>n?{text:s.slice(0,n),missing:!1,truncated:!0}:{text:s,missing:!1}}catch{return{text:null,missing:!0}}}function shortPath(t,e){const n=String(t||"");if(!e)return n;const s=path.relative(e,n);if(s&&!s.startsWith("..")&&!path.isAbsolute(s))return s;const i=n.split(path.sep).filter(Boolean),r=n.startsWith(path.sep)?path.sep:"";return i.length>2?r+"…"+path.sep+i.slice(-2).join(path.sep):n}function editPreview(t,e,n={}){try{const s=null==n.cwd?process.cwd():n.cwd,i=n.readFile||readCapped;if(!e||"object"!=typeof e)return null;const r="string"==typeof e.file_path?e.file_path:"string"==typeof e.path?e.path:null;if(!r)return null;const l={file:r,short:shortPath(r,s)};if("Edit"===t||"editFile"===t)return"string"!=typeof e.old_string||"string"!=typeof e.new_string?null:Object.assign({kind:"Update"},l,lineDiff(e.old_string,e.new_string),{replaceAll:!!e.replace_all});if("Write"===t||"writeFile"===t){if("string"!=typeof e.content)return null;const t=i(r)||{text:null,missing:!0};let n=lineDiff(null==t.text?"":t.text,e.content);return n.rows.length||t.missing||!e.content||(n=fileRows(e.content)),Object.assign({kind:t.missing?"Create":"Write"},l,n,{truncated:n.truncated||!!t.truncated})}if("MultiEdit"===t){const t=(Array.isArray(e.edits)?e.edits:[]).filter((t=>t&&"string"==typeof t.old_string&&"string"==typeof t.new_string));if(!t.length)return null;const n=i(r)||{text:null,missing:!0};if("string"==typeof n.text){let e=n.text,s=0;for(const n of t)-1!==e.indexOf(n.old_string)?e=n.replace_all?e.split(n.old_string).join(n.new_string):e.replace(n.old_string,n.new_string):s++;const i=lineDiff(n.text,e);return Object.assign({kind:"Update"},l,i,{misses:s,replaceAll:t.some((t=>t.replace_all))})}let s=[],o=0,a=0,c=!1;return t.forEach(((e,n)=>{const i=lineDiff(e.old_string,e.new_string);n&&s.push({sign:" ",text:"",marker:!0,note:`… edit ${n+1} of ${t.length}`}),s=s.concat(i.rows),o+=i.adds,a+=i.dels,c=c||i.truncated})),Object.assign({kind:"Update"},l,{rows:s,adds:o,dels:a,truncated:c,stacked:t.length})}return null}catch{return null}}function changeSummary(t){const e=[];return t.adds&&e.push(`Added ${t.adds} line${1===t.adds?"":"s"}`),t.dels&&e.push(`removed ${t.dels} line${1===t.dels?"":"s"}`),e.length?e.join(", "):"no line changes"}module.exports={DIFF_LIMITS:DIFF_LIMITS,splitLines:splitLines,lineDiff:lineDiff,readCapped:readCapped,shortPath:shortPath,changeSummary:changeSummary,editPreview:editPreview};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const{DIM:DIM,RESET:RESET,GLYPH:GLYPH,themeOf:themeOf,diffOf:diffOf}=require("./theme.js"),{w:w,clip:clip}=require("./screen.js"),AUTO_OPEN_ROWS=30,MAX_BLOCK_ROWS=200,INDENT=" ",KEYWORDS=new Set(["const","let","var","function","return","if","else","for","while","do","switch","case","break","continue","import","export","from","default","class","extends","new","try","catch","finally","throw","async","await","yield","static","typeof","instanceof","in","of","delete","this","super","null","undefined","true","false","def","elif","lambda","pass","raise","with","as","not","and","or","is","None","True","False","self","fn","mut","pub","impl","struct","enum","trait","match","package","func","defer","chan","nil","echo","local","then","fi","esac"]);function highlightLine(e,n){const t=n||diffOf(null),i=[],l=String(null==e?"":e),o=/(\/\/[^\n]*|#[^\n]*|\/\*[\s\S]*?\*\/)|('(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|`(?:\\.|[^`\\])*`)|(0[xX][0-9a-fA-F]+|\d+(?:\.\d+)?)|([A-Za-z_$][A-Za-z0-9_$]*)/g,s=(e,n)=>{e&&i.push({t:e,c:n})};let r,d=0;for(;r=o.exec(l);){if(r.index>d&&s(l.slice(d,r.index),t.codeFg),r[1])s(r[1],t.comment);else if(r[2])s(r[2],t.str);else if(r[3])s(r[3],t.num);else{const e=r[4],n=/^\s*\(/.test(l.slice(r.index+e.length));s(e,KEYWORDS.has(e)?t.kw:n?t.fn:t.codeFg)}d=r.index+r[0].length}return d<l.length&&s(l.slice(d),t.codeFg),i}function markIntraLine(e){for(let n=0;n<e.length;n++){if("-"!==e[n].sign)continue;let t=n;for(;t<e.length&&"-"===e[t].sign;)t++;let i=t;for(;i<e.length&&"+"===e[i].sign;)i++;const l=t-n;if(l&&l===i-t)for(let i=0;i<l;i++){const l=intraLine(e[n+i].text,e[t+i].text);l&&(e[n+i].hi={start:l.delStart,end:l.delEnd,side:"del"},e[t+i].hi={start:l.addStart,end:l.addEnd,side:"add"})}n=i-1}return e}function intraLine(e,n){const t=[...String(null==e?"":e)],i=[...String(null==n?"":n)];let l=0;for(;l<t.length&&l<i.length&&t[l]===i[l];)l++;let o=0;for(;o<t.length-l&&o<i.length-l&&t[t.length-1-o]===i[i.length-1-o];)o++;return l+o<.4*(Math.max(t.length,i.length)||1)?null:{delStart:l,delEnd:t.length-o,addStart:l,addEnd:i.length-o}}function defaultOpen(e){return!(!e||!e.rows)&&e.rows.length<=30}function diffSummaryRow(e,n,t={}){const i=themeOf(n),l=diffOf(n),o=[` ${i.gray}${GLYPH.hook} ${RESET}`];
|
|
3
|
+
"use strict";const{DIM:DIM,RESET:RESET,GLYPH:GLYPH,themeOf:themeOf,diffOf:diffOf}=require("./theme.js"),{w:w,clip:clip}=require("./screen.js"),AUTO_OPEN_ROWS=30,MAX_BLOCK_ROWS=200,INDENT=" ",KEYWORDS=new Set(["const","let","var","function","return","if","else","for","while","do","switch","case","break","continue","import","export","from","default","class","extends","new","try","catch","finally","throw","async","await","yield","static","typeof","instanceof","in","of","delete","this","super","null","undefined","true","false","def","elif","lambda","pass","raise","with","as","not","and","or","is","None","True","False","self","fn","mut","pub","impl","struct","enum","trait","match","package","func","defer","chan","nil","echo","local","then","fi","esac"]);function highlightLine(e,n){const t=n||diffOf(null),i=[],l=String(null==e?"":e),o=/(\/\/[^\n]*|#[^\n]*|\/\*[\s\S]*?\*\/)|('(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|`(?:\\.|[^`\\])*`)|(0[xX][0-9a-fA-F]+|\d+(?:\.\d+)?)|([A-Za-z_$][A-Za-z0-9_$]*)/g,s=(e,n)=>{e&&i.push({t:e,c:n})};let r,d=0;for(;r=o.exec(l);){if(r.index>d&&s(l.slice(d,r.index),t.codeFg),r[1])s(r[1],t.comment);else if(r[2])s(r[2],t.str);else if(r[3])s(r[3],t.num);else{const e=r[4],n=/^\s*\(/.test(l.slice(r.index+e.length));s(e,KEYWORDS.has(e)?t.kw:n?t.fn:t.codeFg)}d=r.index+r[0].length}return d<l.length&&s(l.slice(d),t.codeFg),i}function markIntraLine(e){for(let n=0;n<e.length;n++){if("-"!==e[n].sign)continue;let t=n;for(;t<e.length&&"-"===e[t].sign;)t++;let i=t;for(;i<e.length&&"+"===e[i].sign;)i++;const l=t-n;if(l&&l===i-t)for(let i=0;i<l;i++){const l=intraLine(e[n+i].text,e[t+i].text);l&&(e[n+i].hi={start:l.delStart,end:l.delEnd,side:"del"},e[t+i].hi={start:l.addStart,end:l.addEnd,side:"add"})}n=i-1}return e}function intraLine(e,n){const t=[...String(null==e?"":e)],i=[...String(null==n?"":n)];let l=0;for(;l<t.length&&l<i.length&&t[l]===i[l];)l++;let o=0;for(;o<t.length-l&&o<i.length-l&&t[t.length-1-o]===i[i.length-1-o];)o++;return l+o<.4*(Math.max(t.length,i.length)||1)?null:{delStart:l,delEnd:t.length-o,addStart:l,addEnd:i.length-o}}function defaultOpen(e){return!(!e||!e.rows)&&e.rows.length<=30}function diffSummaryRow(e,n,t={}){const i=themeOf(n),l=diffOf(n),o=[` ${i.gray}${GLYPH.hook} ${RESET}`];if(o.push(`${i.lavender}${e.kind}(${e.short})${RESET}`),e.adds&&o.push(`${l.addFg} +${e.adds}${RESET}`),e.dels&&o.push(`${l.delFg} -${e.dels}${RESET}`),e.adds||e.dels||o.push(`${i.gray} no line changes${RESET}`),e.misses&&o.push(`${i.gold} ${e.misses} edit(s) not applied${RESET}`),e.rows&&e.rows.length){const n=t.open?"click to collapse":e.adds||e.dels?"click to view diff":"click to view file";o.push(`${DIM} · ${n}${RESET}`)}return o.join("")}function renderDiffBlock(e,n,t,i={}){const l=Math.max(8,Number(t)||80),o=diffOf(n),s=(themeOf(n),[clipRow(diffSummaryRow(e,n,{open:i.open}),l)]);if(!(i.open&&e&&e.rows&&e.rows.length))return s;const r=markIntraLine(e.rows.slice(0,200).map((e=>Object.assign({},e))));let d=1;for(const e of r)e.no&&e.no>d&&(d=e.no);const a=Math.max(2,String(d).length),c=Math.max(4,l-(5+a+3));for(const e of r){if(e.marker){s.push(clipRow(`${DIM}${INDENT}… ${null==e.note?"":e.note}${RESET}`,l));continue}const n="-"===e.sign?"del":"+"===e.sign?"add":"ctx",t="del"===n?o.delBg:"add"===n?o.addBg:"",i="del"===n?o.delHiBg:o.addHiBg,r="del"===n?o.delHiFg:o.addHiFg,d="del"===n?o.delFg:"add"===n?o.addFg:DIM,f=`${t}${o.gutter}${INDENT}${String(null==e.no?"":e.no).padStart(a)} ${RESET}`,h=`${t}${d}${" "===e.sign?" ":e.sign} ${RESET}`,u=codeRow(clip(String(null==e.text?"":e.text),c),t,i,r,o,e.hi),g=w(`${INDENT}${String(null==e.no?"":e.no).padStart(a)} `)+2+w(clip(String(null==e.text?"":e.text),c)),$=t&&g<l?`${t}${" ".repeat(l-g)}${RESET}`:"";s.push(f+h+u+$+RESET)}const f=e.rows.length-200;return f>0&&s.push(clipRow(`${DIM}${INDENT}… ${f} more diff lines${RESET}`,l)),e.truncated&&s.push(clipRow(`${DIM}${INDENT}… diff truncated (file too large to compare in full)${RESET}`,l)),s}function codeRow(e,n,t,i,l,o){const s=[];let r=0;for(const d of highlightLine(e,l)){const e=[...d.t],l=r,a=r+e.length;if(r=a,!o||a<=o.start||l>=o.end){s.push(`${n}${d.c}${d.t}`);continue}const c=Math.max(o.start,l)-l,f=Math.min(o.end,a)-l;c>0&&s.push(`${n}${d.c}${e.slice(0,c).join("")}`),f>c&&s.push(`${t}${i}${e.slice(c,f).join("")}`),f<e.length&&s.push(`${n}${d.c}${e.slice(f).join("")}`)}return s.join("")}function clipRow(e,n){return w(e)<=n?e:clipVisible(e,n)+RESET}function clipVisible(e,n){let t=0,i="",l=0;const o=String(e);for(;l<o.length;){if(""===o[l]&&"["===o[l+1]){const e=o.indexOf("m",l);if(-1===e)break;i+=o.slice(l,e+1),l=e+1;continue}const e=o.codePointAt(l),s=String.fromCodePoint(e);l+=s.length;const r=w(s);if(t+r>n)break;i+=s,t+=r}return i}module.exports={AUTO_OPEN_ROWS:30,MAX_BLOCK_ROWS:200,INDENT:INDENT,defaultOpen:defaultOpen,highlightLine:highlightLine,markIntraLine:markIntraLine,diffSummaryRow:diffSummaryRow,renderDiffBlock:renderDiffBlock};
|
|
@@ -8,13 +8,13 @@
|
|
|
8
8
|
"source": "/usr/bin/bwrap",
|
|
9
9
|
"sourceDigest": "e318903862396f96de3df57264e0158682b952fd3fb53ac23d876413e7b30f71",
|
|
10
10
|
"linkage": [
|
|
11
|
-
"linux-vdso.so.1 (
|
|
12
|
-
"libselinux.so.1 => /lib/x86_64-linux-gnu/libselinux.so.1 (
|
|
13
|
-
"libcap.so.2 => /lib/x86_64-linux-gnu/libcap.so.2 (
|
|
14
|
-
"libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (
|
|
15
|
-
"libpcre2-8.so.0 => /lib/x86_64-linux-gnu/libpcre2-8.so.0 (
|
|
16
|
-
"/lib64/ld-linux-x86-64.so.2 (
|
|
11
|
+
"linux-vdso.so.1 (0x00007602120c7000)",
|
|
12
|
+
"libselinux.so.1 => /lib/x86_64-linux-gnu/libselinux.so.1 (0x0000760212069000)",
|
|
13
|
+
"libcap.so.2 => /lib/x86_64-linux-gnu/libcap.so.2 (0x000076021205c000)",
|
|
14
|
+
"libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x0000760211e00000)",
|
|
15
|
+
"libpcre2-8.so.0 => /lib/x86_64-linux-gnu/libpcre2-8.so.0 (0x0000760211d66000)",
|
|
16
|
+
"/lib64/ld-linux-x86-64.so.2 (0x00007602120c9000)"
|
|
17
17
|
],
|
|
18
18
|
"usernsProbe": "ok",
|
|
19
|
-
"stagedAt": "2026-11-
|
|
19
|
+
"stagedAt": "2026-11-06T14:18:34.860Z"
|
|
20
20
|
}
|