aegisone 1.0.69 → 1.0.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/vendor/cli/bin/aegiscode.js +11 -0
  4. package/vendor/cli/package.json +1 -1
  5. package/vendor/cli/src/app.js +1 -1
  6. package/vendor/cli/src/limits.js +1 -1
  7. package/vendor/cli/src/provenance.lock.json +2 -2
  8. package/vendor/cli/src/screen.js +1 -1
  9. package/vendor/cli/vendor/client/session-store.js +1 -1
  10. package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
  11. package/vendor/cli/vendor/desktop/main.js +12 -1
  12. package/vendor/desktop/lib/local/integrity.js +1 -1
  13. package/vendor/desktop/lib/local/pty-host.js +1 -1
  14. package/vendor/desktop/main.js +12 -1
  15. package/vendor/desktop/package.json +1 -1
  16. package/vendor/desktop/renderer/app.js +3 -3
  17. package/vendor/desktop/renderer/index.html +18 -0
  18. package/vendor/desktop/renderer/pty-panel.js +1 -1
  19. package/vendor/desktop/renderer/pty-renderer.js +1 -1
  20. package/vendor/desktop/renderer/pty-window.js +1 -1
  21. package/vendor/desktop/renderer/style.css +53 -1
  22. package/vendor/desktop/vendor/faces/cli/bin/aegiscode.js +2 -2
  23. package/vendor/desktop/vendor/faces/cli/package.json +1 -1
  24. package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
  25. package/vendor/desktop/vendor/faces/cli/src/limits.js +1 -1
  26. package/vendor/desktop/vendor/faces/cli/src/provenance.lock.json +2 -2
  27. package/vendor/desktop/vendor/faces/cli/src/screen.js +1 -1
  28. package/vendor/desktop/vendor/faces/cli/vendor/client/session-store.js +1 -1
  29. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
  30. package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +1 -1
  31. package/vendor/desktop/vendor/session-store.js +1 -1
@@ -1465,6 +1465,24 @@
1465
1465
  <div class="queue-upgrade" id="queue-upgrade"></div>
1466
1466
  </section>
1467
1467
  </div><!-- /#automations-view -->
1468
+
1469
+ <!-- The terminal face as a PAGE in this canvas, beside Settings and
1470
+ Automations (app.js showPtyView). It exists so the embedded
1471
+ `aegiscode` terminal can be reached from the Sessions list the way
1472
+ every other conversation is, instead of only as the full-window
1473
+ overlay or a detached OS window. The panel itself is unchanged:
1474
+ pty-panel.js mounts the same shell into #pty-mount here when it is
1475
+ handed a host, so tabs, `+`, `×` and the live xterm all still apply.
1476
+
1477
+ The terminal is NOT torn down when this page is hidden — switching
1478
+ to Sessions and back leaves the shell running, exactly as closing
1479
+ the overlay used to require an explicit `×`. -->
1480
+ <div id="pty-view" hidden>
1481
+ <div class="settings-view-header">
1482
+ <button type="button" class="settings-back" id="pty-back">&larr; Back to conversations</button>
1483
+ </div>
1484
+ <div class="pty-view-mount" id="pty-mount"></div>
1485
+ </div>
1468
1486
  </main>
1469
1487
 
1470
1488
  <!-- The ⌘P command palette.
@@ -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 PTY_PANEL_FRAME_SRC="pty-frame.html",PTY_PANEL_FRAME_ROOT="pty-frame-root";function ptyPanelCreateId(){return"undefined"!=typeof window&&window.crypto&&"function"==typeof window.crypto.randomUUID?window.crypto.randomUUID():`pty-${Date.now()}-${Math.random().toString(36).slice(2)}`}const ptyPanelSessions=new Map;let ptyPanelNextLabel=1,ptyPanelShell=null;function ptyPanelBuildShell(){const e=document.createElement("div");return e.className="pty-panel-overlay",e.innerHTML='<div class="pty-panel" role="dialog" aria-label="Terminal"><div class="pty-panel-header"><span class="pty-panel-tabs" role="tablist" aria-label="Terminal sessions"></span><button type="button" class="pty-panel-new" aria-label="New terminal" title="New terminal">+</button><button type="button" class="pty-panel-close" aria-label="Close terminal" title="Close this terminal">×</button></div><div class="pty-panel-body"></div></div>',e}function ptyPanelMount(e){const t=ptyPanelShell;if(!t)return!1;const n=t.querySelector(".pty-panel-tabs"),l=t.querySelector(".pty-panel-body");if(!n||!l)return!1;const a=document.createElement("button");a.type="button",a.className="pty-panel-tab",a.setAttribute("role","tab"),a.setAttribute("aria-selected","false"),a.textContent=e.label,a.addEventListener("click",()=>ptyPanelActivate(e)),n.appendChild(a);const o=document.createElement("div");o.className="pty-panel-slot",o.hidden=!0;const i=document.createElement("iframe");return i.className="pty-panel-frame",i.title=`Terminal ${e.label} (aegiscode)`,i.src="pty-frame.html",o.appendChild(i),l.appendChild(o),e.tab=a,e.slot=o,e.frame=i,!0}function ptyPanelActivate(e){if(e&&!e.closed){for(const t of ptyPanelSessions.values()){const n=t===e;t.slot&&(t.slot.hidden=!n),t.tab&&(t.tab.classList.toggle("is-active",n),t.tab.setAttribute("aria-selected",n?"true":"false"))}if(ptyPanelShell.active=e.id,e.term&&e.host){const t=e.term,n=e.host;requestAnimationFrame(()=>{e.closed||e.slot.hidden||ptyPanelFit(t,n)})}e.term&&e.term.focus()}}function ptyPanelTeardown(e){if(e){e.closed=!0;try{e.unsubscribe&&e.unsubscribe()}catch{}try{window.aegis.pty.cancel(e.id)}catch{}try{e.term&&e.term.dispose()}catch{}try{e.resizeObserver&&e.resizeObserver.disconnect()}catch{}e.tab&&e.tab.parentNode&&e.tab.parentNode.removeChild(e.tab),e.slot&&e.slot.parentNode&&e.slot.parentNode.removeChild(e.slot)}}function ptyPanelClose(e){const t=e?ptyPanelSessions.get(e):ptyPanelSessions.get(ptyPanelShell&&ptyPanelShell.active);if(!t)return;if(ptyPanelSessions.delete(t.id),ptyPanelTeardown(t),0===ptyPanelSessions.size)return void ptyPanelCloseAll();const n=Array.from(ptyPanelSessions.values());ptyPanelActivate(n[n.length-1])}function ptyPanelCloseAll(){for(const e of Array.from(ptyPanelSessions.values()))ptyPanelSessions.delete(e.id),ptyPanelTeardown(e);ptyPanelShell&&ptyPanelShell.parentNode&&ptyPanelShell.parentNode.removeChild(ptyPanelShell),ptyPanelShell=null}function ptyPanelFontFamily(e){try{return e.getComputedStyle(e.document.documentElement).getPropertyValue("--font-mono").trim()||"monospace"}catch{return"monospace"}}function ptyPanelAttachRenderer(e,t){const n=t&&t.aegisPtyRenderer;return n&&"function"==typeof n.attach?n.attach(e,{win:t,bridge:window.aegis}):{tier:"dom",addon:null,tried:["dom"],errors:[]}}function ptyPanelFail(e,t){if(!e||!e.slot)return;const n=document.createElement("p");n.className="pty-panel-note",n.textContent=t,e.slot.appendChild(n)}function ptyPanelBoot(e){if(!e||e.closed||e.term)return;const t=e.frame&&e.frame.contentWindow,n=t&&t.document,l=n&&n.getElementById("pty-frame-root");if(!t||"function"!=typeof t.Terminal||!l)return void ptyPanelFail(e,"the terminal panel is not available in this build (xterm.js missing)");const a=new t.Terminal({convertEol:!0,cursorBlink:!1,fontSize:13,fontFamily:ptyPanelFontFamily(t)});e.term=a,e.host=l,a.open(l),e.renderer=ptyPanelAttachRenderer(a,t),ptyPanelFit(a,l),ptyPanelSettle(e,a,l);const o=t.document.fonts;o&&"object"==typeof o.ready&&"function"==typeof o.ready.then&&o.ready.then(()=>{e.closed||e.slot.hidden||ptyPanelFit(a,l)});const i=e.id;e.unsubscribe=window.aegis.pty.onEvent(i,e=>{const t=e&&e.p;t&&("data"===t.kind?a.write(t.chunk):"exit"===t.kind&&a.write("\r\n[process exited]\r\n"))}),e.slot&&"function"==typeof ResizeObserver&&(e.resizeObserver=new ResizeObserver(()=>{ptyPanelFitting!==a&&ptyPanelFit(a,l)}),e.resizeObserver.observe(e.slot)),a.onData(e=>window.aegis.pty.write(i,e)),a.onResize(({cols:e,rows:t})=>window.aegis.pty.resize(i,e,t)),window.aegis.pty.exec(i,{cols:a.cols,rows:a.rows}).then(e=>{e&&e.ok||a.write(`\r\n[could not start: ${e&&e.e&&e.e.msg||"unknown error"}]\r\n`)}),a.focus()}function ptyPanelOpen(){if("undefined"==typeof window||void 0===window.aegis||!window.aegis.pty)return{ok:!1,reason:"the terminal panel bridge is not available in this build"};ptyPanelShell||(ptyPanelShell=ptyPanelBuildShell(),document.body.appendChild(ptyPanelShell),ptyPanelShell.querySelector(".pty-panel-new").addEventListener("click",()=>ptyPanelOpen()),ptyPanelShell.querySelector(".pty-panel-close").addEventListener("click",()=>ptyPanelClose()),ptyPanelShell.addEventListener("keydown",e=>{"Escape"===e.key&&ptyPanelClose()}));const e={id:ptyPanelCreateId(),label:String(ptyPanelNextLabel++),tab:null,slot:null,frame:null,term:null,host:null,unsubscribe:null,resizeObserver:null,closed:!1};return ptyPanelSessions.set(e.id,e),ptyPanelMount(e)?(ptyPanelActivate(e),e.frame&&e.frame.addEventListener("load",()=>ptyPanelBoot(e)),{ok:!0,id:e.id}):(ptyPanelSessions.delete(e.id),{ok:!1,reason:"could not build the terminal panel"})}let ptyPanelFitting=null;function ptyPanelSettle(e,t,n){let l=null,a=0;const o=()=>{if(!e||e.closed||e.term!==t)return;if(a>=3)return;a+=1;let i=null;try{const e=ptyPanelFit(t,n);i=e?`${e.cols}x${e.rows}`:null}catch{return}i&&i===l||(l=i,"function"==typeof requestAnimationFrame&&requestAnimationFrame(o))};"function"==typeof requestAnimationFrame&&requestAnimationFrame(o)}function ptyPanelPad(e,t,n){const l=e=>{const t=parseFloat(e);return Number.isFinite(t)?t:0};return l(e&&e[t])+l(e&&e[n])}function ptyPanelFit(e,t){const n=e._core,l=n&&n._renderService&&n._renderService.dimensions&&n._renderService.dimensions.css.cell;if(!l||!l.width||!l.height)return null;const a=(t.ownerDocument&&t.ownerDocument.defaultView||window).getComputedStyle(t),o=ptyPanelPad(a,"paddingLeft","paddingRight"),i=ptyPanelPad(a,"paddingTop","paddingBottom"),s=Math.max(2,Math.floor((t.clientWidth-o)/l.width)),r=Math.max(1,Math.floor((t.clientHeight-i)/l.height));if(s!==e.cols||r!==e.rows){ptyPanelFitting=e;try{e.resize(s,r)}finally{ptyPanelFitting=null}}return{cols:s,rows:r}}function ptyPanelIsOpen(){return ptyPanelSessions.size>0}"undefined"!=typeof module&&module.exports&&(module.exports={createId:ptyPanelCreateId,open:ptyPanelOpen,close:ptyPanelClose,closeAll:ptyPanelCloseAll,isOpen:ptyPanelIsOpen,count:()=>ptyPanelSessions.size,FRAME_SRC:"pty-frame.html",FRAME_ROOT:"pty-frame-root"}),"undefined"!=typeof window&&(window.aegisPtyPanel={open:ptyPanelOpen,close:ptyPanelClose,closeAll:ptyPanelCloseAll,isOpen:ptyPanelIsOpen,count:()=>ptyPanelSessions.size});
3
+ "use strict";const PTY_PANEL_FRAME_SRC="pty-frame.html",PTY_PANEL_FRAME_ROOT="pty-frame-root";function ptyPanelCreateId(){return"undefined"!=typeof window&&window.crypto&&"function"==typeof window.crypto.randomUUID?window.crypto.randomUUID():`pty-${Date.now()}-${Math.random().toString(36).slice(2)}`}const ptyPanelSessions=new Map;let ptyPanelNextLabel=1,ptyPanelShell=null,ptyPanelHost=null;function ptyPanelBuildShell(e){const t=document.createElement("div");return t.className=e?"pty-panel-overlay is-page":"pty-panel-overlay",t.innerHTML='<div class="pty-panel" role="dialog" aria-label="Terminal"><div class="pty-panel-header"><span class="pty-panel-tabs" role="tablist" aria-label="Terminal sessions"></span><button type="button" class="pty-panel-new" aria-label="New terminal" title="New terminal">+</button><button type="button" class="pty-panel-close" aria-label="Close terminal" title="Close this terminal">×</button></div><div class="pty-panel-body"></div></div>',t}function ptyPanelMount(e){const t=ptyPanelShell;if(!t)return!1;const n=t.querySelector(".pty-panel-tabs"),l=t.querySelector(".pty-panel-body");if(!n||!l)return!1;const a=document.createElement("button");a.type="button",a.className="pty-panel-tab",a.setAttribute("role","tab"),a.setAttribute("aria-selected","false"),a.textContent=e.label,a.addEventListener("click",()=>ptyPanelActivate(e)),n.appendChild(a);const o=document.createElement("div");o.className="pty-panel-slot",o.hidden=!0;const i=document.createElement("iframe");return i.className="pty-panel-frame",i.title=`Terminal ${e.label} (aegiscode)`,i.src="pty-frame.html",o.appendChild(i),l.appendChild(o),e.tab=a,e.slot=o,e.frame=i,!0}function ptyPanelActivate(e){if(e&&!e.closed){for(const t of ptyPanelSessions.values()){const n=t===e;t.slot&&(t.slot.hidden=!n),t.tab&&(t.tab.classList.toggle("is-active",n),t.tab.setAttribute("aria-selected",n?"true":"false"))}if(ptyPanelShell.active=e.id,e.term&&e.host){const t=e.term,n=e.host;requestAnimationFrame(()=>{e.closed||e.slot.hidden||ptyPanelFit(t,n)})}e.term&&e.term.focus()}}function ptyPanelTeardown(e){if(e){e.closed=!0;try{e.unsubscribe&&e.unsubscribe()}catch{}try{window.aegis.pty.cancel(e.id)}catch{}try{e.term&&e.term.dispose()}catch{}try{e.resizeObserver&&e.resizeObserver.disconnect()}catch{}e.tab&&e.tab.parentNode&&e.tab.parentNode.removeChild(e.tab),e.slot&&e.slot.parentNode&&e.slot.parentNode.removeChild(e.slot)}}function ptyPanelClose(e){const t=e?ptyPanelSessions.get(e):ptyPanelSessions.get(ptyPanelShell&&ptyPanelShell.active);if(!t)return;if(ptyPanelSessions.delete(t.id),ptyPanelTeardown(t),0===ptyPanelSessions.size)return void ptyPanelCloseAll();const n=Array.from(ptyPanelSessions.values());ptyPanelActivate(n[n.length-1])}function ptyPanelCloseAll(){for(const e of Array.from(ptyPanelSessions.values()))ptyPanelSessions.delete(e.id),ptyPanelTeardown(e);ptyPanelShell&&ptyPanelShell.parentNode&&ptyPanelShell.parentNode.removeChild(ptyPanelShell),ptyPanelShell=null}function ptyPanelFontFamily(e){try{return e.getComputedStyle(e.document.documentElement).getPropertyValue("--font-mono").trim()||"monospace"}catch{return"monospace"}}function ptyPanelAttachRenderer(e,t){const n=t&&t.aegisPtyRenderer;return n&&"function"==typeof n.attach?n.attach(e,{win:t,bridge:window.aegis}):{tier:"dom",addon:null,tried:["dom"],errors:[]}}function ptyPanelTitleName(e,t){const n=t&&t.aegisPtyRenderer;if(n&&"function"==typeof n.titleName)return n.titleName(e);const l=String(null==e?"":e).replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim().replace(/^[\u2800-\u28FF]\s*/,"").split(" · AEGIS Code")[0].trim();return"AEGIS Code"===l?"":l}function ptyPanelFail(e,t){if(!e||!e.slot)return;const n=document.createElement("p");n.className="pty-panel-note",n.textContent=t,e.slot.appendChild(n)}function ptyPanelBoot(e){if(!e||e.closed||e.term)return;const t=e.frame&&e.frame.contentWindow,n=t&&t.document,l=n&&n.getElementById("pty-frame-root");if(!t||"function"!=typeof t.Terminal||!l)return void ptyPanelFail(e,"the terminal panel is not available in this build (xterm.js missing)");const a=new t.Terminal({convertEol:!0,cursorBlink:!1,fontSize:13,fontFamily:ptyPanelFontFamily(t)});e.term=a,e.host=l,a.open(l),e.renderer=ptyPanelAttachRenderer(a,t),ptyPanelFit(a,l),ptyPanelSettle(e,a,l);const o=t.document.fonts;o&&"object"==typeof o.ready&&"function"==typeof o.ready.then&&o.ready.then(()=>{e.closed||e.slot.hidden||ptyPanelFit(a,l)});const i=e.id;e.unsubscribe=window.aegis.pty.onEvent(i,e=>{const t=e&&e.p;t&&("data"===t.kind?a.write(t.chunk):"exit"===t.kind&&a.write("\r\n[process exited]\r\n"))}),e.slot&&"function"==typeof ResizeObserver&&(e.resizeObserver=new ResizeObserver(()=>{ptyPanelFitting!==a&&ptyPanelFit(a,l)}),e.resizeObserver.observe(e.slot)),"function"==typeof a.onTitleChange&&a.onTitleChange(n=>{const l=ptyPanelTitleName(n,t);if(l){if(e.name=l,"function"==typeof e.onName)try{e.onName(l)}catch(e){}e.tab&&(e.tab.textContent!==l&&(e.tab.textContent=l),e.tab.title=l),e.frame&&(e.frame.title=`${l} (aegiscode)`)}}),a.onData(e=>window.aegis.pty.write(i,e)),a.onResize(({cols:e,rows:t})=>window.aegis.pty.resize(i,e,t)),window.aegis.pty.exec(i,{cols:a.cols,rows:a.rows,cliSessionId:e.cliSessionId||void 0}).then(e=>{e&&e.ok||a.write(`\r\n[could not start: ${e&&e.e&&e.e.msg||"unknown error"}]\r\n`)}),a.focus()}function ptyPanelOpen(e){const t=e||{};if("undefined"==typeof window||void 0===window.aegis||!window.aegis.pty)return{ok:!1,reason:"the terminal panel bridge is not available in this build"};const n=t.host||ptyPanelHost||null,l=n||document.body;if(ptyPanelShell?(ptyPanelShell.parentNode!==l&&l.appendChild(ptyPanelShell),ptyPanelShell.className=n?"pty-panel-overlay is-page":"pty-panel-overlay"):(ptyPanelShell=ptyPanelBuildShell(Boolean(n)),l.appendChild(ptyPanelShell),ptyPanelShell.querySelector(".pty-panel-new").addEventListener("click",()=>ptyPanelOpen()),ptyPanelShell.querySelector(".pty-panel-close").addEventListener("click",()=>ptyPanelClose()),ptyPanelShell.addEventListener("keydown",e=>{"Escape"===e.key&&ptyPanelClose()})),ptyPanelHost=n,t.sessionId){const e=String(t.sessionId);for(const t of ptyPanelSessions.values())if(t.cliSessionId&&t.cliSessionId===e)return ptyPanelActivate(t),{ok:!0,reused:!0}}const a={id:ptyPanelCreateId(),label:String(ptyPanelNextLabel++),cliSessionId:t.sessionId?String(t.sessionId):"",onName:"function"==typeof t.onName?t.onName:null,name:"",tab:null,slot:null,frame:null,term:null,host:null,unsubscribe:null,resizeObserver:null,closed:!1};return ptyPanelSessions.set(a.id,a),ptyPanelMount(a)?(ptyPanelActivate(a),a.frame&&a.frame.addEventListener("load",()=>ptyPanelBoot(a)),{ok:!0,id:a.id}):(ptyPanelSessions.delete(a.id),{ok:!1,reason:"could not build the terminal panel"})}let ptyPanelFitting=null;function ptyPanelSettle(e,t,n){let l=null,a=0;const o=()=>{if(!e||e.closed||e.term!==t)return;if(a>=3)return;a+=1;let i=null;try{const e=ptyPanelFit(t,n);i=e?`${e.cols}x${e.rows}`:null}catch{return}i&&i===l||(l=i,"function"==typeof requestAnimationFrame&&requestAnimationFrame(o))};"function"==typeof requestAnimationFrame&&requestAnimationFrame(o)}function ptyPanelPad(e,t,n){const l=e=>{const t=parseFloat(e);return Number.isFinite(t)?t:0};return l(e&&e[t])+l(e&&e[n])}function ptyPanelFit(e,t){const n=e._core,l=n&&n._renderService&&n._renderService.dimensions&&n._renderService.dimensions.css.cell;if(!l||!l.width||!l.height)return null;const a=(t.ownerDocument&&t.ownerDocument.defaultView||window).getComputedStyle(t),o=ptyPanelPad(a,"paddingLeft","paddingRight"),i=ptyPanelPad(a,"paddingTop","paddingBottom"),s=Math.max(2,Math.floor((t.clientWidth-o)/l.width)),r=Math.max(1,Math.floor((t.clientHeight-i)/l.height));if(s!==e.cols||r!==e.rows){ptyPanelFitting=e;try{e.resize(s,r)}finally{ptyPanelFitting=null}}return{cols:s,rows:r}}function ptyPanelIsOpen(){return ptyPanelSessions.size>0}"undefined"!=typeof module&&module.exports&&(module.exports={createId:ptyPanelCreateId,open:ptyPanelOpen,close:ptyPanelClose,closeAll:ptyPanelCloseAll,isOpen:ptyPanelIsOpen,count:()=>ptyPanelSessions.size,FRAME_SRC:"pty-frame.html",FRAME_ROOT:"pty-frame-root"}),"undefined"!=typeof window&&(window.aegisPtyPanel={open:ptyPanelOpen,close:ptyPanelClose,closeAll:ptyPanelCloseAll,isOpen:ptyPanelIsOpen,count:()=>ptyPanelSessions.size});
@@ -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 PTY_RENDER_TIERS=Object.freeze(["webgl","canvas","dom"]);function ptyGpuAllowed(n){const e=(n||{}).pty;return Boolean(e)&&!0===e.gpu}function addonCtor(n,e){return"function"==typeof n?n:n&&"object"==typeof n&&"function"==typeof n[e]?n[e]:null}function ptyRenderPlan(n){const e=n||{},o=e.win||{},t=[];return ptyGpuAllowed(e.bridge)&&addonCtor(o.WebglAddon,"WebglAddon")&&t.push("webgl"),addonCtor(o.CanvasAddon,"CanvasAddon")&&t.push("canvas"),t.push("dom"),t}function ptyAttachRenderer(n,e){const o=e||{},t=o.win||{},d=ptyRenderPlan(o),r=[],a=[];for(const e of d){if(r.push(e),"dom"===e)return"function"==typeof o.onTier&&o.onTier("dom",null),{tier:"dom",addon:null,tried:r,errors:a};const d="webgl"===e?addonCtor(t.WebglAddon,"WebglAddon"):addonCtor(t.CanvasAddon,"CanvasAddon");if("function"==typeof d)try{const t=new d;return n.loadAddon(t),"function"==typeof o.onTier&&o.onTier(e,t),{tier:e,addon:t,tried:r,errors:a}}catch(n){a.push(`${e}: ${n&&n.message||n}`);continue}else a.push(`${e}: addon is not loaded`)}return{tier:"dom",addon:null,tried:r,errors:a}}"undefined"!=typeof window&&(window.aegisPtyRenderer={TIERS:PTY_RENDER_TIERS,gpuAllowed:ptyGpuAllowed,ctor:addonCtor,plan:ptyRenderPlan,attach:ptyAttachRenderer}),"undefined"!=typeof module&&module.exports&&(module.exports={PTY_RENDER_TIERS:PTY_RENDER_TIERS,addonCtor:addonCtor,ptyGpuAllowed:ptyGpuAllowed,ptyRenderPlan:ptyRenderPlan,ptyAttachRenderer:ptyAttachRenderer});
3
+ "use strict";const PTY_RENDER_TIERS=Object.freeze(["webgl","canvas","dom"]);function ptyGpuAllowed(e){const n=(e||{}).pty;return Boolean(n)&&!0===n.gpu}function addonCtor(e,n){return"function"==typeof e?e:e&&"object"==typeof e&&"function"==typeof e[n]?e[n]:null}function ptyRenderPlan(e){const n=e||{},t=n.win||{},o=[];return ptyGpuAllowed(n.bridge)&&addonCtor(t.WebglAddon,"WebglAddon")&&o.push("webgl"),addonCtor(t.CanvasAddon,"CanvasAddon")&&o.push("canvas"),o.push("dom"),o}function ptyAttachRenderer(e,n){const t=n||{},o=t.win||{},d=ptyRenderPlan(t),r=[],l=[];for(const n of d){if(r.push(n),"dom"===n)return"function"==typeof t.onTier&&t.onTier("dom",null),{tier:"dom",addon:null,tried:r,errors:l};const d="webgl"===n?addonCtor(o.WebglAddon,"WebglAddon"):addonCtor(o.CanvasAddon,"CanvasAddon");if("function"==typeof d)try{const o=new d;return e.loadAddon(o),"function"==typeof t.onTier&&t.onTier(n,o),{tier:n,addon:o,tried:r,errors:l}}catch(e){l.push(`${n}: ${e&&e.message||e}`);continue}else l.push(`${n}: addon is not loaded`)}return{tier:"dom",addon:null,tried:r,errors:l}}const PTY_TITLE_APP="AEGIS Code",PTY_TITLE_MAX=28,PTY_TITLE_SPIN=/^[\u2800-\u28FF]\s*/;function ptyTitleName(e,n){const t=n||{},o=t.app||"AEGIS Code",d=t.max||28;let r=String(null==e?"":e).replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();if(!r)return"";r=r.replace(PTY_TITLE_SPIN,"").trim();const l=` · ${o}`;if(r.length>l.length&&r.slice(-l.length)===l&&(r=r.slice(0,-l.length).trim()),!r||r===o)return"";if(r.length>d){const e=r.slice(0,d),n=e.lastIndexOf(" ");r=`${(n>0?e.slice(0,n):e).trim()}…`}return r}"undefined"!=typeof window&&(window.aegisPtyRenderer={TIERS:PTY_RENDER_TIERS,gpuAllowed:ptyGpuAllowed,ctor:addonCtor,plan:ptyRenderPlan,attach:ptyAttachRenderer,titleName:ptyTitleName}),"undefined"!=typeof module&&module.exports&&(module.exports={PTY_RENDER_TIERS:PTY_RENDER_TIERS,PTY_TITLE_APP:"AEGIS Code",PTY_TITLE_MAX:28,addonCtor:addonCtor,ptyGpuAllowed:ptyGpuAllowed,ptyRenderPlan:ptyRenderPlan,ptyAttachRenderer:ptyAttachRenderer,ptyTitleName:ptyTitleName});
@@ -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 ptyWinSessions=new Map;let ptyWinNextLabel=1,ptyWinActive=null;function ptyWinId(){return window.crypto&&"function"==typeof window.crypto.randomUUID?window.crypto.randomUUID():`pty-${Date.now()}-${Math.random().toString(36).slice(2)}`}let ptyWinFitting=null;function ptyPad(t,e,n){const i=t=>{const e=parseFloat(t);return Number.isFinite(e)?e:0};return i(t&&t[e])+i(t&&t[n])}function ptyWinFit(t,e){const n=t&&t._core,i=n&&n._renderService&&n._renderService.dimensions&&n._renderService.dimensions.css.cell;if(!i||!i.width||!i.height)return null;const o=ptyPad(getComputedStyle(e),"paddingLeft","paddingRight"),s=ptyPad(getComputedStyle(e),"paddingTop","paddingBottom"),r=Math.max(2,Math.floor((e.clientWidth-o)/i.width)),l=Math.max(1,Math.floor((e.clientHeight-s)/i.height));if(r!==t.cols||l!==t.rows){ptyWinFitting=t;try{t.resize(r,l)}finally{ptyWinFitting=null}}return{cols:r,rows:l}}function ptyWinFontFamily(){return getComputedStyle(document.documentElement).getPropertyValue("--font-mono").trim()||"ui-monospace, SFMono-Regular, Menlo, monospace"}function ptyWinSettle(t,e,n){let i=null,o=0;const s=()=>{if(!t||t.closed||t.term!==e)return;if(o>=3)return;o+=1;let r=null;try{const t=ptyWinFit(e,n);r=t?`${t.cols}x${t.rows}`:null}catch{return}r&&r===i||(i=r,"function"==typeof requestAnimationFrame&&requestAnimationFrame(s))};"function"==typeof requestAnimationFrame&&requestAnimationFrame(s)}function ptyWinActivate(t){if(t&&!t.closed){for(const e of ptyWinSessions.values()){const n=e===t;e.slot&&(e.slot.hidden=!n),e.tab&&(e.tab.classList.toggle("is-active",n),e.tab.setAttribute("aria-selected",n?"true":"false"))}if(ptyWinActive=t.id,t.term&&t.slot){const e=t.term,n=t.slot;requestAnimationFrame(()=>{t.closed||ptyWinFit(e,n)})}t.term&&t.term.focus()}}function ptyWinTeardown(t){if(t){t.closed=!0;try{t.unsubscribe&&t.unsubscribe()}catch{}try{t.ro&&t.ro.disconnect()}catch{}try{window.aegis.pty.cancel(t.id)}catch{}if(ptyWinSessions.delete(t.id),t.tab&&t.tab.remove&&t.tab.remove(),t.slot&&t.slot.remove&&t.slot.remove(),ptyWinActive===t.id){const t=ptyWinSessions.values().next().value||null;ptyWinActive=null,t&&ptyWinActivate(t)}}}function ptyWinClose(t){const e=t?ptyWinSessions.get(t):ptyWinActive&&ptyWinSessions.get(ptyWinActive);e&&ptyWinTeardown(e),0===ptyWinSessions.size&&window.aegis&&"function"==typeof window.aegis.closePtyWindow&&window.aegis.closePtyWindow()}function ptyWinFail(t,e){const n=document.createElement("div");n.className="pty-win-note",n.textContent=e,t.slot&&t.slot.appendChild(n)}function ptyWinAttachRenderer(t){const e="undefined"!=typeof window?window.aegisPtyRenderer:null;return e&&"function"==typeof e.attach?e.attach(t,{win:window,bridge:window.aegis}):{tier:"dom",addon:null,tried:["dom"],errors:[]}}function ptyWinStart(){if("undefined"==typeof window||!window.aegis||!window.aegis.pty)return document.getElementById("pty-win-body").innerHTML='<div class="pty-win-note">the terminal bridge is not available in this build</div>',null;if("function"!=typeof window.Terminal)return document.getElementById("pty-win-body").innerHTML='<div class="pty-win-note">xterm.js is missing from this build — the terminal cannot render</div>',null;const t=document.getElementById("pty-win-tabs"),e=document.getElementById("pty-win-body"),n=ptyWinId(),i=String(ptyWinNextLabel++),o=document.createElement("button");o.type="button",o.className="pty-win-tab",o.setAttribute("role","tab"),o.textContent=i,o.title=`Terminal ${i} — click to switch, middle-click to close`;const s=document.createElement("div");s.className="pty-win-slot",s.hidden=!0;const r={id:n,label:i,tab:o,slot:s,term:null,unsubscribe:null,ro:null,closed:!1};ptyWinSessions.set(n,r),o.addEventListener("click",()=>ptyWinActivate(r)),o.addEventListener("auxclick",t=>{1===t.button&&(t.preventDefault(),ptyWinClose(n))}),t.appendChild(o),e.appendChild(s);const l=new window.Terminal({convertEol:!0,cursorBlink:!1,fontSize:13,fontFamily:ptyWinFontFamily(),allowProposedApi:!0});r.term=l,l.open(s),r.renderer=ptyWinAttachRenderer(l),ptyWinFit(l,s),ptyWinSettle(r,l,s);const c=document.fonts;return c&&c.ready&&"function"==typeof c.ready.then&&c.ready.then(()=>{r.closed||ptyWinFit(l,s)}),r.unsubscribe=window.aegis.pty.onEvent(n,t=>{const e=t&&t.p;e&&("data"===e.kind?l.write(e.chunk):"exit"===e.kind&&l.write("\r\n[process exited]\r\n"))}),"function"==typeof ResizeObserver&&(r.ro=new ResizeObserver(()=>{ptyWinFitting!==l&&ptyWinFit(l,s)}),r.ro.observe(e)),l.onData(t=>window.aegis.pty.write(n,t)),l.onResize(({cols:t,rows:e})=>window.aegis.pty.resize(n,t,e)),window.aegis.pty.exec(n,{cols:l.cols,rows:l.rows}).then(t=>{t&&t.ok||l.write(`\r\n[could not start: ${t&&t.e&&t.e.msg||"unknown error"}]\r\n`)}),ptyWinActivate(r),r}window.addEventListener("DOMContentLoaded",()=>{const t=document.getElementById("pty-win-new");t&&t.addEventListener("click",()=>ptyWinStart()),window.addEventListener("keydown",t=>{t.ctrlKey&&t.shiftKey&&("T"===t.key||"t"===t.key)?(t.preventDefault(),ptyWinStart()):t.ctrlKey&&t.shiftKey&&("W"===t.key||"w"===t.key)&&(t.preventDefault(),ptyWinClose())}),ptyWinStart()}),window.aegisPtyWindow={start:ptyWinStart,close:ptyWinClose,count:()=>ptyWinSessions.size,active:()=>ptyWinActive,renderers:()=>[...ptyWinSessions.values()].map(t=>t.renderer&&t.renderer.tier||"dom"),inspect:()=>{const t=ptyWinActive?ptyWinSessions.get(ptyWinActive):null;if(!t||!t.term)return null;const e=t.term,n=e.buffer&&e.buffer.active;let i="";if(n&&"function"==typeof n.getLine){const t=[];for(let e=0;e<n.length;e+=1){const i=n.getLine(e);i&&t.push("function"==typeof i.translateToString?i.translateToString(!0):i.text||"")}i=t.join("\n")}const o=t.slot,s=o?o.querySelectorAll("canvas"):[];return{tier:t.renderer&&t.renderer.tier||"dom",text:i,fontFamily:e.options&&e.options.fontFamily||null,cols:e.cols,rows:e.rows,canvases:s.length,canvasSize:s.length?[s[0].width,s[0].height]:null,slotSize:o?[o.clientWidth,o.clientHeight]:null}}};
3
+ "use strict";const ptyWinSessions=new Map;let ptyWinNextLabel=1,ptyWinActive=null;function ptyWinId(){return window.crypto&&"function"==typeof window.crypto.randomUUID?window.crypto.randomUUID():`pty-${Date.now()}-${Math.random().toString(36).slice(2)}`}let ptyWinFitting=null;function ptyPad(t,e,n){const i=t=>{const e=parseFloat(t);return Number.isFinite(e)?e:0};return i(t&&t[e])+i(t&&t[n])}function ptyWinFit(t,e){const n=t&&t._core,i=n&&n._renderService&&n._renderService.dimensions&&n._renderService.dimensions.css.cell;if(!i||!i.width||!i.height)return null;const o=ptyPad(getComputedStyle(e),"paddingLeft","paddingRight"),s=ptyPad(getComputedStyle(e),"paddingTop","paddingBottom"),r=Math.max(2,Math.floor((e.clientWidth-o)/i.width)),l=Math.max(1,Math.floor((e.clientHeight-s)/i.height));if(r!==t.cols||l!==t.rows){ptyWinFitting=t;try{t.resize(r,l)}finally{ptyWinFitting=null}}return{cols:r,rows:l}}function ptyWinFontFamily(){return getComputedStyle(document.documentElement).getPropertyValue("--font-mono").trim()||"ui-monospace, SFMono-Regular, Menlo, monospace"}function ptyWinSettle(t,e,n){let i=null,o=0;const s=()=>{if(!t||t.closed||t.term!==e)return;if(o>=3)return;o+=1;let r=null;try{const t=ptyWinFit(e,n);r=t?`${t.cols}x${t.rows}`:null}catch{return}r&&r===i||(i=r,"function"==typeof requestAnimationFrame&&requestAnimationFrame(s))};"function"==typeof requestAnimationFrame&&requestAnimationFrame(s)}function ptyWinActivate(t){if(t&&!t.closed){for(const e of ptyWinSessions.values()){const n=e===t;e.slot&&(e.slot.hidden=!n),e.tab&&(e.tab.classList.toggle("is-active",n),e.tab.setAttribute("aria-selected",n?"true":"false"))}if(ptyWinActive=t.id,t.term&&t.slot){const e=t.term,n=t.slot;requestAnimationFrame(()=>{t.closed||ptyWinFit(e,n)})}t.term&&t.term.focus()}}function ptyWinTeardown(t){if(t){t.closed=!0;try{t.unsubscribe&&t.unsubscribe()}catch{}try{t.ro&&t.ro.disconnect()}catch{}try{window.aegis.pty.cancel(t.id)}catch{}if(ptyWinSessions.delete(t.id),t.tab&&t.tab.remove&&t.tab.remove(),t.slot&&t.slot.remove&&t.slot.remove(),ptyWinActive===t.id){const t=ptyWinSessions.values().next().value||null;ptyWinActive=null,t&&ptyWinActivate(t)}}}function ptyWinClose(t){const e=t?ptyWinSessions.get(t):ptyWinActive&&ptyWinSessions.get(ptyWinActive);e&&ptyWinTeardown(e),0===ptyWinSessions.size&&window.aegis&&"function"==typeof window.aegis.closePtyWindow&&window.aegis.closePtyWindow()}function ptyWinFail(t,e){const n=document.createElement("div");n.className="pty-win-note",n.textContent=e,t.slot&&t.slot.appendChild(n)}function ptyWinAttachRenderer(t){const e="undefined"!=typeof window?window.aegisPtyRenderer:null;return e&&"function"==typeof e.attach?e.attach(t,{win:window,bridge:window.aegis}):{tier:"dom",addon:null,tried:["dom"],errors:[]}}function ptyWinTitleName(t){const e="undefined"!=typeof window&&window.aegisPtyRenderer;if(e&&"function"==typeof e.titleName)return e.titleName(t);const n=String(null==t?"":t).replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim().replace(/^[\u2800-\u28FF]\s*/,"").split(" · AEGIS Code")[0].trim();return"AEGIS Code"===n?"":n}function ptyWinHasActiveElsewhere(t){for(const e of ptyWinSessions.values())if(e!==t&&!e.closed&&e.slot&&!e.slot.hidden)return!0;return!1}function ptyWinStart(){if("undefined"==typeof window||!window.aegis||!window.aegis.pty)return document.getElementById("pty-win-body").innerHTML='<div class="pty-win-note">the terminal bridge is not available in this build</div>',null;if("function"!=typeof window.Terminal)return document.getElementById("pty-win-body").innerHTML='<div class="pty-win-note">xterm.js is missing from this build — the terminal cannot render</div>',null;const t=document.getElementById("pty-win-tabs"),e=document.getElementById("pty-win-body"),n=ptyWinId(),i=String(ptyWinNextLabel++),o=document.createElement("button");o.type="button",o.className="pty-win-tab",o.setAttribute("role","tab"),o.textContent=i,o.title=`Terminal ${i} — click to switch, middle-click to close`;const s=document.createElement("div");s.className="pty-win-slot",s.hidden=!0;const r={id:n,label:i,name:"",tab:o,slot:s,term:null,unsubscribe:null,ro:null,closed:!1};ptyWinSessions.set(n,r),o.addEventListener("click",()=>ptyWinActivate(r)),o.addEventListener("auxclick",t=>{1===t.button&&(t.preventDefault(),ptyWinClose(n))}),t.appendChild(o),e.appendChild(s);const l=new window.Terminal({convertEol:!0,cursorBlink:!1,fontSize:13,fontFamily:ptyWinFontFamily(),allowProposedApi:!0});r.term=l,l.open(s),r.renderer=ptyWinAttachRenderer(l),ptyWinFit(l,s),ptyWinSettle(r,l,s);const c=document.fonts;return c&&c.ready&&"function"==typeof c.ready.then&&c.ready.then(()=>{r.closed||ptyWinFit(l,s)}),r.unsubscribe=window.aegis.pty.onEvent(n,t=>{const e=t&&t.p;e&&("data"===e.kind?l.write(e.chunk):"exit"===e.kind&&l.write("\r\n[process exited]\r\n"))}),"function"==typeof ResizeObserver&&(r.ro=new ResizeObserver(()=>{ptyWinFitting!==l&&ptyWinFit(l,s)}),r.ro.observe(e)),"function"==typeof l.onTitleChange&&l.onTitleChange(t=>{const e=ptyWinTitleName(t);if(!e)return;r.name=e,o.textContent!==e&&(o.textContent=e),o.title=`${e} — click to switch, middle-click to close`;const n=s.ownerDocument;n&&!ptyWinHasActiveElsewhere(r)&&(n.title=`${e} — AEGIS Code`)}),l.onData(t=>window.aegis.pty.write(n,t)),l.onResize(({cols:t,rows:e})=>window.aegis.pty.resize(n,t,e)),window.aegis.pty.exec(n,{cols:l.cols,rows:l.rows}).then(t=>{t&&t.ok||l.write(`\r\n[could not start: ${t&&t.e&&t.e.msg||"unknown error"}]\r\n`)}),ptyWinActivate(r),r}window.addEventListener("DOMContentLoaded",()=>{const t=document.getElementById("pty-win-new");t&&t.addEventListener("click",()=>ptyWinStart()),window.addEventListener("keydown",t=>{t.ctrlKey&&t.shiftKey&&("T"===t.key||"t"===t.key)?(t.preventDefault(),ptyWinStart()):t.ctrlKey&&t.shiftKey&&("W"===t.key||"w"===t.key)&&(t.preventDefault(),ptyWinClose())}),ptyWinStart()}),window.aegisPtyWindow={start:ptyWinStart,close:ptyWinClose,count:()=>ptyWinSessions.size,active:()=>ptyWinActive,renderers:()=>[...ptyWinSessions.values()].map(t=>t.renderer&&t.renderer.tier||"dom"),inspect:()=>{const t=ptyWinActive?ptyWinSessions.get(ptyWinActive):null;if(!t||!t.term)return null;const e=t.term,n=e.buffer&&e.buffer.active;let i="";if(n&&"function"==typeof n.getLine){const t=[];for(let e=0;e<n.length;e+=1){const i=n.getLine(e);i&&t.push("function"==typeof i.translateToString?i.translateToString(!0):i.text||"")}i=t.join("\n")}const o=t.slot,s=o?o.querySelectorAll("canvas"):[];return{tier:t.renderer&&t.renderer.tier||"dom",text:i,fontFamily:e.options&&e.options.fontFamily||null,cols:e.cols,rows:e.rows,canvases:s.length,canvasSize:s.length?[s[0].width,s[0].height]:null,slotSize:o?[o.clientWidth,o.clientHeight]:null}}};
@@ -686,13 +686,42 @@ main {
686
686
  padding: 24px clamp(16px, 4vw, 48px) 48px;
687
687
  }
688
688
 
689
+ /* The terminal face as a page (index.html #pty-view). Same page box as
690
+ Settings/Automations, but it does not cap at 56rem: a terminal is measured in
691
+ columns, and a page that stops halfway across the canvas would spend its
692
+ width on margins instead of on the shell. */
693
+ #pty-view {
694
+ display: flex;
695
+ flex-direction: column;
696
+ gap: 12px;
697
+ flex: 1;
698
+ min-width: 0;
699
+ background: var(--bg);
700
+ overflow: hidden;
701
+ padding: 24px clamp(16px, 4vw, 48px) 24px;
702
+ }
703
+
704
+ /* The mount is the whole page under the back button, and it must be a
705
+ measurable box: pty-panel.js sizes xterm from its container's client size. */
706
+ .pty-view-mount {
707
+ display: flex;
708
+ flex: 1 1 auto;
709
+ min-height: 0;
710
+ min-width: 0;
711
+ }
712
+
713
+ .pty-view-mount .pty-panel-overlay.is-page {
714
+ flex: 1 1 auto;
715
+ }
716
+
689
717
  /* Same author-stylesheet-beats-UA-stylesheet gotcha noted elsewhere in this
690
718
  sheet (e.g. `.autonomous-controls[hidden]`): the `display: flex` two rules
691
719
  up outranks the UA default for `[hidden]` regardless of specificity, so
692
720
  the attribute needs its own explicit override. */
693
721
  #settings-view[hidden],
694
722
  #automations-view[hidden],
695
- #conversations-view[hidden] {
723
+ #conversations-view[hidden],
724
+ #pty-view[hidden] {
696
725
  display: none;
697
726
  }
698
727
 
@@ -6091,6 +6120,29 @@ body.keys-open {
6091
6120
  background: rgba(0, 0, 0, 0.5);
6092
6121
  }
6093
6122
 
6123
+ /* Hosted in #pty-view instead of over the window: no backdrop, no fixed
6124
+ positioning, no centred 900x560 card — the panel IS the page, so it fills
6125
+ the mount and the canvas supplies the chrome around it. Everything below
6126
+ the overlay rule (header, tabs, +, ×, xterm body) is shared unchanged. */
6127
+ .pty-panel-overlay.is-page {
6128
+ position: static;
6129
+ inset: auto;
6130
+ z-index: auto;
6131
+ background: none;
6132
+ min-height: 0;
6133
+ min-width: 0;
6134
+ }
6135
+
6136
+ .pty-panel-overlay.is-page .pty-panel {
6137
+ width: 100%;
6138
+ height: 100%;
6139
+ max-width: none;
6140
+ max-height: none;
6141
+ border-radius: var(--r-md, var(--r-lg));
6142
+ box-shadow: none;
6143
+ border: 1px solid var(--border, rgba(255, 255, 255, 0.12));
6144
+ }
6145
+
6094
6146
  .pty-panel {
6095
6147
  display: flex;
6096
6148
  flex-direction: column;
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
4
- "use strict";const path=require("node:path");for(const e of[process.stdout,process.stderr])e.on("error",e=>{throw!e||"EPIPE"!==e.code&&"ERR_STREAM_DESTROYED"!==e.code||process.exit(0),e});const HELP="aegiscode — AEGIS in your shell.\n\nUsage:\n aegiscode interactive session\n aegiscode \"question\" one-shot, then exit\n aegiscode -p \"question\" same, explicit\n echo \"q\" | aegiscode -p - read the prompt from stdin\n\nAccount:\n aegiscode connect sign this machine in — registers a device account\n if it has none (idempotent per machine), and that\n key is what cloud memory and the record vault use\n aegiscode connect --status is this machine connected? (--json; exit 1 if not)\n aegiscode connect --logout sign out (forget the saved key here)\n aegiscode login [<key>] save your AEGIS API key (prompts, no echo, if omitted)\n aegiscode logout remove the saved key\n aegiscode key status show which key is in use and where it came from\n aegiscode topup [EUR] add credit to the token bank (2..1000, default 10):\n opens the payment page, then confirms the credit\n here — the account this machine auto-provisions\n has no browser session, so the page cannot show it\n\nAutomation:\n aegiscode autonomous help run queued tasks with no terminal at all\n aegiscode dream --since 7d build the local wiki over recent transcripts\n + cloud notes (offline, --dry-run to preview)\n aegiscode mcp install put AEGIS inside VS Code / Cursor / Zed /\n Cline / Windsurf / … ('mcp list' shows them)\n aegiscode mcp status which editors are configured, and do they work\n aegiscode mcp shim OpenAI-compatible endpoint for clients that\n take a base URL but speak no MCP\n aegiscode mcp help all subcommands and their flags\n\nAttestation (φ(α) — a sealed record of what a session was):\n aegiscode fingerprint status which authorship key is in use, and where\n aegiscode fingerprint keygen mint a private key (0600, never printed)\n aegiscode fingerprint mint seal the last session as a record\n aegiscode fingerprint verify <file> recompute a record's attestation\n aegiscode fingerprint backup --to DIR copy the key somewhere safe\n aegiscode fingerprint publish [<file>] publish a record, link the copy\n aegiscode fingerprint anchor <file> is the published copy still ours?\n aegiscode fingerprint vault --audit what is in the vault, and is a key in it\n aegiscode fingerprint help all subcommands and their flags\n\nCode protection (the agent-key gate on aegiscodex-dev / aegiscode-plugin):\n aegiscode gate status can THIS machine edit a gated tree?\n aegiscode gate import-key [PATH] adopt a key dropped at PATH\n (default ~/Downloads/agent.key),\n then delete PATH\n aegiscode gate bind-machine trust this machine in the manifest\n aegiscode gate rotate mint a fresh key, burn the old one\n aegiscode gate add-key add another key (from stdin)\n aegiscode gate lock-status the server-side half of the lock\n aegiscode gate help all subcommands and their flags\n\nProvenance (this binary, and whether it is still the published one):\n aegiscode provenance licence, source, and a self-check of\n this build against the published seal\n (--json for scripts; exit 1 if a\n sealed unit has moved)\n\nOptions:\n -m, --model <id> pin a model id (see /models; default: server choice)\n --class <name> run this turn on aegis|byok|local|pro. The one-shot\n path had no way to state a class, so '-p' always ran\n the pooled route (DEFAULT_CLASS) no matter what was\n pinned — a headless turn could not use a BYOK key at\n all. '--class byok' needs '--model <provider>:<model>'.\n --base <url> API base (default $AEGIS_API_BASE or aegiscloud.org)\n --key <key> API key for THIS RUN only — it is not saved. Use\n \"aegiscode login\" to store one for good.\n --json with -p: emit JSON instead of text\n --no-stream buffer the answer instead of streaming it\n --max-tokens <n> output ceiling hint\n --light light theme\n --width <cols> force a render width (useful for piping/logs)\n --automode skip tool-approval prompts (exec/writeFile/editFile\n run without asking) — same as the in-session /automode\n --yolo alias of --automode (the pre-rename spelling)\n --ascii draw with the ASCII mark and glyph set (no Unicode).\n Same as AEGIS_ART=ascii; /terminal ascii toggles it\n mid-session.\n --no-color no colour at all (same as NO_COLOR=1)\n --terminal print the resolved terminal capabilities and exit —\n one report shape on every platform, so pasting it\n from PowerShell (or into a bug report) reads the same\n as pasting it from zsh\n -c, --continue skip onboarding and resume the most recent session\n -h, --help this text\n -v, --version print the version\n\nIn-session: type /help for commands, /quit to exit, esc/ctrl+c to interrupt a\nrunning call. Plain text is a prompt (identical to /ask) — a question that\nneeds a file read, a shell command, or an edit is handled the same turn.\n";function parseArgs(e){const s={model:null,base:null,key:null,json:!1,class:null,stream:!0,maxTokens:void 0,light:!1,width:null,yolo:!1,ascii:null,color:null,terminal:!1,continue:!1,prompt:null,help:!1,version:!1,command:null,commandArg:null,commandArgv:null},t=[],n=e[0];if(n&&!n.startsWith("-")&&ACCOUNT_COMMANDS.has(n)){const t=e[1];s.command=n,s.commandArg=t&&!t.startsWith("-")?t:null,e=e.slice(s.commandArg?2:1)}else if("autonomous"===n){const t=e[1]&&!e[1].startsWith("-")?e[1]:"help";s.command="autonomous",s.commandArg=t,s.commandArgv=e.slice(e[1]&&!e[1].startsWith("-")?2:1),e=[]}else if("mcp"===n){const t=e[1]&&!e[1].startsWith("-")?e[1]:"status";s.command="mcp",s.commandArg=t,s.commandArgv=e.slice(e[1]&&!e[1].startsWith("-")?2:1),e=[]}else if("fingerprint"===n){const t=e[1]&&!e[1].startsWith("-")?e[1]:"status";s.command="fingerprint",s.commandArg=t,s.commandArgv=e.slice(e[1]&&!e[1].startsWith("-")?2:1),e=[]}else if("gate"===n){const t=e[1]&&!e[1].startsWith("-")?e[1]:"status";s.command="gate",s.commandArg=t,s.commandArgv=e.slice(e[1]&&!e[1].startsWith("-")?2:1),e=[]}else if("dream"===n)s.command="dream",s.commandArgv=e.slice(1),e=[];else if("connect"===n)s.command="connect",s.commandArg=null,s.commandArgv=e.slice(1),e=[];else if("provenance"===n)s.command="provenance",e=e.slice(1);else if("topup"===n){const t=e[1]&&!e[1].startsWith("-")?e[1]:null;s.command="topup",s.commandArg=t,e=t?e.slice(2):e.slice(1)}for(let n=0;n<e.length;n++){const o=e[n],r=()=>{const s=e[++n];if(void 0===s)throw new Error(`${o} needs a value`);return s};switch(o){case"-h":case"--help":s.help=!0;break;case"-v":case"--version":s.version=!0;break;case"-p":case"--print":s.prompt=e[n+1]&&!e[n+1].startsWith("-")?r():"-";break;case"-m":case"--model":s.model=r();break;case"--class":s.class=r();break;case"--base":s.base=r();break;case"--key":s.key=r();break;case"--json":s.json=!0;break;case"--no-stream":s.stream=!1;break;case"--stream":s.stream=!0;break;case"--max-tokens":s.maxTokens=Number(r());break;case"--light":s.light=!0;break;case"--automode":case"--yolo":s.yolo=!0;break;case"-c":case"--continue":s.continue=!0;break;case"--width":s.width=Number(r());break;case"--ascii":s.ascii=!0;break;case"--unicode":s.ascii=!1;break;case"--no-color":case"--no-colour":s.color=!1;break;case"--color":case"--colour":s.color=!0;break;case"--terminal":case"--caps":s.terminal=!0;break;default:if(o.startsWith("-")&&"-"!==o)throw new Error(`unknown option: ${o}`);t.push(o)}}return!s.prompt&&t.length&&(s.prompt=t.join(" ")),s}
4
+ "use strict";const path=require("node:path");for(const e of[process.stdout,process.stderr])e.on("error",e=>{throw!e||"EPIPE"!==e.code&&"ERR_STREAM_DESTROYED"!==e.code||process.exit(0),e});const HELP="aegiscode — AEGIS in your shell.\n\nUsage:\n aegiscode interactive session\n aegiscode \"question\" one-shot, then exit\n aegiscode -p \"question\" same, explicit\n echo \"q\" | aegiscode -p - read the prompt from stdin\n\nAccount:\n aegiscode connect sign this machine in — registers a device account\n if it has none (idempotent per machine), and that\n key is what cloud memory and the record vault use\n aegiscode connect --status is this machine connected? (--json; exit 1 if not)\n aegiscode connect --logout sign out (forget the saved key here)\n aegiscode login [<key>] save your AEGIS API key (prompts, no echo, if omitted)\n aegiscode logout remove the saved key\n aegiscode key status show which key is in use and where it came from\n aegiscode topup [EUR] add credit to the token bank (2..1000, default 10):\n opens the payment page, then confirms the credit\n here — the account this machine auto-provisions\n has no browser session, so the page cannot show it\n\nAutomation:\n aegiscode autonomous help run queued tasks with no terminal at all\n aegiscode dream --since 7d build the local wiki over recent transcripts\n + cloud notes (offline, --dry-run to preview)\n aegiscode mcp install put AEGIS inside VS Code / Cursor / Zed /\n Cline / Windsurf / … ('mcp list' shows them)\n aegiscode mcp status which editors are configured, and do they work\n aegiscode mcp shim OpenAI-compatible endpoint for clients that\n take a base URL but speak no MCP\n aegiscode mcp help all subcommands and their flags\n\nAttestation (φ(α) — a sealed record of what a session was):\n aegiscode fingerprint status which authorship key is in use, and where\n aegiscode fingerprint keygen mint a private key (0600, never printed)\n aegiscode fingerprint mint seal the last session as a record\n aegiscode fingerprint verify <file> recompute a record's attestation\n aegiscode fingerprint backup --to DIR copy the key somewhere safe\n aegiscode fingerprint publish [<file>] publish a record, link the copy\n aegiscode fingerprint anchor <file> is the published copy still ours?\n aegiscode fingerprint vault --audit what is in the vault, and is a key in it\n aegiscode fingerprint help all subcommands and their flags\n\nCode protection (the agent-key gate on aegiscodex-dev / aegiscode-plugin):\n aegiscode gate status can THIS machine edit a gated tree?\n aegiscode gate import-key [PATH] adopt a key dropped at PATH\n (default ~/Downloads/agent.key),\n then delete PATH\n aegiscode gate bind-machine trust this machine in the manifest\n aegiscode gate rotate mint a fresh key, burn the old one\n aegiscode gate add-key add another key (from stdin)\n aegiscode gate lock-status the server-side half of the lock\n aegiscode gate help all subcommands and their flags\n\nProvenance (this binary, and whether it is still the published one):\n aegiscode provenance licence, source, and a self-check of\n this build against the published seal\n (--json for scripts; exit 1 if a\n sealed unit has moved)\n\nOptions:\n -m, --model <id> pin a model id (see /models; default: server choice)\n --class <name> run this turn on aegis|byok|local|pro. The one-shot\n path had no way to state a class, so '-p' always ran\n the pooled route (DEFAULT_CLASS) no matter what was\n pinned — a headless turn could not use a BYOK key at\n all. '--class byok' needs '--model <provider>:<model>'.\n --base <url> API base (default $AEGIS_API_BASE or aegiscloud.org)\n --key <key> API key for THIS RUN only — it is not saved. Use\n \"aegiscode login\" to store one for good.\n --json with -p: emit JSON instead of text\n --no-stream buffer the answer instead of streaming it\n --max-tokens <n> output ceiling hint\n --light light theme\n --width <cols> force a render width (useful for piping/logs)\n --automode skip tool-approval prompts (exec/writeFile/editFile\n run without asking) — same as the in-session /automode\n --yolo alias of --automode (the pre-rename spelling)\n --ascii draw with the ASCII mark and glyph set (no Unicode).\n Same as AEGIS_ART=ascii; /terminal ascii toggles it\n mid-session.\n --no-color no colour at all (same as NO_COLOR=1)\n --terminal print the resolved terminal capabilities and exit —\n one report shape on every platform, so pasting it\n from PowerShell (or into a bug report) reads the same\n as pasting it from zsh\n -c, --continue skip onboarding and resume the most recent session\n --session-id <id> resume that one stored session (the window's\n Sessions list passes this when you open a CLI row)\n -h, --help this text\n -v, --version print the version\n\nIn-session: type /help for commands, /quit to exit, esc/ctrl+c to interrupt a\nrunning call. Plain text is a prompt (identical to /ask) — a question that\nneeds a file read, a shell command, or an edit is handled the same turn.\n";function parseArgs(e){const s={model:null,base:null,key:null,json:!1,class:null,stream:!0,maxTokens:void 0,light:!1,width:null,yolo:!1,ascii:null,color:null,terminal:!1,continue:!1,sessionId:null,prompt:null,help:!1,version:!1,command:null,commandArg:null,commandArgv:null},t=[],n=e[0];if(n&&!n.startsWith("-")&&ACCOUNT_COMMANDS.has(n)){const t=e[1];s.command=n,s.commandArg=t&&!t.startsWith("-")?t:null,e=e.slice(s.commandArg?2:1)}else if("autonomous"===n){const t=e[1]&&!e[1].startsWith("-")?e[1]:"help";s.command="autonomous",s.commandArg=t,s.commandArgv=e.slice(e[1]&&!e[1].startsWith("-")?2:1),e=[]}else if("mcp"===n){const t=e[1]&&!e[1].startsWith("-")?e[1]:"status";s.command="mcp",s.commandArg=t,s.commandArgv=e.slice(e[1]&&!e[1].startsWith("-")?2:1),e=[]}else if("fingerprint"===n){const t=e[1]&&!e[1].startsWith("-")?e[1]:"status";s.command="fingerprint",s.commandArg=t,s.commandArgv=e.slice(e[1]&&!e[1].startsWith("-")?2:1),e=[]}else if("gate"===n){const t=e[1]&&!e[1].startsWith("-")?e[1]:"status";s.command="gate",s.commandArg=t,s.commandArgv=e.slice(e[1]&&!e[1].startsWith("-")?2:1),e=[]}else if("dream"===n)s.command="dream",s.commandArgv=e.slice(1),e=[];else if("connect"===n)s.command="connect",s.commandArg=null,s.commandArgv=e.slice(1),e=[];else if("provenance"===n)s.command="provenance",e=e.slice(1);else if("topup"===n){const t=e[1]&&!e[1].startsWith("-")?e[1]:null;s.command="topup",s.commandArg=t,e=t?e.slice(2):e.slice(1)}for(let n=0;n<e.length;n++){const o=e[n],r=()=>{const s=e[++n];if(void 0===s)throw new Error(`${o} needs a value`);return s};switch(o){case"-h":case"--help":s.help=!0;break;case"-v":case"--version":s.version=!0;break;case"-p":case"--print":s.prompt=e[n+1]&&!e[n+1].startsWith("-")?r():"-";break;case"-m":case"--model":s.model=r();break;case"--class":s.class=r();break;case"--base":s.base=r();break;case"--key":s.key=r();break;case"--json":s.json=!0;break;case"--no-stream":s.stream=!1;break;case"--stream":s.stream=!0;break;case"--max-tokens":s.maxTokens=Number(r());break;case"--light":s.light=!0;break;case"--automode":case"--yolo":s.yolo=!0;break;case"-c":case"--continue":s.continue=!0;break;case"--session-id":s.sessionId=String(r());break;case"--width":s.width=Number(r());break;case"--ascii":s.ascii=!0;break;case"--unicode":s.ascii=!1;break;case"--no-color":case"--no-colour":s.color=!1;break;case"--color":case"--colour":s.color=!0;break;case"--terminal":case"--caps":s.terminal=!0;break;default:if(o.startsWith("-")&&"-"!==o)throw new Error(`unknown option: ${o}`);t.push(o)}}return!s.prompt&&t.length&&(s.prompt=t.join(" ")),s}
5
5
  /**
6
6
  * `aegiscode provenance` — what this binary is, and whether its safety files are
7
7
  * the ones that were published.
@@ -17,4 +17,4 @@
17
17
  * cheap attack must be the loud one). A fork that has deliberately rebuilt is
18
18
  * expected to regenerate the manifest and exit 0 naming itself; one that has
19
19
  * not now says so instead of staying silent.
20
- */function runProvenance(e={}){const s=require(path.join(__dirname,"..","package.json")),t=require("../src/provenance.js"),n=t.describe({version:s.version});return e.json?(process.stdout.write(JSON.stringify({product:t.IDENTITY.product,bin:t.IDENTITY.bin,version:s.version,license:t.IDENTITY.license,source:t.IDENTITY.source,homepage:t.IDENTITY.homepage,copyright:t.IDENTITY.copyright,safety:{ok:n.report.ok,checked:n.report.checked,problems:n.report.problems}},null,2)+"\n"),n.ok?0:1):(process.stdout.write(n.text),n.ok?0:1)}const ACCOUNT_COMMANDS=new Set(["login","logout","key"]);async function runAccountCommand(e,s,t={}){const n=t.stdout||process.stdout,o=t.stderr||process.stderr,r=t.stdin||process.stdin,{credentials:i,readSecret:a,maskKey:c}=loadAccountDeps();if("logout"===e||"key"===e&&["clear","remove","rm"].includes(String(s||"").toLowerCase())){const e=i.clearApiKey();return n.write(e.cleared?`aegiscode: key removed from ${e.path}\n`:"aegiscode: no saved key to remove\n"),i.legacyKeyOnDisk()&&n.write('aegiscode: note — a plaintext copy is also in config.json, written by an older AEGIS CLI; delete its "aegiscloud" block as well to finish removing it\n'),0}if("key"===e&&["status","show",""].includes(String(s||"").toLowerCase())){const e=i.keyStatus();return t.json?(n.write(JSON.stringify({configured:e.configured,source:e.source,source_label:i.sourceLabel(e.source),path:e.path,file_mode:e.fileMode,masked:e.configured?c(e.key):null,memory_token:e.memoryToken,verified_at:e.verifiedAt,plaintext_copy_in_config:e.legacyPlaintext},null,2)+"\n"),e.configured?0:1):(n.write([`key: ${e.configured?c(e.key):"not set"}`,`source: ${i.sourceLabel(e.source)}`,`file: ${e.path}${e.fileMode?` (${e.fileMode})`:""}`,"memory: "+(e.memoryToken?"token held (cloud sync ready)":"no token"),e.verifiedAt?`verified: ${e.verifiedAt}`:null,e.legacyPlaintext?"note: a plaintext copy also sits in config.json — re-save with `aegiscode login` to move it":null].filter(Boolean).join("\n")+"\n"),e.configured?0:1)}let d=s&&"status"!==s?String(s).trim():"";if(!d){if(!r.isTTY)return o.write("aegiscode: no terminal to prompt on — pass the key: `aegiscode login <api_key>`\n (or set AEGIS_API_KEY for a single run)\n"),2;d=await a("AEGIS API key (kept off screen, Enter to cancel): ",{stdin:r,stdout:n})}if(!d)return o.write("aegiscode: no key given — nothing saved\n"),2;const{createApp:l}=require("../src/app.js"),u=l({interactive:!1}),m=await u.setApiKey(d);if(!m.ok)return o.write(`aegiscode: ${m.message||"that key could not be saved"}\n`),2;const p=m.account&&(m.account.email||m.account.plan);if(n.write(`aegiscode: key saved to ${m.path}${p?` — ${p}`:""}\n`),m.error){const e=m.error.status;return o.write(`aegiscode: the account check failed: ${m.error.message}\n`),401===e||403===e?(o.write("aegiscode: the key is stored but the server refused it — re-run with a fresh key\n"),1):(o.write("aegiscode: (stored anyway — the server could not be reached to confirm it)\n"),0)}return n.write("aegiscode: verified — run `aegiscode` to start a session\n"),0}function loadAccountDeps(){const e=require("../src/credentials.js"),{readSecret:s}=require("../src/secret.js"),{maskKey:t}=require("../src/format.js");return{credentials:e,readSecret:s,maskKey:t}}function readStdin(){return new Promise(e=>{let s="";process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{s+=e}),process.stdin.on("end",()=>e(s.trim()))})}async function main(e=process.argv.slice(2)){let s;try{s=parseArgs(e)}catch(e){return process.stderr.write(`aegiscode: ${e.message}\n\n${HELP}`),2}if(s.help)return process.stdout.write(HELP),0;const t=require(path.join(__dirname,"..","package.json"));let n=!1,o=0;try{const e=require("../src/limits.js");if(n=e.armed(),n&&(o=e.refuse(),e.isPrivileged(s.command)))return o}catch{}if(s.version)return process.stdout.write(t.version+"\n"),n?o:0;try{const{resolveClientModule:e}=require("../src/shared.js"),s=require(e("env-file.js")).loadEnvFile();s.loose&&process.stderr.write(`aegiscode: ${s.file} is readable by other accounts (mode ${s.mode.toString(8)}) — consider \`chmod 600\` on it.\n`)}catch(e){process.stderr.write(`aegiscode: could not read ~/.aegiscode/.env: ${e&&e.message}\n`)}const{setCaps:r,describe:i}=require("../src/caps.js"),a={...process.env};if(!0===s.ascii&&(a.AEGIS_ART="ascii"),!1===s.ascii&&(a.AEGIS_ART="unicode"),!1===s.color&&(a.NO_COLOR="1"),!0===s.color&&(delete a.NO_COLOR,a.FORCE_COLOR="3"),s.width&&(a.AEGIS_WIDTH=String(s.width)),r(null,a),s.terminal){const e=i(),s=e.reduce((e,[s])=>Math.max(e,s.length),0);process.stdout.write(`aegiscode ${t.version} — terminal capabilities\n\n`);for(const[t,n]of e)process.stdout.write(` ${t.padEnd(s)} ${n}\n`);return process.stdout.write("\nOverride with --ascii / --color / --light / --width, or AEGIS_ART,\nAEGIS_STAR, AEGIS_COLOR, AEGIS_BACKGROUND, AEGIS_BACKGROUND_PROBE, AEGIS_VT,\nAEGIS_WIDTH (see README).\n"),0}if(s.base&&(process.env.AEGIS_API_BASE=s.base),s.key&&(process.env.AEGIS_API_KEY=s.key),"fingerprint"===s.command){const{runFingerprint:e}=require("../src/fingerprint.js");return e(s.commandArg||"status",s.commandArgv||[],{json:s.json,stdout:process.stdout,stderr:process.stderr})}if("connect"===s.command){const{runConnect:e}=require("../src/connect.js");return e(s.commandArgv||[],{json:s.json,stdout:process.stdout,stderr:process.stderr})}if("gate"===s.command){const{runGate:e}=require("../src/gate.js");return e(s.commandArg||"status",s.commandArgv||[])}if("topup"===s.command){const{runTopupCommand:e}=require("../src/topup.js");return e(s.commandArg,{json:s.json,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}if(ACCOUNT_COMMANDS.has(s.command))return runAccountCommand(s.command,s.commandArg,{json:s.json,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr});if("autonomous"===s.command){const e=require("../src/presence.js"),t=require("../src/credentials.js");e.start({credentials:t,autonomous:!0,queueDepth:e.queueDepthReader()}),process.once("exit",()=>e.stop());const{runQueueCommand:n}=require("../src/autonomous.js");return n(s.commandArg,s.commandArgv||[],{json:s.json,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}if("mcp"===s.command){const{runMcpCommand:e}=require("../src/mcp.js");return e(s.commandArg,s.commandArgv||[],{json:s.json,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}if("dream"===s.command){const{runDreamCommand:e}=require("../src/dream-cmd.js");return e(s.commandArgv||[],{stdout:process.stdout,stderr:process.stderr})}if("provenance"===s.command&&!n)return runProvenance({json:s.json});const{createApp:c}=require("../src/app.js");if(!n)try{const e=require("../src/provenance.js"),s=e.warning(e.selfCheck());s&&process.stderr.write(s)}catch{}const d=require("../src/presence.js");d.start({credentials:require("../src/credentials.js"),queueDepth:d.queueDepthReader()}),process.once("exit",()=>d.stop());let l=s.prompt;if("-"===l){if(process.stdin.isTTY)return process.stderr.write("aegiscode: -p - expects a prompt on stdin\n"),2;if(l=await readStdin(),!l)return process.stderr.write("aegiscode: empty stdin\n"),2}const u=c({model:s.model,class:s.class,stream:s.stream,light:s.light,maxTokens:s.maxTokens,...s.effort?{effort:s.effort}:{},width:s.width?()=>s.width:void 0,interactive:!l&&Boolean(process.stdin.isTTY),confirmMode:!s.yolo&&void 0,continue:s.continue});if(l)return u.runOnce(l,{json:s.json});if(!process.stdin.isTTY)return process.stderr.write('aegiscode: no terminal and no prompt. Use `aegiscode -p "question"` or pipe a prompt in.\n'),2;const m=require("../src/screen.js");m.queueExitNotice("\nResume this session with:\n aegiscode --continue (or /resume for the list)\n");const p=()=>{try{m.isAltScreen()&&m.leaveAltScreen(),m.flushExitNotice()}catch{}},h=u.runInteractive();process.once("exit",p);const g=await h;return p(),g}require.main===module&&main().then(async e=>{try{await require("../src/presence.js").flush()}catch{}process.exit(e||0)}).catch(e=>{process.stderr.write(`aegiscode: ${e&&e.message?e.message:e}\n`),process.exit(1)}),module.exports={main:main,parseArgs:parseArgs,HELP:HELP,ACCOUNT_COMMANDS:ACCOUNT_COMMANDS,runAccountCommand:runAccountCommand};
20
+ */function runProvenance(e={}){const s=require(path.join(__dirname,"..","package.json")),t=require("../src/provenance.js"),n=t.describe({version:s.version});return e.json?(process.stdout.write(JSON.stringify({product:t.IDENTITY.product,bin:t.IDENTITY.bin,version:s.version,license:t.IDENTITY.license,source:t.IDENTITY.source,homepage:t.IDENTITY.homepage,copyright:t.IDENTITY.copyright,safety:{ok:n.report.ok,checked:n.report.checked,problems:n.report.problems}},null,2)+"\n"),n.ok?0:1):(process.stdout.write(n.text),n.ok?0:1)}const ACCOUNT_COMMANDS=new Set(["login","logout","key"]);async function runAccountCommand(e,s,t={}){const n=t.stdout||process.stdout,o=t.stderr||process.stderr,r=t.stdin||process.stdin,{credentials:i,readSecret:a,maskKey:c}=loadAccountDeps();if("logout"===e||"key"===e&&["clear","remove","rm"].includes(String(s||"").toLowerCase())){const e=i.clearApiKey();return n.write(e.cleared?`aegiscode: key removed from ${e.path}\n`:"aegiscode: no saved key to remove\n"),i.legacyKeyOnDisk()&&n.write('aegiscode: note — a plaintext copy is also in config.json, written by an older AEGIS CLI; delete its "aegiscloud" block as well to finish removing it\n'),0}if("key"===e&&["status","show",""].includes(String(s||"").toLowerCase())){const e=i.keyStatus();return t.json?(n.write(JSON.stringify({configured:e.configured,source:e.source,source_label:i.sourceLabel(e.source),path:e.path,file_mode:e.fileMode,masked:e.configured?c(e.key):null,memory_token:e.memoryToken,verified_at:e.verifiedAt,plaintext_copy_in_config:e.legacyPlaintext},null,2)+"\n"),e.configured?0:1):(n.write([`key: ${e.configured?c(e.key):"not set"}`,`source: ${i.sourceLabel(e.source)}`,`file: ${e.path}${e.fileMode?` (${e.fileMode})`:""}`,"memory: "+(e.memoryToken?"token held (cloud sync ready)":"no token"),e.verifiedAt?`verified: ${e.verifiedAt}`:null,e.legacyPlaintext?"note: a plaintext copy also sits in config.json — re-save with `aegiscode login` to move it":null].filter(Boolean).join("\n")+"\n"),e.configured?0:1)}let d=s&&"status"!==s?String(s).trim():"";if(!d){if(!r.isTTY)return o.write("aegiscode: no terminal to prompt on — pass the key: `aegiscode login <api_key>`\n (or set AEGIS_API_KEY for a single run)\n"),2;d=await a("AEGIS API key (kept off screen, Enter to cancel): ",{stdin:r,stdout:n})}if(!d)return o.write("aegiscode: no key given — nothing saved\n"),2;const{createApp:l}=require("../src/app.js"),u=l({interactive:!1}),m=await u.setApiKey(d);if(!m.ok)return o.write(`aegiscode: ${m.message||"that key could not be saved"}\n`),2;const p=m.account&&(m.account.email||m.account.plan);if(n.write(`aegiscode: key saved to ${m.path}${p?` — ${p}`:""}\n`),m.error){const e=m.error.status;return o.write(`aegiscode: the account check failed: ${m.error.message}\n`),401===e||403===e?(o.write("aegiscode: the key is stored but the server refused it — re-run with a fresh key\n"),1):(o.write("aegiscode: (stored anyway — the server could not be reached to confirm it)\n"),0)}return n.write("aegiscode: verified — run `aegiscode` to start a session\n"),0}function loadAccountDeps(){const e=require("../src/credentials.js"),{readSecret:s}=require("../src/secret.js"),{maskKey:t}=require("../src/format.js");return{credentials:e,readSecret:s,maskKey:t}}function readStdin(){return new Promise(e=>{let s="";process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{s+=e}),process.stdin.on("end",()=>e(s.trim()))})}async function main(e=process.argv.slice(2)){let s;try{s=parseArgs(e)}catch(e){return process.stderr.write(`aegiscode: ${e.message}\n\n${HELP}`),2}if(s.help)return process.stdout.write(HELP),0;const t=require(path.join(__dirname,"..","package.json"));let n=!1,o=0;try{const e=require("../src/limits.js");if(n=e.armed(),n&&(o=e.refuse(),e.isPrivileged(s.command)))return o}catch{}if(s.version)return process.stdout.write(t.version+"\n"),n?o:0;try{const{resolveClientModule:e}=require("../src/shared.js"),s=require(e("env-file.js")).loadEnvFile();s.loose&&process.stderr.write(`aegiscode: ${s.file} is readable by other accounts (mode ${s.mode.toString(8)}) — consider \`chmod 600\` on it.\n`)}catch(e){process.stderr.write(`aegiscode: could not read ~/.aegiscode/.env: ${e&&e.message}\n`)}const{setCaps:r,describe:i}=require("../src/caps.js"),a={...process.env};if(!0===s.ascii&&(a.AEGIS_ART="ascii"),!1===s.ascii&&(a.AEGIS_ART="unicode"),!1===s.color&&(a.NO_COLOR="1"),!0===s.color&&(delete a.NO_COLOR,a.FORCE_COLOR="3"),s.width&&(a.AEGIS_WIDTH=String(s.width)),r(null,a),s.terminal){const e=i(),s=e.reduce((e,[s])=>Math.max(e,s.length),0);process.stdout.write(`aegiscode ${t.version} — terminal capabilities\n\n`);for(const[t,n]of e)process.stdout.write(` ${t.padEnd(s)} ${n}\n`);return process.stdout.write("\nOverride with --ascii / --color / --light / --width, or AEGIS_ART,\nAEGIS_STAR, AEGIS_COLOR, AEGIS_BACKGROUND, AEGIS_BACKGROUND_PROBE, AEGIS_VT,\nAEGIS_WIDTH (see README).\n"),0}if(s.base&&(process.env.AEGIS_API_BASE=s.base),s.key&&(process.env.AEGIS_API_KEY=s.key),"fingerprint"===s.command){const{runFingerprint:e}=require("../src/fingerprint.js");return e(s.commandArg||"status",s.commandArgv||[],{json:s.json,stdout:process.stdout,stderr:process.stderr})}if("connect"===s.command){const{runConnect:e}=require("../src/connect.js");return e(s.commandArgv||[],{json:s.json,stdout:process.stdout,stderr:process.stderr})}if("gate"===s.command){const{runGate:e}=require("../src/gate.js");return e(s.commandArg||"status",s.commandArgv||[])}if("topup"===s.command){const{runTopupCommand:e}=require("../src/topup.js");return e(s.commandArg,{json:s.json,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}if(ACCOUNT_COMMANDS.has(s.command))return runAccountCommand(s.command,s.commandArg,{json:s.json,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr});if("autonomous"===s.command){const e=require("../src/presence.js"),t=require("../src/credentials.js");e.start({credentials:t,autonomous:!0,queueDepth:e.queueDepthReader()}),process.once("exit",()=>e.stop());const{runQueueCommand:n}=require("../src/autonomous.js");return n(s.commandArg,s.commandArgv||[],{json:s.json,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}if("mcp"===s.command){const{runMcpCommand:e}=require("../src/mcp.js");return e(s.commandArg,s.commandArgv||[],{json:s.json,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}if("dream"===s.command){const{runDreamCommand:e}=require("../src/dream-cmd.js");return e(s.commandArgv||[],{stdout:process.stdout,stderr:process.stderr})}if("provenance"===s.command&&!n)return runProvenance({json:s.json});const{createApp:c}=require("../src/app.js");if(!n)try{const e=require("../src/provenance.js"),s=e.warning(e.selfCheck());s&&process.stderr.write(s)}catch{}const d=require("../src/presence.js");d.start({credentials:require("../src/credentials.js"),queueDepth:d.queueDepthReader()}),process.once("exit",()=>d.stop());let l=s.prompt;if("-"===l){if(process.stdin.isTTY)return process.stderr.write("aegiscode: -p - expects a prompt on stdin\n"),2;if(l=await readStdin(),!l)return process.stderr.write("aegiscode: empty stdin\n"),2}const u=c({model:s.model,class:s.class,stream:s.stream,light:s.light,maxTokens:s.maxTokens,...s.effort?{effort:s.effort}:{},width:s.width?()=>s.width:void 0,interactive:!l&&Boolean(process.stdin.isTTY),confirmMode:!s.yolo&&void 0,continue:s.continue,sessionId:s.sessionId||null});if(l)return u.runOnce(l,{json:s.json});if(!process.stdin.isTTY)return process.stderr.write('aegiscode: no terminal and no prompt. Use `aegiscode -p "question"` or pipe a prompt in.\n'),2;const m=require("../src/screen.js");m.queueExitNotice("\nResume this session with:\n aegiscode --continue (or /resume for the list)\n");const p=()=>{try{m.isAltScreen()&&m.leaveAltScreen(),m.flushExitNotice()}catch{}},h=u.runInteractive();process.once("exit",p);const g=await h;return p(),g}require.main===module&&main().then(async e=>{try{await require("../src/presence.js").flush()}catch{}process.exit(e||0)}).catch(e=>{process.stderr.write(`aegiscode: ${e&&e.message?e.message:e}\n`),process.exit(1)}),module.exports={main:main,parseArgs:parseArgs,HELP:HELP,ACCOUNT_COMMANDS:ACCOUNT_COMMANDS,runAccountCommand:runAccountCommand};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "7.0.61",
4
+ "version": "7.0.65",
5
5
  "description": "aegiscode — the command-line version of AEGIS One. 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",
@@ -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 readline=require("node:readline"),os=require("node:os"),{randomUUID:randomUUID}=require("node:crypto"),{createTools:createTools,createClient:createClient,usageTokens:usageTokens,usageBuckets:usageBuckets,buildSystemPrompt:buildSystemPrompt,autoProvisionApiKey:autoProvisionApiKey,provisionFailureText:provisionFailureText,trialNote:trialNote,hostEnv:hostEnv,autonomous:autonomous,claudePro:claudePro}=require("./deps.js"),{createEngine:createEngine,HOST_CLASSES:HOST_CLASSES,DEFAULT_CLASS:DEFAULT_CLASS,byokNamespace:byokNamespace,effortRung:effortRung,offeredClasses:offeredClasses,proEnabled:proEnabled}=require("./engine.js"),{GLYPH:GLYPH,VERBS:VERBS,themeOf:themeOf,RESET:RESET,THEME_TABLE:THEME_TABLE,AUTO_THEME_INDEX:AUTO_THEME_INDEX,themeIsLight:themeIsLight,reconcileThemeIndex:reconcileThemeIndex}=require("./theme.js"),{probeTerminalBackground:probeTerminalBackground}=require("./caps.js"),{LiveRegion:LiveRegion,termWidth:termWidth,w:w}=require("./screen.js"),{estimateTokensFromCells:estimateTokensFromCells}=require("./tokens.js"),{editPreview:editPreview}=require("./diff.js"),{defaultOpen:defaultOpen}=require("./diffview.js"),{parseLine:parseLine,COMMANDS:COMMANDS,visibleCommands:visibleCommands,runAutoModelSync:runAutoModelSync}=require("./commands.js"),{updateConfig:updateConfig,loadPermissions:loadPermissions,loadConfig:loadConfig,configExists:configExists,memoryPersistState:memoryPersistState,memoryPersistEnabled:memoryPersistEnabled,setMemoryPersist:setMemoryPersist,confirmPosture:confirmPosture,permissionMode:permissionMode}=require("./config.js"),credentials=require("./credentials.js"),events=require("./events.js"),cloudsync=require("./cloudsync.js"),{readSecret:readSecret}=require("./secret.js"),{normalizeModelCatalog:normalizeModelCatalog,pickerEntries:pickerEntries,catalogIds:catalogIds,providerForModel:providerForModel,withAutoRow:withAutoRow,AUTO_MODEL_ID:AUTO_MODEL_ID}=require("./models.js"),{appendHistory:appendHistory,readSessionTranscript:readSessionTranscript,readOwnSessions:readOwnSessions,setSessionTitle:setSessionTitle}=require("./history.js"),naming=require("./naming.js"),{snapshotCheckpoint:snapshotCheckpoint}=require("./checkpoint.js"),screens=require("./screens.js"),chatflow=require("./chatflow.js"),overlays=require("./overlays.js"),render=require("./render.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,maskKey:maskKey,feeBillable:feeBillable}=require("./format.js"),{resolveSkip:resolveSkip}=require("./permissions.js"),VERSION=require("../package.json").version;let _defaultSystem=null;function defaultSystemPrompt(){if(null===_defaultSystem)try{_defaultSystem=buildSystemPrompt(hostEnv({},{},null))}catch{_defaultSystem=""}return _defaultSystem||void 0}function normalizeDecision(e){const t="string"==typeof e?e.trim().toLowerCase():"";return"session"===t?"session":"once"===t||"allow"===t||"yes"===t||"approve"===t||"approved"===t?"once":"deny"}const PROVIDER_REFUSAL_PATTERNS=Object.freeze([/^invalid api key\b/i,/^fix external api key\b/i,/^you've hit your session limit\b/i,/^you have hit your session limit\b/i,/^provider request timed out\b/i,/^insufficient (?:credit|balance|quota)\b/i,/^rate limit(?:ed)?\b/i,/^unauthorized\b/i]);function providerRefusal(e,t){if("string"!=typeof e)return null;const n=t&&(t.total_tokens||0),r=t&&(t.output_tokens||t.completion_tokens||0);if(n>0||r>0)return null;const o=e.trim();if(!o||o.length>160||o.includes("\n"))return null;for(const e of PROVIDER_REFUSAL_PATTERNS)if(e.test(o))return o;return null}function briefArgs(e){let t;try{t="string"==typeof e?e:JSON.stringify(e??"")}catch{t=String(e)}return t=String(t).replace(/\s+/g," ").trim(),t.length>140?`${t.slice(0,137)}...`:t}function createApp(e={}){const t={model:null,stream:!0,light:!1,maxTokens:void 0,system:void 0,interactive:!0,...e},n=e.out||process.stdout,r=e.err||process.stderr,o=e.client||createClient(credentials.clientOptions({channel:"cli"})),{createLocalWiki:s}=require("./dream-cmd.js"),{TOOLS:i,toolList:a}=e.tools||createTools(o,{localWiki:s()});let l=!1,c="";async function d(){const e=await autoProvisionApiKey(o,credentials,{app:"cli"});return c=e.key?"":provisionFailureText(e),e}async function u(){if(o.apiKey||l)return;l=!0;const e=await d();e.key&&Y(render.renderNotice(b(),"info","auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.`))}let m=!1!==e.confirmMode,f=(()=>{try{return autonomous.autoRoundsDefault(process.env)}catch{return!0}})();const p=e.engine||createEngine({client:o,getClass:()=>g.modelClass,getProEnabled:()=>{try{return proEnabled(loadConfig())}catch{return!1}},getConfirmMode:()=>{if(void 0!==e.confirmMode)return m;try{const e=resolveSkip({env:process.env,interactive:Boolean(process.stdin.isTTY&&process.stdout.isTTY)});if(e.warned&&!skipEnvWarned&&(skipEnvWarned=!0,process.stderr.write(`aegiscode: ${e.warning}\n`)),e.skip)return!1}catch{}try{return confirmPosture().enabled}catch{return m}},getPermissionMode:()=>{try{return permissionMode()}catch{return null}}}),y=e=>"function"==typeof p.classLabel?p.classLabel(e):String(e||""),h=()=>e.width?e.width():termWidth(),g={light:t.light,model:t.model,modelClass:DEFAULT_CLASS,effort:null,thinking:!1,recallDeep:!1,themeIndex:t.light?2:AUTO_THEME_INDEX,vim:!1,stream:t.stream,cwd:process.cwd(),lastRecap:null,sessionId:randomUUID()};g.themeIndex===AUTO_THEME_INDEX&&(g.light=themeIsLight(AUTO_THEME_INDEX));const k=[];let v=!1;const b=()=>({light:g.light}),S={turns:0,calls:0,tokens:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,cost:0,balance:null,seenLedgerRows:new Map,ledgerBaselined:!1,startedAt:Date.now()};let T=null,E=!1;function C(e){if(!e||"object"!=typeof e)return null;if("usage"!==e.kind)return null;const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6;return Number.isFinite(t)?Math.abs(t):null}function I(e){return[e.created_at||"",e.kind||"",null!=e.amount_eur?e.amount_eur:"",null!=e.charged_micros?e.charged_micros:"",null!=e.id?e.id:"",null!=e.note?e.note:""].join("|")}async function N(){try{const e=await o.tokenBankBalance(),t=Number(e.balance_eur);Number.isFinite(t)&&(S.balance=t);let n=null;const r=Array.isArray(e.ledger)?e.ledger:[],s=new Map;for(const e of r){const t=I(e),n=s.get(t);n?n.n+=1:s.set(t,{n:1,row:e})}for(const[e,{n:t,row:r}]of s){const o=S.seenLedgerRows.get(e)||0;if(S.seenLedgerRows.set(e,t),!S.ledgerBaselined)continue;const s=t-o;if(s<=0)continue;const i=C(r);null!=i&&i>0&&(S.cost+=i*s,null==n&&(n=i))}return S.ledgerBaselined=!0,{balance:S.balance,lastCost:n}}catch{return null}}async function A(e,{verify:t=!0}={}){const n=credentials.saveApiKey(e);if(!n.ok)return n;o.setApiKey(n.key),R.models=[],R.at=0;let r=null,s=null;if(t)try{const e=await o.verifyApiKey()||{};r=e;const t={verifiedAt:(new Date).toISOString()};e.memory_token&&(t.memoryToken=e.memory_token),e.plan&&(t.plan=e.plan),t.account={plan:e.plan||null,email:e.email||null,valid:!1!==e.valid},credentials.writeCredentials(t),e.plan&&(S.plan=e.plan),e.email&&(S.account={...S.account||{},email:e.email})}catch(e){s=e}return{...n,account:r,error:s}}function P(){const e=credentials.clearApiKey();return o.setApiKey(""),R.models=[],R.at=0,e}function x(){try{return memoryPersistEnabled()}catch{return!0}}function M(){try{return memoryPersistState()}catch{return{enabled:!0,source:"default",explicit:!1}}}function O(e){return setMemoryPersist(e)}function L(){try{return"config"!==credentials.resolveApiKey().source?[]:credentials.adoptLegacy().adopted}catch{return[]}}const _=3e5,R={at:0,models:[]},$={at:0,models:[],declared:""};async function K({force:e=!1}={}){const t=function(){try{if("function"!=typeof p.userModels)return"";const e=(p.userModels()||{}).map||{};return JSON.stringify(Object.keys(e).sort().map(t=>[t,e[t]]))}catch{return""}}(),n=$.models.length&&Date.now()-$.at<_&&t===$.declared;if(!e&&n)return $.models;if("function"!=typeof p.listModels)return[];const r=await p.listModels("byok");return $.models=(r&&r.models||[]).map(e=>({...e,note:e.configured?"key on this machine":`no key — /byok-key ${e.provider}`})),$.at=Date.now(),$.declared=t,$.models}async function D(e){const t=U();if(e&&!t.includes(e)&&HOST_CLASSES.includes(e))return[];const n=t.includes(e)?e:g.modelClass;try{if("byok"===n){const e=await K();if(!R.models.length)try{await H()}catch{}return q(e,n)}if("pro"===n){const e=await p.listModels("pro");return(e&&e.models||[]).map(e=>({...e,cls:"pro"}))}if("aegis"!==n){const e=await p.listModels(n);return e&&e.models||[]}return await H()}catch{return[]}}function j(){return withAutoRow(pickerEntries(R.models)).map(e=>({...e,cls:"aegis"}))}function q(e,t){const n=U(),r=n.includes(t)?t:g.modelClass;if("pro"===t&&!n.includes("pro"))return[];if("pro"===r)return pickerEntries(claudePro.PRO_MODELS.map(e=>({id:e.id,label:e.label,note:e.note}))).map(e=>({...e,cls:"pro"}));if("byok"!==r)return j();const o=Array.isArray(e)?e.map(e=>({...e,cls:"byok"})):pickerEntries($.models).map(e=>({...e,cls:"byok"}));return[...j(),...o]}function B(){return new Set(claudePro.PRO_MODELS.map(e=>String(e.id).toLowerCase()))}function U(){try{return offeredClasses(proEnabled(loadConfig()))}catch{return offeredClasses(!1)}}async function H({force:e=!1}={}){const t=R.models.length&&Date.now()-R.at<_;if(!e&&t)return R.models;const n=await o.listModels();return R.models=normalizeModelCatalog(n&&n.models),R.at=Date.now(),R.models}async function F(){const e=g.model;if(!e)return null;if("byok"===g.modelClass)return String(e).includes(":")?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" belongs to the pooled class — on BYOK an id is "<provider>:<model>"; pin cleared, /models lists what this machine can relay.`)),e);if("pro"===g.modelClass){if(!B().has(String(e).toLowerCase()))return g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" is not one the Claude Code CLI resolves — pin cleared, the CLI will choose; /models lists the aliases (${claudePro.PRO_MODELS.map(e=>e.id).join(", ")}).`)),e;let t=!0;try{t=!!claudePro.claudeProStatus({env:process.env}).credentialPresent}catch{t=!0}return t?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" needs a Claude Pro subscription or an ANTHROPIC_API_KEY, and this host has neither — pin cleared. Run \`claude /login\`, export a console key, or \`/class pro off\`.`)),e)}let t;try{t=await H()}catch{return null}return t.length?String(e).trim().toLowerCase()===AUTO_MODEL_ID||catalogIds(t).has(String(e).toLowerCase())?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" is not advertised by AEGIS Cloud — pin cleared, the pool will choose; /models lists what you can pin.`)),e):null}function W(){return render.renderBanner(b(),{width:h(),version:VERSION,model:g.model||"server default",base:o.apiBase,key:maskKey(o.apiKey),stream:g.stream})}function Y(e){const t="string"==typeof e?[e]:e;for(const e of t)n.write(e+"\n")}async function V(e,{history:o=[],presenter:s=null,signal:i=null}={}){const a=Date.now(),l=!s&&t.interactive&&t.stream&&n.isTTY?new LiveRegion(n):null;let c=0,d=0,u="",m=0,f=0,y=VERBS[Math.floor(Math.random()*VERBS.length)],k=!1,v=!1;const S=()=>{l&&l.update([render.renderWorking(b(),{tick:c++,verb:y,elapsedMs:Date.now()-a,streamed:estimateTokensFromCells(d+m)+f,streamedFloor:f>0})])},E=l?setInterval(S,90):null;E&&E.unref&&E.unref(),S();const C=s||{},I=new Map,N=randomUUID();T=N;let A=!1;const P=()=>{A=!0,p.cancel(N)},x=()=>P();process.once("SIGINT",x),i&&(i.aborted?P():i.addEventListener("abort",P,{once:!0}));const M=e=>(r.write(`aegiscode: ${e.tool} needs confirmation but this run has no prompt for it — denied (pass --automode (alias --yolo) to auto-approve mutating tools).\n`),Promise.resolve("deny")),O=()=>Promise.resolve(!1),L=e=>{if(e){if(e.thinkingTokens&&(f+=e.thinkingTokens,k||(k=!0,y="Reasoning"),(e=>{C.thinkingTokens&&C.thinkingTokens(e)})(e.thinkingTokens),S()),e.reasoning&&(m+=w(e.reasoning),k||(k=!0,y="Reasoning",S()),(e=>{C.reasoning&&C.reasoning(e)})(e.reasoning)),e.delta&&(d+=w(e.delta),u+=e.delta,(e=>{if(C.text)return C.text(e);l&&c%2==0&&S()})(e.delta)),e.tool&&(v=!0,(e=>{if(C.tool)return C.tool(e);l&&l.clear();const t=(e=>{const t=e&&void 0!==e.id?`id:${e.id}`:`${e&&e.name}:${JSON.stringify(e&&e.args)}`;return I.has(t)||I.set(t,editPreview(e&&e.name,e&&e.args,{cwd:process.cwd()})),I.get(t)})(e);Y(render.renderTurn(b(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:defaultOpen(t)},h())),S()})(e.tool)),e.approval){const t=e.approval;l&&l.clear();const n=C.approval||M;Promise.resolve(n(t)).catch(()=>"deny").then(e=>p.respondApproval(t.id,normalizeDecision(e)))}if(e.rounds){const t=e.rounds;l&&l.clear();const n=C.rounds||O;Promise.resolve(n(t)).catch(()=>!1).then(e=>p.respondRoundsAsk(t.id,!0===e))}}};try{const n=await p.chat({prompt:e,messages:o,model:g.model||void 0,system:t.system||defaultSystemPrompt(),maxTokens:t.maxTokens,effort:effortRung(g.effort),recallDeep:!0===g.recallDeep||void 0,stream:!1!==g.stream,sessionId:N,sessionKey:g.sessionId,rootSessionId:g.sessionId,roundsAsk:Boolean(C.rounds)},L),r=n.choices&&n.choices[0]||{};return{text:r.message&&r.message.content||u,usage:n.usage||null,model:n.model||g.model||null,ms:Date.now()-a,interrupted:A,reasoningChars:m,usedTools:v}}catch(e){if(A&&u)return{text:u,usage:null,model:g.model||null,ms:Date.now()-a,interrupted:!0,reasoningChars:m,usedTools:v};throw e}finally{E&&clearInterval(E),process.removeListener("SIGINT",x),i&&i.removeEventListener("abort",P),l&&l.clear(),T=null}}function G(e){Y(render.renderTurn(b(),e,h()))}async function z(e,{label:t="you"}={}){if(!e)return void Y(render.renderNotice(b(),"warn","nothing to ask — give /ask a prompt"));if(o.apiKey||await u(),!o.apiKey)return void Y(render.renderNotice(b(),"error",`no AEGIS account key — ${credentials.HOW_TO_SET} (or set $${credentials.KEY_ENV})`));const n=k.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.text}));let r;G({role:"user",text:e,label:t}),k.push({role:"user",text:e});try{r=await V(e,{history:n})}catch(t){return ae(e,{text:"",error:t.message},"error"),void Y(render.renderTurn(b(),{role:"error",text:t.message},h()))}r.text&&k.push({role:"assistant",text:r.text});const s=ie(r);let i=null;try{const e=await N();i=e?e.lastCost:null}catch{}ae(e,r,r.interrupted?"stopped":r.error?"error":"done",i),G({role:"assistant",text:r.text||"(the pool returned no text — see /balance for what it charged)",meta:{model:r.model,tokens:s,usage:null==r.usage?null:usageBuckets(r.usage),eur:i,ms:r.ms,calls:1}}),r.interrupted&&Y(render.renderNotice(b(),"warn","interrupted — the pool may still be running and billing this call"))}async function X(e,t){const n=i[e];if(!n)throw new Error(`unknown tool: ${e}`);if(o.apiKey||await u(),!o.apiKey)throw new Error(`no AEGIS account key — ${credentials.HOW_TO_SET}`);const r=await n.run(t||{});Y(render.renderToolResult(b(),e,r,h()))}function J(e){const t=String(e||"").toLowerCase();if(!t)return null;let n=null;for(const e of COMMANDS)for(const r of[e.name,...e.aliases||[]])r!==t&&(r.startsWith(t)||t.startsWith(r))&&(null==n||Math.abs(r.length-t.length)<Math.abs(n.length-t.length))&&(n=r);return n}function Q(){const e=loadPermissions(),t=confirmPosture();return{version:VERSION,model:g.model||"server default",class:g.modelClass,effort:g.effort,thinking:g.thinking,theme:g.light?"light":"dark",themeIndex:g.themeIndex,vim:g.vim,stream:g.stream,cwd:g.cwd,home:os.homedir(),sessionId:g.sessionId,base:o.apiBase,keyMask:maskKey(o.apiKey),online:!!o.apiKey,turns:S.turns,calls:S.calls,startedAt:S.startedAt,tokens:{input:S.inputTokens,output:S.outputTokens,cacheRead:S.cacheReadTokens,cacheWrite:S.cacheWriteTokens,total:S.tokens},costEur:S.cost,balance:S.balance,plan:S.plan||null,account:S.account||null,permissions:{mode:t.enabled?e.defaultMode:"allow",confirm:t.enabled,source:t.source,rules:e},models:q(),commands:visibleCommands(),transcript:k.slice(),sessions:[],memory:{},lastRecap:g.lastRecap,backend:g.modelClass,url:o.apiBase}}function Z(e){return Array.isArray(e)?e.map(e=>e&&(e.s||"")+(null==e.t?"":e.t)||"").join(""):String(null==e?"":e)}function ee(e){if(!e||"object"!=typeof e)return;const t=h();switch(e.role){case"panel":{const t=Array.isArray(e.lines)?e.lines:[];for(const e of t)Y(Z(e));return}case"note":case"tip":return void Y(render.renderNotice(b(),"info",e.text));case"done":return void Y(render.renderNotice(b(),"ok",e.text));case"error":return void Y(render.renderNotice(b(),"error",e.text));case"user":return void Y(render.renderTurn(b(),{role:"user",text:e.text,label:e.label},t));case"assistant":return void Y(render.renderTurn(b(),{role:"assistant",text:e.text},t));case"tool":return void 0===e.diff&&(e.diff=editPreview(e.name||e.label,e.args,{cwd:process.cwd()}),e.diffOpen=defaultOpen(e.diff)),void Y(render.renderTurn(b(),{role:"tool",label:e.label||e.name,args:e.args,ok:e.ok,diff:e.diff,diffOpen:!!e.diffOpen},t));default:return void Y(render.renderNotice(b(),"info",null==e.text?"":String(e.text)))}}function te(e){return{t:e,s:"",w:w(e)}}async function ne(){return!e.readline&&process.stdin.isTTY&&process.stdout.isTTY&&!1!==e.chatflow?screens.showThemePicker(g):(g.light=!g.light,g.themeIndex=g.light?2:1,Y(render.renderNotice(b(),"ok","theme: "+(g.light?"light":"dark"))),g.themeIndex)}function re(){const e={ctx:g,transcript:k,push:e=>ee(e),note:e=>ee({role:"note",text:e}),panel:e=>ee({role:"panel",lines:e}),render:()=>{},openOverlay:e=>function(e){if(!e||"object"!=typeof e)return;const t=h(),n=Math.max(5,process.stdout&&process.stdout.rows||24);let r=null;if("panel"===e.type?r=e.lines:"palette"===e.type?r=overlays.renderPalette(visibleCommands(),{query:e.query||"",typed:e.query||"",sel:e.sel||0},t,n):"model"===e.type?r=overlays.renderModelPicker(e.items||[],e.sel||0,t,n,null!=e.current?e.current:g.model,e.cls||g.modelClass,y):"effort"===e.type?r=overlays.renderEffortPicker(e.sel||0,t,g.effort):"class"===e.type?r=overlays.renderClassPicker(e.items||[],e.sel||0,t,e.current||g.modelClass,y):"provider"===e.type?r=overlays.renderProviderPicker(e.items||[],e.sel||0,t,e.current,e.hint):"resume"===e.type?r=overlays.renderResumeList(e.items||[],e.sel||0,t,n):"confirm"===e.type&&(r=render.renderApproval(b(),e.info||{},t).map(e=>[te(e)])),r)for(const e of r)Y(Z(e))}(e),closeOverlay:()=>{},setAutoRounds:e=>{f=Boolean(e)},askInput:()=>Promise.resolve(null),withWorking:e=>async function(e){const r=new AbortController,o=t.interactive&&n.isTTY?new LiveRegion(n):null;let s=null;if(o){let e=0;const t=Date.now(),n=()=>o.update([render.renderWorking(b(),{tick:e++,verb:VERBS[0],elapsedMs:Date.now()-t})]);n(),s=setInterval(n,90),s.unref&&s.unref()}try{return await e(r.signal)}finally{s&&clearInterval(s),o&&o.clear()}}(e),runPrompt:e=>z(e),ask:e=>V(e),runTool:(e,t)=>X(e,t),loadModels:()=>D(g.modelClass),settings:()=>p.settings||null,byokNamespace:e=>byokNamespace(e),listModelsFor:e=>D(e),refreshByokModels:()=>K({force:!0}),switchClass:e=>function(e){const t=String(null==e?"":e).trim().toLowerCase(),n=U();if(!n.includes(t))return"pro"===t?{ok:!1,error:"the pro class (your Claude Code subscription) is off by default — enable it once with `/class pro on`"}:{ok:!1,error:`unknown class "${e}" — classes: ${n.join(", ")}`};const r=g.modelClass;g.modelClass=t;let o=null;return r!==t&&g.model&&(function(e,t){const n=String(null==t?"":t);return"byok"===e?n.includes(":"):"pro"===e?B().has(n.toLowerCase()):!n.includes(":")}(t,g.model)||(o=g.model,g.model=null)),updateConfig({modelClass:t,model:g.model,currentModelId:g.model}),{ok:!0,class:t,prev:r,cleared:o}}(e),classLabel:e=>y(e),classes:()=>"function"==typeof p.listClasses?p.listClasses():[],refreshSpend:()=>N(),state:()=>Q(),setInput:()=>{},exit:()=>{v=!0},client:o,TOOLS:i,saveConfig:e=>updateConfig(e),showThemePicker:()=>ne(),keyStatus:()=>credentials.keyStatus(),setApiKey:(e,t)=>A(e,t),forgetApiKey:()=>P(),registerAccount:()=>async function(){return o.apiKey?{alreadyKeyed:!0}:d()}(),readSecret:e=>readSecret(e,{stdin:process.stdin,stdout:n}),cloudsync:cloudsync,cloudSyncEnabled:()=>x(),cloudSyncState:()=>M(),setCloudSync:e=>O(e),adoptLegacyKey:()=>L()};return Object.defineProperty(e,"sessionId",{enumerable:!0,get:()=>g.sessionId,set:e=>{g.sessionId=e}}),e.clearConversationMemory=()=>{p&&"function"==typeof p.clearSessionApprovals&&p.clearSessionApprovals(g.sessionId)},e.listUndoable=()=>p&&"function"==typeof p.listUndoable?p.listUndoable(g.sessionId):[],e.undoMutation=e=>p&&"function"==typeof p.undoMutation?p.undoMutation(g.sessionId,e):{ok:!1,error:"undo is not available on this engine"},e}async function oe(e,t=null){const r=parseLine(e);if("empty"===r.kind)return!0;if("prompt"===r.kind)return await z(r.text),!0;if("unknown"===r.kind){const e=J(r.name);return Y(render.renderNotice(b(),"error",`unknown command: /${r.name}${e?` — did you mean /${e}?`:" — try /help"}`)),!0}if("unavailable"===r.kind){const e=r.command;if(Y(render.renderNotice(b(),"warn",`/${e.name} is not available in aegiscode — ${e.unavailable}`)),e.alt)Y(render.renderNotice(b(),"info",`try ${e.alt} instead`));else{const t=J(e.name);t&&Y(render.renderNotice(b(),"info",`try /${t} instead`))}return!0}const s=r.command,i=r.arg;if(s.generic){let t;try{t=s.build(i)}catch(e){return Y(render.renderNotice(b(),"error",e.message)),!0}const{tool:n,args:r}=t;if(!n)return Y(render.renderNotice(b(),"error","/tool needs a tool name — see /help")),!0;try{await X(n,r)}catch(e){Y(render.renderNotice(b(),"error",e.message))}return!0}if("function"==typeof s.handler){const n=function(e,t){const n=String(null==t?"":t),r=Array.isArray(e.args)?e.args:[],o=function(e){const t=[];let n="",r=null,o=!1;for(const s of String(e||""))r?s===r?r=null:n+=s:'"'!==s&&"'"!==s?/\s/.test(s)?(n||o)&&(t.push(n),n="",o=!1):(n+=s,o=!0):(r=s,o=!0);return(n||o)&&t.push(n),t}(n),s={_rest:n.trim()};return r.forEach((e,t)=>{void 0!==o[t]&&(s[e]=o[t])}),s}(s,i),r=t||re();try{return!1!==await s.handler(r,n)}catch(e){return Y(render.renderNotice(b(),"error",e&&e.message?e.message:String(e))),!0}}try{let e=s.build(i);if(s.secret){const t=await async function(e,t){if("function"!=typeof e.secretDescribe)return null;try{const n=await e.secretDescribe(t,o);return n&&"object"==typeof n?n:null}catch{return null}}(s,e);if(t&&t.note&&Y(render.renderNotice(b(),"info",t.note)),t&&null===t.prompt)return!0;t&&t.provider&&(e={...e,provider:t.provider});const r=await function(e){const t=themeOf(b());return readSecret(t.gray+e+RESET,{stdin:process.stdin,stdout:n})}(t&&t.prompt||`provider key for ${e.provider}: `);if(!r)return Y(render.renderNotice(b(),"warn","empty key — nothing sent")),!0;e={...e,api_key:r}}if("aegis_ask"===s.tool)return await z(e.prompt);await X(s.tool,e),"aegis_memory_list"!==s.tool&&"aegis_memory_search"!==s.tool||function(){let e;try{e=cloudsync.status()}catch{return}const t=e.quota;if(!t)return;const n=fmtTokens(t.used||0),r=fmtTokens(t.limit||0);e.overQuota?Y(render.renderNotice(b(),"warn",`cloud memory: ${n} of ${r} synced tokens — at the plan's ceiling. Everything stored stays readable; new writes are paused until there is room. /cloud memory for the full state.`)):Y(render.renderNotice(b(),"info",`cloud memory: ${n} of ${r} synced tokens — /cloud memory for the full state`))}()}catch(e){Y(render.renderNotice(b(),"error",e.message))}return!0}async function se(){if(p&&"function"==typeof p.unloadLocalModels)try{await p.unloadLocalModels()}catch{}}function ie(e){S.turns++,S.calls+=Number(e&&e.calls||1)||1;const t=e&&e.usage,n=usageTokens(t);if(null!=n){S.tokens+=n;const e=usageBuckets(t);S.inputTokens+=e.input,S.outputTokens+=e.output,S.cacheReadTokens+=e.cacheRead,S.cacheWriteTokens+=e.cacheWrite}return n}function ae(e,t,n="done",r=null){try{const o=t&&t.usage,s="number"==typeof r&&Number.isFinite(r)?r:null,i=String(t&&t.model||g.model||"").trim();appendHistory({sessionId:g.sessionId,prompt:e,reply:t&&t.text||"",status:n,model:i||void 0,provider:i&&providerForModel({id:i,cls:g.modelClass})||void 0,usage:o?{...usageBuckets(o),...null!=s?{costUsd:s}:{}}:null!=s?{input:0,output:0,cacheRead:0,cacheWrite:0,costUsd:s}:null}),snapshotCheckpoint(g.sessionId,k)}catch{}x()&&o.apiKey&&Promise.resolve().then(()=>cloudsync.push(o)).then(e=>{if(e&&e.failed&&e.failed.length){const t=e.failed[0];if(le.has(t.kind))return;if(le.add(t.kind),"quota"===t.kind)return void Y(render.renderNotice(b(),"warn","cloud memory: the plan's synced-token ceiling is reached — earlier sessions stay readable, only NEW writes pause. /cloud memory shows the quota; /cloud memory off stops trying."));const n=t.hint?` — ${t.hint}`:"";Y(render.renderNotice(b(),"error",`cloud sync: ${t.message}${n}`))}}).catch(()=>{})}let le=new Set;function ce(){const e=[S.outputTokens>0?`${fmtTokens(S.outputTokens)} tokens`:`${fmtTokens(S.tokens)} tokens`,`${S.calls} call${1===S.calls?"":"s"}`];return feeBillable()&&(e.push(fmtEur(S.cost)),null!=S.balance&&e.push(`balance ${fmtEur(S.balance)}`)),e.join(" · ")}async function de(e){if(!e||!e.id)return;const t=readSessionTranscript(e.id);if(t.length){k.length=0;for(const e of t)k.push(e);g.sessionId=e.id,Y(render.renderNotice(b(),"ok",`resumed ${e.id} — ${t.length} turn(s)`))}else Y(render.renderNotice(b(),"warn",`no stored turns for ${e.id}`))}function ue(){return{ctx:g,version:VERSION,transcript:k,session:S,client:o,TOOLS:i,ask:(e,t)=>V(e,t),makeCommandContext:()=>re(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=p.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},loadModels:e=>H(e),buildState:()=>Q(),dispatchLine:(e,t)=>oe(e,t),refreshSpend:()=>N(),updateConfig:e=>updateConfig(e),showThemePicker:()=>ne(),persistTurn:(e,t,n,r)=>ae(e,t,n,r),nameConversation:(e,t)=>async function(e,{signal:t=null}={}){const n=await naming.nameConversation(e,{signal:t,callModel:(e,n)=>V(e,{system:n&&n.system||naming.TITLE_SYSTEM,maxTokens:64,signal:n&&n.signal||t}).then(e=>e&&e.text||null)}),r=String(n||"").trim();return r&&setSessionTitle(g.sessionId,r),r}(e,t),visibleCommands:()=>visibleCommands(),tokensFor:e=>usageTokens(e),recordTurn:e=>ie(e),tokenSummary:()=>ce(),resumeSession:e=>de(e),requestExit:()=>{v=!0},wantsExit:()=>v,keyNotice:()=>o.apiKey?"":c,isYolo:()=>{if(!f)return!1;try{return!1===confirmPosture().enabled}catch{return!1}},setAutoRounds:e=>{f=Boolean(e)}}}async function me(){Y(W()),await N(),n.write("\n");const t=e.readline||readline.createInterface({input:process.stdin,output:n,terminal:!0}),r=themeOf(b()).gold+GLYPH.cursor+" "+RESET;return t.setPrompt(r),t.prompt(),new Promise(e=>{t.on("line",async e=>{t.pause();let n=!0;try{n=await oe(e)}catch(e){Y(render.renderNotice(b(),"error",e.message))}if(!n||v)return E=!0,void t.close();t.resume(),t.prompt()}),t.on("close",()=>{E||n.write("\n"),e(0)})})}function fe(){if(e.readline)return;if(!configExists())return;let n;try{n=loadConfig()}catch{return}if(U().includes(n.modelClass)&&(g.modelClass=n.modelClass),t.class){const e=String(t.class).trim().toLowerCase();if(!U().includes(e))throw new Error(`--class ${t.class}: not available on this host (offered: ${U().join(", ")})`);g.modelClass=e}if(!t.model&&n.model&&(g.model=n.model),g.effort=effortRung(t.effort||n.effort),"boolean"==typeof n.vim&&(g.vim=n.vim),n.lastRecap&&(g.lastRecap=n.lastRecap),!t.light&&"number"==typeof n.themeIndex&&THEME_TABLE[n.themeIndex]){g.themeIndex=n.themeIndex,g.light=themeIsLight(n.themeIndex);const e=reconcileThemeIndex(g.themeIndex);if(e.changed){g.themeIndex=e.index,g.light=themeIsLight(e.index),g.themeNotice=e.reason;try{updateConfig({themeIndex:e.index,light:themeIsLight(e.index)})}catch{g.themeNotice+=" (could not save it)"}}}}return{opts:t,session:S,client:o,TOOLS:i,toolList:a,ctx:g,transcript:k,ask:V,runPrompt:z,handleLine:oe,runOnce:async function(e,t={}){try{return await async function(e,{json:t=!1}={}){if(fe(),L(),!o.apiKey&&!l){l=!0;const e=await autoProvisionApiKey(o,credentials,{app:"cli"});e.key&&r.write("aegiscode: auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.\n`)}if(!o.apiKey)return r.write(`aegiscode: no AEGIS account key. ${credentials.HOW_TO_SET}, or set $${credentials.KEY_ENV}.\n`),2;await N();const s=[],i=[],a=t?{tool:e=>{if("done"===(e&&e.phase)){const t=e.id&&i.find(t=>t.id===e.id&&!0!==t.settled)||(e.id?null:i[i.length-1]);t?(t.settled=!0,t.ok=!1!==e.ok):(e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!0,ok:!1!==e.ok}))}else e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!1,ok:null});const t=e&&void 0!==e.preview?e.preview:null,n=render.renderTurn(b(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:!1},h());for(const e of Array.isArray(n)?n:[n])r.write(e+"\n")}}:null,c=await V(e,a?{presenter:a}:{});await N();const d=usageTokens(c.usage),u=providerRefusal(c.text,c.usage);if(t)n.write(JSON.stringify({text:c.text,model:c.model,class:g.modelClass,rounds:c.usage&&Number(c.usage.calls)||null,usage:c.usage,reasoning_chars:"number"==typeof c.reasoningChars?c.reasoningChars:null,tokens:d,ms:c.ms,interrupted:c.interrupted,...s.length?{tools:s}:{},...i.length?{tool_log:i}:{},...u?{error:u}:{},balance_eur:S.balance},null,2)+"\n");else if(n.write(c.text+"\n"),u&&r.write(`aegiscode: the provider refused this turn — ${u}\n`),null!=d){const e=themeOf(b());n.write(e.dim+GLYPH.hook+" "+e.blue+(c.model||"aegis")+RESET+e.dim+" "+GLYPH.bullet+" "+RESET+e.white+`${fmtTokens(d)} tokens`+RESET+"\n")}return c.interrupted?130:u?1:0}(e,t)}finally{await se()}},runInteractive:async function(){try{return await async function(){if(!e.readline&&!1!==e.chatflow&&process.stdin.isTTY&&process.stdout.isTTY){await probeTerminalBackground({onLeftover:e=>events.feedKeys(e,{keystrokes:!0})}),fe(),function(){if(!g.themeNotice)return;const e=g.themeNotice;g.themeNotice="",Y(render.renderNotice(b(),"warn",`theme: ${e} (saved)`))}(),L(),o.apiKey||await u();const t=await screens.runOnboarding(g,{continue:!!e.continue,seen:e.seen||configExists,save:e=>updateConfig(e),needsKey:()=>!o.apiKey,submitKey:e=>A(e)});if(!t.ok)return 0;if(t.key&&t.key.set&&Y(render.renderNotice(b(),"info",`key saved to ${credentials.credentialsPath()} — no export needed from now on`)),t.key&&t.key.skipped&&!o.apiKey&&Y(render.renderNotice(b(),"warn","no key saved — /key <api_key> or `aegiscode login` whenever you are ready")),t.firstRun&&function(){if(!M().enabled)return void Y(render.renderNotice(b(),"info","cross-session memory: off (you turned it off) — /cloud memory on stores sessions so an interrupted turn can be picked up later"));const e=cloudsync.status().quota,t=e&&e.limit?` (used ${fmtTokens(e.used||0)} of ${fmtTokens(e.limit)} tokens)`:"";Y(render.renderNotice(b(),"info",`cross-session memory: on${t} — sessions are stored to your account so a turn that is interrupted can be resumed. /cloud memory shows the quota; /cloud memory off stops it. Past the ceiling, saved memory stays readable and only new writes pause.`))}(),await F(),e.continue){const e=readOwnSessions(1)[0];e&&(g.continueSession=e.id,await de({id:e.id}))}return await N(),runAutoModelSync(g).catch(()=>{}),await chatflow.runSession(ue()),0}return fe(),L(),me()}()}finally{await se()}},runLinearRepl:me,refreshSpend:N,bannerLines:W,makeHost:ue,loadModels:H,validatePinnedModel:F,recordTurn:ie,persistTurn:ae,restorePrefs:fe,setApiKey:A,forgetApiKey:P,adoptLegacyKeyOnce:L,cloudSyncEnabled:x,cloudSyncState:M,setCloudSync:O,cloudsync:cloudsync,keyStatus:()=>credentials.keyStatus(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=p.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},sessionId:()=>g.sessionId,tokenSummary:ce,resumeSession:de,makeCommandContext:re,buildState:Q,get aborted(){return!1}}}module.exports={createApp:createApp,VERSION:VERSION,normalizeDecision:normalizeDecision};
3
+ "use strict";const readline=require("node:readline"),os=require("node:os"),{randomUUID:randomUUID}=require("node:crypto"),{createTools:createTools,createClient:createClient,usageTokens:usageTokens,usageBuckets:usageBuckets,buildSystemPrompt:buildSystemPrompt,autoProvisionApiKey:autoProvisionApiKey,provisionFailureText:provisionFailureText,trialNote:trialNote,hostEnv:hostEnv,autonomous:autonomous,claudePro:claudePro}=require("./deps.js"),{createEngine:createEngine,HOST_CLASSES:HOST_CLASSES,DEFAULT_CLASS:DEFAULT_CLASS,byokNamespace:byokNamespace,effortRung:effortRung,offeredClasses:offeredClasses,proEnabled:proEnabled}=require("./engine.js"),{GLYPH:GLYPH,VERBS:VERBS,themeOf:themeOf,RESET:RESET,THEME_TABLE:THEME_TABLE,AUTO_THEME_INDEX:AUTO_THEME_INDEX,themeIsLight:themeIsLight,reconcileThemeIndex:reconcileThemeIndex}=require("./theme.js"),{probeTerminalBackground:probeTerminalBackground}=require("./caps.js"),{LiveRegion:LiveRegion,termWidth:termWidth,w:w}=require("./screen.js"),{estimateTokensFromCells:estimateTokensFromCells}=require("./tokens.js"),{editPreview:editPreview}=require("./diff.js"),{defaultOpen:defaultOpen}=require("./diffview.js"),{parseLine:parseLine,COMMANDS:COMMANDS,visibleCommands:visibleCommands,runAutoModelSync:runAutoModelSync}=require("./commands.js"),{updateConfig:updateConfig,loadPermissions:loadPermissions,loadConfig:loadConfig,configExists:configExists,memoryPersistState:memoryPersistState,memoryPersistEnabled:memoryPersistEnabled,setMemoryPersist:setMemoryPersist,confirmPosture:confirmPosture,permissionMode:permissionMode}=require("./config.js"),credentials=require("./credentials.js"),events=require("./events.js"),cloudsync=require("./cloudsync.js"),{readSecret:readSecret}=require("./secret.js"),{normalizeModelCatalog:normalizeModelCatalog,pickerEntries:pickerEntries,catalogIds:catalogIds,providerForModel:providerForModel,withAutoRow:withAutoRow,AUTO_MODEL_ID:AUTO_MODEL_ID}=require("./models.js"),{appendHistory:appendHistory,readSessionTranscript:readSessionTranscript,readOwnSessions:readOwnSessions,setSessionTitle:setSessionTitle}=require("./history.js"),naming=require("./naming.js"),{snapshotCheckpoint:snapshotCheckpoint}=require("./checkpoint.js"),screens=require("./screens.js"),chatflow=require("./chatflow.js"),overlays=require("./overlays.js"),render=require("./render.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,maskKey:maskKey,feeBillable:feeBillable}=require("./format.js"),{resolveSkip:resolveSkip}=require("./permissions.js"),VERSION=require("../package.json").version;let _defaultSystem=null;function defaultSystemPrompt(){if(null===_defaultSystem)try{_defaultSystem=buildSystemPrompt(hostEnv({},{},null))}catch{_defaultSystem=""}return _defaultSystem||void 0}function normalizeDecision(e){const t="string"==typeof e?e.trim().toLowerCase():"";return"session"===t?"session":"once"===t||"allow"===t||"yes"===t||"approve"===t||"approved"===t?"once":"deny"}const PROVIDER_REFUSAL_PATTERNS=Object.freeze([/^invalid api key\b/i,/^fix external api key\b/i,/^you've hit your session limit\b/i,/^you have hit your session limit\b/i,/^provider request timed out\b/i,/^insufficient (?:credit|balance|quota)\b/i,/^rate limit(?:ed)?\b/i,/^unauthorized\b/i]);function providerRefusal(e,t){if("string"!=typeof e)return null;const n=t&&(t.total_tokens||0),r=t&&(t.output_tokens||t.completion_tokens||0);if(n>0||r>0)return null;const o=e.trim();if(!o||o.length>160||o.includes("\n"))return null;for(const e of PROVIDER_REFUSAL_PATTERNS)if(e.test(o))return o;return null}function briefArgs(e){let t;try{t="string"==typeof e?e:JSON.stringify(e??"")}catch{t=String(e)}return t=String(t).replace(/\s+/g," ").trim(),t.length>140?`${t.slice(0,137)}...`:t}function createApp(e={}){const t={model:null,stream:!0,light:!1,maxTokens:void 0,system:void 0,interactive:!0,...e},n=e.out||process.stdout,r=e.err||process.stderr,o=e.client||createClient(credentials.clientOptions({channel:"cli"})),{createLocalWiki:s}=require("./dream-cmd.js"),{TOOLS:i,toolList:a}=e.tools||createTools(o,{localWiki:s()});let l=!1,c="";async function d(){const e=await autoProvisionApiKey(o,credentials,{app:"cli"});return c=e.key?"":provisionFailureText(e),e}async function u(){if(o.apiKey||l)return;l=!0;const e=await d();e.key&&Y(render.renderNotice(S(),"info","auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.`))}let m=!1!==e.confirmMode,f=(()=>{try{return autonomous.autoRoundsDefault(process.env)}catch{return!0}})();const p=e.engine||createEngine({client:o,getClass:()=>g.modelClass,getProEnabled:()=>{try{return proEnabled(loadConfig())}catch{return!1}},getConfirmMode:()=>{if(void 0!==e.confirmMode)return m;try{const e=resolveSkip({env:process.env,interactive:Boolean(process.stdin.isTTY&&process.stdout.isTTY)});if(e.warned&&!skipEnvWarned&&(skipEnvWarned=!0,process.stderr.write(`aegiscode: ${e.warning}\n`)),e.skip)return!1}catch{}try{return confirmPosture().enabled}catch{return m}},getPermissionMode:()=>{try{return permissionMode()}catch{return null}}}),y=e=>"function"==typeof p.classLabel?p.classLabel(e):String(e||""),h=()=>e.width?e.width():termWidth(),g={light:t.light,model:t.model,modelClass:DEFAULT_CLASS,effort:null,thinking:!1,recallDeep:!1,themeIndex:t.light?2:AUTO_THEME_INDEX,vim:!1,stream:t.stream,cwd:process.cwd(),lastRecap:null,sessionId:randomUUID()};g.themeIndex===AUTO_THEME_INDEX&&(g.light=themeIsLight(AUTO_THEME_INDEX));const k=[];let v=!1;const S=()=>({light:g.light}),b={turns:0,calls:0,tokens:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,cost:0,balance:null,seenLedgerRows:new Map,ledgerBaselined:!1,startedAt:Date.now()};let T=null,E=!1;function C(e){if(!e||"object"!=typeof e)return null;if("usage"!==e.kind)return null;const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6;return Number.isFinite(t)?Math.abs(t):null}function I(e){return[e.created_at||"",e.kind||"",null!=e.amount_eur?e.amount_eur:"",null!=e.charged_micros?e.charged_micros:"",null!=e.id?e.id:"",null!=e.note?e.note:""].join("|")}async function N(){try{const e=await o.tokenBankBalance(),t=Number(e.balance_eur);Number.isFinite(t)&&(b.balance=t);let n=null;const r=Array.isArray(e.ledger)?e.ledger:[],s=new Map;for(const e of r){const t=I(e),n=s.get(t);n?n.n+=1:s.set(t,{n:1,row:e})}for(const[e,{n:t,row:r}]of s){const o=b.seenLedgerRows.get(e)||0;if(b.seenLedgerRows.set(e,t),!b.ledgerBaselined)continue;const s=t-o;if(s<=0)continue;const i=C(r);null!=i&&i>0&&(b.cost+=i*s,null==n&&(n=i))}return b.ledgerBaselined=!0,{balance:b.balance,lastCost:n}}catch{return null}}async function A(e,{verify:t=!0}={}){const n=credentials.saveApiKey(e);if(!n.ok)return n;o.setApiKey(n.key),R.models=[],R.at=0;let r=null,s=null;if(t)try{const e=await o.verifyApiKey()||{};r=e;const t={verifiedAt:(new Date).toISOString()};e.memory_token&&(t.memoryToken=e.memory_token),e.plan&&(t.plan=e.plan),t.account={plan:e.plan||null,email:e.email||null,valid:!1!==e.valid},credentials.writeCredentials(t),e.plan&&(b.plan=e.plan),e.email&&(b.account={...b.account||{},email:e.email})}catch(e){s=e}return{...n,account:r,error:s}}function P(){const e=credentials.clearApiKey();return o.setApiKey(""),R.models=[],R.at=0,e}function x(){try{return memoryPersistEnabled()}catch{return!0}}function M(){try{return memoryPersistState()}catch{return{enabled:!0,source:"default",explicit:!1}}}function O(e){return setMemoryPersist(e)}function L(){try{return"config"!==credentials.resolveApiKey().source?[]:credentials.adoptLegacy().adopted}catch{return[]}}const _=3e5,R={at:0,models:[]},$={at:0,models:[],declared:""};async function K({force:e=!1}={}){const t=function(){try{if("function"!=typeof p.userModels)return"";const e=(p.userModels()||{}).map||{};return JSON.stringify(Object.keys(e).sort().map(t=>[t,e[t]]))}catch{return""}}(),n=$.models.length&&Date.now()-$.at<_&&t===$.declared;if(!e&&n)return $.models;if("function"!=typeof p.listModels)return[];const r=await p.listModels("byok");return $.models=(r&&r.models||[]).map(e=>({...e,note:e.configured?"key on this machine":`no key — /byok-key ${e.provider}`})),$.at=Date.now(),$.declared=t,$.models}async function D(e){const t=U();if(e&&!t.includes(e)&&HOST_CLASSES.includes(e))return[];const n=t.includes(e)?e:g.modelClass;try{if("byok"===n){const e=await K();if(!R.models.length)try{await H()}catch{}return q(e,n)}if("pro"===n){const e=await p.listModels("pro");return(e&&e.models||[]).map(e=>({...e,cls:"pro"}))}if("aegis"!==n){const e=await p.listModels(n);return e&&e.models||[]}return await H()}catch{return[]}}function j(){return withAutoRow(pickerEntries(R.models)).map(e=>({...e,cls:"aegis"}))}function q(e,t){const n=U(),r=n.includes(t)?t:g.modelClass;if("pro"===t&&!n.includes("pro"))return[];if("pro"===r)return pickerEntries(claudePro.PRO_MODELS.map(e=>({id:e.id,label:e.label,note:e.note}))).map(e=>({...e,cls:"pro"}));if("byok"!==r)return j();const o=Array.isArray(e)?e.map(e=>({...e,cls:"byok"})):pickerEntries($.models).map(e=>({...e,cls:"byok"}));return[...j(),...o]}function B(){return new Set(claudePro.PRO_MODELS.map(e=>String(e.id).toLowerCase()))}function U(){try{return offeredClasses(proEnabled(loadConfig()))}catch{return offeredClasses(!1)}}async function H({force:e=!1}={}){const t=R.models.length&&Date.now()-R.at<_;if(!e&&t)return R.models;const n=await o.listModels();return R.models=normalizeModelCatalog(n&&n.models),R.at=Date.now(),R.models}async function F(){const e=g.model;if(!e)return null;if("byok"===g.modelClass)return String(e).includes(":")?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(S(),"warn",`pinned model "${e}" belongs to the pooled class — on BYOK an id is "<provider>:<model>"; pin cleared, /models lists what this machine can relay.`)),e);if("pro"===g.modelClass){if(!B().has(String(e).toLowerCase()))return g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(S(),"warn",`pinned model "${e}" is not one the Claude Code CLI resolves — pin cleared, the CLI will choose; /models lists the aliases (${claudePro.PRO_MODELS.map(e=>e.id).join(", ")}).`)),e;let t=!0;try{t=!!claudePro.claudeProStatus({env:process.env}).credentialPresent}catch{t=!0}return t?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(S(),"warn",`pinned model "${e}" needs a Claude Pro subscription or an ANTHROPIC_API_KEY, and this host has neither — pin cleared. Run \`claude /login\`, export a console key, or \`/class pro off\`.`)),e)}let t;try{t=await H()}catch{return null}return t.length?String(e).trim().toLowerCase()===AUTO_MODEL_ID||catalogIds(t).has(String(e).toLowerCase())?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(S(),"warn",`pinned model "${e}" is not advertised by AEGIS Cloud — pin cleared, the pool will choose; /models lists what you can pin.`)),e):null}function W(){return render.renderBanner(S(),{width:h(),version:VERSION,model:g.model||"server default",base:o.apiBase,key:maskKey(o.apiKey),stream:g.stream})}function Y(e){const t="string"==typeof e?[e]:e;for(const e of t)n.write(e+"\n")}async function V(e,{history:o=[],presenter:s=null,signal:i=null}={}){const a=Date.now(),l=!s&&t.interactive&&t.stream&&n.isTTY?new LiveRegion(n):null;let c=0,d=0,u="",m=0,f=0,y=VERBS[Math.floor(Math.random()*VERBS.length)],k=!1,v=!1;const b=()=>{l&&l.update([render.renderWorking(S(),{tick:c++,verb:y,elapsedMs:Date.now()-a,streamed:estimateTokensFromCells(d+m)+f,streamedFloor:f>0})])},E=l?setInterval(b,90):null;E&&E.unref&&E.unref(),b();const C=s||{},I=new Map,N=randomUUID();T=N;let A=!1;const P=()=>{A=!0,p.cancel(N)},x=()=>P();process.once("SIGINT",x),i&&(i.aborted?P():i.addEventListener("abort",P,{once:!0}));const M=e=>(r.write(`aegiscode: ${e.tool} needs confirmation but this run has no prompt for it — denied (pass --automode (alias --yolo) to auto-approve mutating tools).\n`),Promise.resolve("deny")),O=()=>Promise.resolve(!1),L=e=>{if(e){if(e.thinkingTokens&&(f+=e.thinkingTokens,k||(k=!0,y="Reasoning"),(e=>{C.thinkingTokens&&C.thinkingTokens(e)})(e.thinkingTokens),b()),e.reasoning&&(m+=w(e.reasoning),k||(k=!0,y="Reasoning",b()),(e=>{C.reasoning&&C.reasoning(e)})(e.reasoning)),e.delta&&(d+=w(e.delta),u+=e.delta,(e=>{if(C.text)return C.text(e);l&&c%2==0&&b()})(e.delta)),e.tool&&(v=!0,(e=>{if(C.tool)return C.tool(e);l&&l.clear();const t=(e=>{const t=e&&void 0!==e.id?`id:${e.id}`:`${e&&e.name}:${JSON.stringify(e&&e.args)}`;return I.has(t)||I.set(t,editPreview(e&&e.name,e&&e.args,{cwd:process.cwd()})),I.get(t)})(e);Y(render.renderTurn(S(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:defaultOpen(t)},h())),b()})(e.tool)),e.approval){const t=e.approval;l&&l.clear();const n=C.approval||M;Promise.resolve(n(t)).catch(()=>"deny").then(e=>p.respondApproval(t.id,normalizeDecision(e)))}if(e.rounds){const t=e.rounds;l&&l.clear();const n=C.rounds||O;Promise.resolve(n(t)).catch(()=>!1).then(e=>p.respondRoundsAsk(t.id,!0===e))}}};try{const n=await p.chat({prompt:e,messages:o,model:g.model||void 0,system:t.system||defaultSystemPrompt(),maxTokens:t.maxTokens,effort:effortRung(g.effort),recallDeep:!0===g.recallDeep||void 0,stream:!1!==g.stream,sessionId:N,sessionKey:g.sessionId,rootSessionId:g.sessionId,roundsAsk:Boolean(C.rounds)},L),r=n.choices&&n.choices[0]||{};return{text:r.message&&r.message.content||u,usage:n.usage||null,model:n.model||g.model||null,ms:Date.now()-a,interrupted:A,reasoningChars:m,usedTools:v}}catch(e){if(A&&u)return{text:u,usage:null,model:g.model||null,ms:Date.now()-a,interrupted:!0,reasoningChars:m,usedTools:v};throw e}finally{E&&clearInterval(E),process.removeListener("SIGINT",x),i&&i.removeEventListener("abort",P),l&&l.clear(),T=null}}function G(e){Y(render.renderTurn(S(),e,h()))}async function z(e,{label:t="you"}={}){if(!e)return void Y(render.renderNotice(S(),"warn","nothing to ask — give /ask a prompt"));if(o.apiKey||await u(),!o.apiKey)return void Y(render.renderNotice(S(),"error",`no AEGIS account key — ${credentials.HOW_TO_SET} (or set $${credentials.KEY_ENV})`));const n=k.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.text}));let r;G({role:"user",text:e,label:t}),k.push({role:"user",text:e});try{r=await V(e,{history:n})}catch(t){return ae(e,{text:"",error:t.message},"error"),void Y(render.renderTurn(S(),{role:"error",text:t.message},h()))}r.text&&k.push({role:"assistant",text:r.text});const s=ie(r);let i=null;try{const e=await N();i=e?e.lastCost:null}catch{}ae(e,r,r.interrupted?"stopped":r.error?"error":"done",i),G({role:"assistant",text:r.text||"(the pool returned no text — see /balance for what it charged)",meta:{model:r.model,tokens:s,usage:null==r.usage?null:usageBuckets(r.usage),eur:i,ms:r.ms,calls:1}}),r.interrupted&&Y(render.renderNotice(S(),"warn","interrupted — the pool may still be running and billing this call"))}async function X(e,t){const n=i[e];if(!n)throw new Error(`unknown tool: ${e}`);if(o.apiKey||await u(),!o.apiKey)throw new Error(`no AEGIS account key — ${credentials.HOW_TO_SET}`);const r=await n.run(t||{});Y(render.renderToolResult(S(),e,r,h()))}function J(e){const t=String(e||"").toLowerCase();if(!t)return null;let n=null;for(const e of COMMANDS)for(const r of[e.name,...e.aliases||[]])r!==t&&(r.startsWith(t)||t.startsWith(r))&&(null==n||Math.abs(r.length-t.length)<Math.abs(n.length-t.length))&&(n=r);return n}function Q(){const e=loadPermissions(),t=confirmPosture();return{version:VERSION,model:g.model||"server default",class:g.modelClass,effort:g.effort,thinking:g.thinking,theme:g.light?"light":"dark",themeIndex:g.themeIndex,vim:g.vim,stream:g.stream,cwd:g.cwd,home:os.homedir(),sessionId:g.sessionId,base:o.apiBase,keyMask:maskKey(o.apiKey),online:!!o.apiKey,turns:b.turns,calls:b.calls,startedAt:b.startedAt,tokens:{input:b.inputTokens,output:b.outputTokens,cacheRead:b.cacheReadTokens,cacheWrite:b.cacheWriteTokens,total:b.tokens},costEur:b.cost,balance:b.balance,plan:b.plan||null,account:b.account||null,permissions:{mode:t.enabled?e.defaultMode:"allow",confirm:t.enabled,source:t.source,rules:e},models:q(),commands:visibleCommands(),transcript:k.slice(),sessions:[],memory:{},lastRecap:g.lastRecap,backend:g.modelClass,url:o.apiBase}}function Z(e){return Array.isArray(e)?e.map(e=>e&&(e.s||"")+(null==e.t?"":e.t)||"").join(""):String(null==e?"":e)}function ee(e){if(!e||"object"!=typeof e)return;const t=h();switch(e.role){case"panel":{const t=Array.isArray(e.lines)?e.lines:[];for(const e of t)Y(Z(e));return}case"note":case"tip":return void Y(render.renderNotice(S(),"info",e.text));case"done":return void Y(render.renderNotice(S(),"ok",e.text));case"error":return void Y(render.renderNotice(S(),"error",e.text));case"user":return void Y(render.renderTurn(S(),{role:"user",text:e.text,label:e.label},t));case"assistant":return void Y(render.renderTurn(S(),{role:"assistant",text:e.text},t));case"tool":return void 0===e.diff&&(e.diff=editPreview(e.name||e.label,e.args,{cwd:process.cwd()}),e.diffOpen=defaultOpen(e.diff)),void Y(render.renderTurn(S(),{role:"tool",label:e.label||e.name,args:e.args,ok:e.ok,diff:e.diff,diffOpen:!!e.diffOpen},t));default:return void Y(render.renderNotice(S(),"info",null==e.text?"":String(e.text)))}}function te(e){return{t:e,s:"",w:w(e)}}async function ne(){return!e.readline&&process.stdin.isTTY&&process.stdout.isTTY&&!1!==e.chatflow?screens.showThemePicker(g):(g.light=!g.light,g.themeIndex=g.light?2:1,Y(render.renderNotice(S(),"ok","theme: "+(g.light?"light":"dark"))),g.themeIndex)}function re(){const e={ctx:g,transcript:k,push:e=>ee(e),note:e=>ee({role:"note",text:e}),panel:e=>ee({role:"panel",lines:e}),render:()=>{},openOverlay:e=>function(e){if(!e||"object"!=typeof e)return;const t=h(),n=Math.max(5,process.stdout&&process.stdout.rows||24);let r=null;if("panel"===e.type?r=e.lines:"palette"===e.type?r=overlays.renderPalette(visibleCommands(),{query:e.query||"",typed:e.query||"",sel:e.sel||0},t,n):"model"===e.type?r=overlays.renderModelPicker(e.items||[],e.sel||0,t,n,null!=e.current?e.current:g.model,e.cls||g.modelClass,y):"effort"===e.type?r=overlays.renderEffortPicker(e.sel||0,t,g.effort):"class"===e.type?r=overlays.renderClassPicker(e.items||[],e.sel||0,t,e.current||g.modelClass,y):"provider"===e.type?r=overlays.renderProviderPicker(e.items||[],e.sel||0,t,e.current,e.hint):"resume"===e.type?r=overlays.renderResumeList(e.items||[],e.sel||0,t,n):"confirm"===e.type&&(r=render.renderApproval(S(),e.info||{},t).map(e=>[te(e)])),r)for(const e of r)Y(Z(e))}(e),closeOverlay:()=>{},setAutoRounds:e=>{f=Boolean(e)},askInput:()=>Promise.resolve(null),withWorking:e=>async function(e){const r=new AbortController,o=t.interactive&&n.isTTY?new LiveRegion(n):null;let s=null;if(o){let e=0;const t=Date.now(),n=()=>o.update([render.renderWorking(S(),{tick:e++,verb:VERBS[0],elapsedMs:Date.now()-t})]);n(),s=setInterval(n,90),s.unref&&s.unref()}try{return await e(r.signal)}finally{s&&clearInterval(s),o&&o.clear()}}(e),runPrompt:e=>z(e),ask:e=>V(e),runTool:(e,t)=>X(e,t),loadModels:()=>D(g.modelClass),settings:()=>p.settings||null,byokNamespace:e=>byokNamespace(e),listModelsFor:e=>D(e),refreshByokModels:()=>K({force:!0}),switchClass:e=>function(e){const t=String(null==e?"":e).trim().toLowerCase(),n=U();if(!n.includes(t))return"pro"===t?{ok:!1,error:"the pro class (your Claude Code subscription) is off by default — enable it once with `/class pro on`"}:{ok:!1,error:`unknown class "${e}" — classes: ${n.join(", ")}`};const r=g.modelClass;g.modelClass=t;let o=null;return r!==t&&g.model&&(function(e,t){const n=String(null==t?"":t);return"byok"===e?n.includes(":"):"pro"===e?B().has(n.toLowerCase()):!n.includes(":")}(t,g.model)||(o=g.model,g.model=null)),updateConfig({modelClass:t,model:g.model,currentModelId:g.model}),{ok:!0,class:t,prev:r,cleared:o}}(e),classLabel:e=>y(e),classes:()=>"function"==typeof p.listClasses?p.listClasses():[],refreshSpend:()=>N(),state:()=>Q(),setInput:()=>{},exit:()=>{v=!0},client:o,TOOLS:i,saveConfig:e=>updateConfig(e),showThemePicker:()=>ne(),keyStatus:()=>credentials.keyStatus(),setApiKey:(e,t)=>A(e,t),forgetApiKey:()=>P(),registerAccount:()=>async function(){return o.apiKey?{alreadyKeyed:!0}:d()}(),readSecret:e=>readSecret(e,{stdin:process.stdin,stdout:n}),cloudsync:cloudsync,cloudSyncEnabled:()=>x(),cloudSyncState:()=>M(),setCloudSync:e=>O(e),adoptLegacyKey:()=>L()};return Object.defineProperty(e,"sessionId",{enumerable:!0,get:()=>g.sessionId,set:e=>{g.sessionId=e}}),e.clearConversationMemory=()=>{p&&"function"==typeof p.clearSessionApprovals&&p.clearSessionApprovals(g.sessionId)},e.listUndoable=()=>p&&"function"==typeof p.listUndoable?p.listUndoable(g.sessionId):[],e.undoMutation=e=>p&&"function"==typeof p.undoMutation?p.undoMutation(g.sessionId,e):{ok:!1,error:"undo is not available on this engine"},e}async function oe(e,t=null){const r=parseLine(e);if("empty"===r.kind)return!0;if("prompt"===r.kind)return await z(r.text),!0;if("unknown"===r.kind){const e=J(r.name);return Y(render.renderNotice(S(),"error",`unknown command: /${r.name}${e?` — did you mean /${e}?`:" — try /help"}`)),!0}if("unavailable"===r.kind){const e=r.command;if(Y(render.renderNotice(S(),"warn",`/${e.name} is not available in aegiscode — ${e.unavailable}`)),e.alt)Y(render.renderNotice(S(),"info",`try ${e.alt} instead`));else{const t=J(e.name);t&&Y(render.renderNotice(S(),"info",`try /${t} instead`))}return!0}const s=r.command,i=r.arg;if(s.generic){let t;try{t=s.build(i)}catch(e){return Y(render.renderNotice(S(),"error",e.message)),!0}const{tool:n,args:r}=t;if(!n)return Y(render.renderNotice(S(),"error","/tool needs a tool name — see /help")),!0;try{await X(n,r)}catch(e){Y(render.renderNotice(S(),"error",e.message))}return!0}if("function"==typeof s.handler){const n=function(e,t){const n=String(null==t?"":t),r=Array.isArray(e.args)?e.args:[],o=function(e){const t=[];let n="",r=null,o=!1;for(const s of String(e||""))r?s===r?r=null:n+=s:'"'!==s&&"'"!==s?/\s/.test(s)?(n||o)&&(t.push(n),n="",o=!1):(n+=s,o=!0):(r=s,o=!0);return(n||o)&&t.push(n),t}(n),s={_rest:n.trim()};return r.forEach((e,t)=>{void 0!==o[t]&&(s[e]=o[t])}),s}(s,i),r=t||re();try{return!1!==await s.handler(r,n)}catch(e){return Y(render.renderNotice(S(),"error",e&&e.message?e.message:String(e))),!0}}try{let e=s.build(i);if(s.secret){const t=await async function(e,t){if("function"!=typeof e.secretDescribe)return null;try{const n=await e.secretDescribe(t,o);return n&&"object"==typeof n?n:null}catch{return null}}(s,e);if(t&&t.note&&Y(render.renderNotice(S(),"info",t.note)),t&&null===t.prompt)return!0;t&&t.provider&&(e={...e,provider:t.provider});const r=await function(e){const t=themeOf(S());return readSecret(t.gray+e+RESET,{stdin:process.stdin,stdout:n})}(t&&t.prompt||`provider key for ${e.provider}: `);if(!r)return Y(render.renderNotice(S(),"warn","empty key — nothing sent")),!0;e={...e,api_key:r}}if("aegis_ask"===s.tool)return await z(e.prompt);await X(s.tool,e),"aegis_memory_list"!==s.tool&&"aegis_memory_search"!==s.tool||function(){let e;try{e=cloudsync.status()}catch{return}const t=e.quota;if(!t)return;const n=fmtTokens(t.used||0),r=fmtTokens(t.limit||0);e.overQuota?Y(render.renderNotice(S(),"warn",`cloud memory: ${n} of ${r} synced tokens — at the plan's ceiling. Everything stored stays readable; new writes are paused until there is room. /cloud memory for the full state.`)):Y(render.renderNotice(S(),"info",`cloud memory: ${n} of ${r} synced tokens — /cloud memory for the full state`))}()}catch(e){Y(render.renderNotice(S(),"error",e.message))}return!0}async function se(){if(p&&"function"==typeof p.unloadLocalModels)try{await p.unloadLocalModels()}catch{}}function ie(e){b.turns++,b.calls+=Number(e&&e.calls||1)||1;const t=e&&e.usage,n=usageTokens(t);if(null!=n){b.tokens+=n;const e=usageBuckets(t);b.inputTokens+=e.input,b.outputTokens+=e.output,b.cacheReadTokens+=e.cacheRead,b.cacheWriteTokens+=e.cacheWrite}return n}function ae(e,t,n="done",r=null){try{const o=t&&t.usage,s="number"==typeof r&&Number.isFinite(r)?r:null,i=String(t&&t.model||g.model||"").trim();appendHistory({sessionId:g.sessionId,prompt:e,reply:t&&t.text||"",status:n,model:i||void 0,provider:i&&providerForModel({id:i,cls:g.modelClass})||void 0,usage:o?{...usageBuckets(o),...null!=s?{costUsd:s}:{}}:null!=s?{input:0,output:0,cacheRead:0,cacheWrite:0,costUsd:s}:null}),snapshotCheckpoint(g.sessionId,k)}catch{}x()&&o.apiKey&&Promise.resolve().then(()=>cloudsync.push(o)).then(e=>{if(e&&e.failed&&e.failed.length){const t=e.failed[0];if(le.has(t.kind))return;if(le.add(t.kind),"quota"===t.kind)return void Y(render.renderNotice(S(),"warn","cloud memory: the plan's synced-token ceiling is reached — earlier sessions stay readable, only NEW writes pause. /cloud memory shows the quota; /cloud memory off stops trying."));const n=t.hint?` — ${t.hint}`:"";Y(render.renderNotice(S(),"error",`cloud sync: ${t.message}${n}`))}}).catch(()=>{})}let le=new Set;function ce(){const e=[b.outputTokens>0?`${fmtTokens(b.outputTokens)} tokens`:`${fmtTokens(b.tokens)} tokens`,`${b.calls} call${1===b.calls?"":"s"}`];return feeBillable()&&(e.push(fmtEur(b.cost)),null!=b.balance&&e.push(`balance ${fmtEur(b.balance)}`)),e.join(" · ")}async function de(e){if(!e||!e.id)return;const t=readSessionTranscript(e.id);if(t.length){k.length=0;for(const e of t)k.push(e);g.sessionId=e.id,Y(render.renderNotice(S(),"ok",`resumed ${e.id} — ${t.length} turn(s)`))}else Y(render.renderNotice(S(),"warn",`no stored turns for ${e.id}`))}function ue(){return{ctx:g,version:VERSION,transcript:k,session:b,client:o,TOOLS:i,ask:(e,t)=>V(e,t),makeCommandContext:()=>re(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=p.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},loadModels:e=>H(e),buildState:()=>Q(),dispatchLine:(e,t)=>oe(e,t),refreshSpend:()=>N(),updateConfig:e=>updateConfig(e),showThemePicker:()=>ne(),persistTurn:(e,t,n,r)=>ae(e,t,n,r),nameConversation:(e,t)=>async function(e,{signal:t=null}={}){const n=await naming.nameConversation(e,{signal:t,callModel:(e,n)=>V(e,{system:n&&n.system||naming.TITLE_SYSTEM,maxTokens:64,signal:n&&n.signal||t}).then(e=>e&&e.text||null)}),r=String(n||"").trim();return r&&setSessionTitle(g.sessionId,r),r}(e,t),visibleCommands:()=>visibleCommands(),tokensFor:e=>usageTokens(e),recordTurn:e=>ie(e),tokenSummary:()=>ce(),resumeSession:e=>de(e),requestExit:()=>{v=!0},wantsExit:()=>v,keyNotice:()=>o.apiKey?"":c,isYolo:()=>{if(!f)return!1;try{return!1===confirmPosture().enabled}catch{return!1}},setAutoRounds:e=>{f=Boolean(e)}}}async function me(){Y(W()),await N(),n.write("\n");const t=e.readline||readline.createInterface({input:process.stdin,output:n,terminal:!0}),r=themeOf(S()).gold+GLYPH.cursor+" "+RESET;return t.setPrompt(r),t.prompt(),new Promise(e=>{t.on("line",async e=>{t.pause();let n=!0;try{n=await oe(e)}catch(e){Y(render.renderNotice(S(),"error",e.message))}if(!n||v)return E=!0,void t.close();t.resume(),t.prompt()}),t.on("close",()=>{E||n.write("\n"),e(0)})})}function fe(){if(e.readline)return;if(!configExists())return;let n;try{n=loadConfig()}catch{return}if(U().includes(n.modelClass)&&(g.modelClass=n.modelClass),t.class){const e=String(t.class).trim().toLowerCase();if(!U().includes(e))throw new Error(`--class ${t.class}: not available on this host (offered: ${U().join(", ")})`);g.modelClass=e}if(!t.model&&n.model&&(g.model=n.model),g.effort=effortRung(t.effort||n.effort),"boolean"==typeof n.vim&&(g.vim=n.vim),n.lastRecap&&(g.lastRecap=n.lastRecap),!t.light&&"number"==typeof n.themeIndex&&THEME_TABLE[n.themeIndex]){g.themeIndex=n.themeIndex,g.light=themeIsLight(n.themeIndex);const e=reconcileThemeIndex(g.themeIndex);if(e.changed){g.themeIndex=e.index,g.light=themeIsLight(e.index),g.themeNotice=e.reason;try{updateConfig({themeIndex:e.index,light:themeIsLight(e.index)})}catch{g.themeNotice+=" (could not save it)"}}}}return{opts:t,session:b,client:o,TOOLS:i,toolList:a,ctx:g,transcript:k,ask:V,runPrompt:z,handleLine:oe,runOnce:async function(e,t={}){try{return await async function(e,{json:t=!1}={}){if(fe(),L(),!o.apiKey&&!l){l=!0;const e=await autoProvisionApiKey(o,credentials,{app:"cli"});e.key&&r.write("aegiscode: auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.\n`)}if(!o.apiKey)return r.write(`aegiscode: no AEGIS account key. ${credentials.HOW_TO_SET}, or set $${credentials.KEY_ENV}.\n`),2;await N();const s=[],i=[],a=t?{tool:e=>{if("done"===(e&&e.phase)){const t=e.id&&i.find(t=>t.id===e.id&&!0!==t.settled)||(e.id?null:i[i.length-1]);t?(t.settled=!0,t.ok=!1!==e.ok):(e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!0,ok:!1!==e.ok}))}else e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!1,ok:null});const t=e&&void 0!==e.preview?e.preview:null,n=render.renderTurn(S(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:!1},h());for(const e of Array.isArray(n)?n:[n])r.write(e+"\n")}}:null,c=await V(e,a?{presenter:a}:{});await N();const d=usageTokens(c.usage),u=providerRefusal(c.text,c.usage);if(t)n.write(JSON.stringify({text:c.text,model:c.model,class:g.modelClass,rounds:c.usage&&Number(c.usage.calls)||null,usage:c.usage,reasoning_chars:"number"==typeof c.reasoningChars?c.reasoningChars:null,tokens:d,ms:c.ms,interrupted:c.interrupted,...s.length?{tools:s}:{},...i.length?{tool_log:i}:{},...u?{error:u}:{},balance_eur:b.balance},null,2)+"\n");else if(n.write(c.text+"\n"),u&&r.write(`aegiscode: the provider refused this turn — ${u}\n`),null!=d){const e=themeOf(S());n.write(e.dim+GLYPH.hook+" "+e.blue+(c.model||"aegis")+RESET+e.dim+" "+GLYPH.bullet+" "+RESET+e.white+`${fmtTokens(d)} tokens`+RESET+"\n")}return c.interrupted?130:u?1:0}(e,t)}finally{await se()}},runInteractive:async function(){try{return await async function(){if(!e.readline&&!1!==e.chatflow&&process.stdin.isTTY&&process.stdout.isTTY){await probeTerminalBackground({onLeftover:e=>events.feedKeys(e,{keystrokes:!0})}),fe(),function(){if(!g.themeNotice)return;const e=g.themeNotice;g.themeNotice="",Y(render.renderNotice(S(),"warn",`theme: ${e} (saved)`))}(),L(),o.apiKey||await u();const t=await screens.runOnboarding(g,{continue:!!e.continue,seen:e.seen||configExists,save:e=>updateConfig(e),needsKey:()=>!o.apiKey,submitKey:e=>A(e)});if(!t.ok)return 0;if(t.key&&t.key.set&&Y(render.renderNotice(S(),"info",`key saved to ${credentials.credentialsPath()} — no export needed from now on`)),t.key&&t.key.skipped&&!o.apiKey&&Y(render.renderNotice(S(),"warn","no key saved — /key <api_key> or `aegiscode login` whenever you are ready")),t.firstRun&&function(){if(!M().enabled)return void Y(render.renderNotice(S(),"info","cross-session memory: off (you turned it off) — /cloud memory on stores sessions so an interrupted turn can be picked up later"));const e=cloudsync.status().quota,t=e&&e.limit?` (used ${fmtTokens(e.used||0)} of ${fmtTokens(e.limit)} tokens)`:"";Y(render.renderNotice(S(),"info",`cross-session memory: on${t} — sessions are stored to your account so a turn that is interrupted can be resumed. /cloud memory shows the quota; /cloud memory off stops it. Past the ceiling, saved memory stays readable and only new writes pause.`))}(),await F(),e.sessionId)g.continueSession=String(e.sessionId),await de({id:String(e.sessionId)});else if(e.continue){const e=readOwnSessions(1)[0];e&&(g.continueSession=e.id,await de({id:e.id}))}return await N(),runAutoModelSync(g).catch(()=>{}),await chatflow.runSession(ue()),0}return fe(),L(),me()}()}finally{await se()}},runLinearRepl:me,refreshSpend:N,bannerLines:W,makeHost:ue,loadModels:H,validatePinnedModel:F,recordTurn:ie,persistTurn:ae,restorePrefs:fe,setApiKey:A,forgetApiKey:P,adoptLegacyKeyOnce:L,cloudSyncEnabled:x,cloudSyncState:M,setCloudSync:O,cloudsync:cloudsync,keyStatus:()=>credentials.keyStatus(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=p.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},sessionId:()=>g.sessionId,tokenSummary:ce,resumeSession:de,makeCommandContext:re,buildState:Q,get aborted(){return!1}}}module.exports={createApp:createApp,VERSION:VERSION,normalizeDecision:normalizeDecision};
@@ -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{createHash:createHash}=require("node:crypto"),{existsSync:existsSync,readFileSync:readFileSync}=require("node:fs"),path=require("node:path"),PACKAGE_ROOT=path.join(__dirname,".."),SALT="aegiscode-interlock-v1",PAD="aegis-interlock-pad-v1",sha256=e=>createHash("sha256").update(e).digest("hex"),PAD_HEX=sha256(PAD);function unmask(e){let t="";for(let r=0;r<e.length;r++){const n=parseInt(e[r],16),i=parseInt(PAD_HEX[r%PAD_HEX.length],16);if(Number.isNaN(n)||Number.isNaN(i))return null;t+=(n^i).toString(16)}return t}const UNITS=Object.freeze([{id:"p1",rel:Buffer.from("YmluL2FlZ2lzY29kZS5qcw==","base64").toString("utf8")},{id:"p2",rel:Buffer.from("c3JjL3Byb3ZlbmFuY2UuanM=","base64").toString("utf8")},{id:"p3",rel:Buffer.from("c3JjL2dhdGUuanM=","base64").toString("utf8")},{id:"p4",rel:Buffer.from("c3JjL3Blcm1pc3Npb25zLmpz","base64").toString("utf8")},{id:"p5",rel:Buffer.from("c3JjL2NhcHMuanM=","base64").toString("utf8")},{id:"p6",rel:Buffer.from("c3JjL2F1dG9ub21vdXMuanM=","base64").toString("utf8")},{id:"p8",rel:Buffer.from("c3JjL21jcC5qcw==","base64").toString("utf8")}]),SEALED="42b7689fd5fd8cad4ee0070866c7bc9b68f04c0b324c32431d71c958331350fd",PRIVILEGED=Object.freeze(["gate","provenance","mcp"]);function check(){const e=[];for(const t of UNITS){const r=path.join(PACKAGE_ROOT,t.rel);if(!existsSync(r))return{tripped:!0,code:"p1",units:UNITS.length};try{e.push(sha256(readFileSync(r)))}catch{return{tripped:!0,code:"p1",units:UNITS.length}}}const t=sha256(`${SALT}\n${e.join("\n")}`),r=SEALED.trim();return 64!==r.length?{tripped:!0,code:"p2",units:UNITS.length}:unmask(r)!==t?{tripped:!0,code:"p3",units:UNITS.length}:{tripped:!1,code:null,units:UNITS.length}}function line(e){return e&&e.tripped?`aegiscode: reduced mode (${e.code}) — this build is not the one that was published.\n`:null}let ARMED=null;function armed(){if(null!==ARMED)return ARMED;let e;try{e=check()}catch{e={tripped:!0,code:"p2",units:UNITS.length}}if(ARMED=Boolean(e.tripped),ARMED){process.env.AEGIS_REDUCED_MODE="1";const t=line(e);t&&process.stderr.write(t)}return ARMED}function isPrivileged(e){return PRIVILEGED.includes(e)}function refuse(){return 1}function sealOf(e){const t=e.map(e=>sha256(readFileSync(e)));return sha256(`${SALT}\n${t.join("\n")}`)}module.exports={UNITS:UNITS,PRIVILEGED:PRIVILEGED,SALT:SALT,PAD:PAD,check:check,armed:armed,line:line,isPrivileged:isPrivileged,refuse:refuse,sealOf:sealOf,mask:e=>unmask(e)};
3
+ "use strict";const{createHash:createHash}=require("node:crypto"),{existsSync:existsSync,readFileSync:readFileSync}=require("node:fs"),path=require("node:path"),PACKAGE_ROOT=path.join(__dirname,".."),SALT="aegiscode-interlock-v1",PAD="aegis-interlock-pad-v1",sha256=e=>createHash("sha256").update(e).digest("hex"),PAD_HEX=sha256(PAD);function unmask(e){let t="";for(let r=0;r<e.length;r++){const n=parseInt(e[r],16),i=parseInt(PAD_HEX[r%PAD_HEX.length],16);if(Number.isNaN(n)||Number.isNaN(i))return null;t+=(n^i).toString(16)}return t}const UNITS=Object.freeze([{id:"p1",rel:Buffer.from("YmluL2FlZ2lzY29kZS5qcw==","base64").toString("utf8")},{id:"p2",rel:Buffer.from("c3JjL3Byb3ZlbmFuY2UuanM=","base64").toString("utf8")},{id:"p3",rel:Buffer.from("c3JjL2dhdGUuanM=","base64").toString("utf8")},{id:"p4",rel:Buffer.from("c3JjL3Blcm1pc3Npb25zLmpz","base64").toString("utf8")},{id:"p5",rel:Buffer.from("c3JjL2NhcHMuanM=","base64").toString("utf8")},{id:"p6",rel:Buffer.from("c3JjL2F1dG9ub21vdXMuanM=","base64").toString("utf8")},{id:"p8",rel:Buffer.from("c3JjL21jcC5qcw==","base64").toString("utf8")}]),SEALED="84a424d6ea58ea5eb8e65b7ca42f6b89ccdb00a0e4a718bc331cc2afd93f6a46",PRIVILEGED=Object.freeze(["gate","provenance","mcp"]);function check(){const e=[];for(const t of UNITS){const r=path.join(PACKAGE_ROOT,t.rel);if(!existsSync(r))return{tripped:!0,code:"p1",units:UNITS.length};try{e.push(sha256(readFileSync(r)))}catch{return{tripped:!0,code:"p1",units:UNITS.length}}}const t=sha256(`${SALT}\n${e.join("\n")}`),r=SEALED.trim();return 64!==r.length?{tripped:!0,code:"p2",units:UNITS.length}:unmask(r)!==t?{tripped:!0,code:"p3",units:UNITS.length}:{tripped:!1,code:null,units:UNITS.length}}function line(e){return e&&e.tripped?`aegiscode: reduced mode (${e.code}) — this build is not the one that was published.\n`:null}let ARMED=null;function armed(){if(null!==ARMED)return ARMED;let e;try{e=check()}catch{e={tripped:!0,code:"p2",units:UNITS.length}}if(ARMED=Boolean(e.tripped),ARMED){process.env.AEGIS_REDUCED_MODE="1";const t=line(e);t&&process.stderr.write(t)}return ARMED}function isPrivileged(e){return PRIVILEGED.includes(e)}function refuse(){return 1}function sealOf(e){const t=e.map(e=>sha256(readFileSync(e)));return sha256(`${SALT}\n${t.join("\n")}`)}module.exports={UNITS:UNITS,PRIVILEGED:PRIVILEGED,SALT:SALT,PAD:PAD,check:check,armed:armed,line:line,isPrivileged:isPrivileged,refuse:refuse,sealOf:sealOf,mask:e=>unmask(e)};
@@ -24,13 +24,13 @@
24
24
  "license": "AGPL-3.0-or-later",
25
25
  "source": "https://github.com/aegisinfo/aegiscode-plugin",
26
26
  "units": {
27
- "p1": "49709650e67546d1a3d9d6c173bb9e5b1bb1fd6a59f0b04ac754ab72a8f0d04c",
27
+ "p1": "eebf2baed711b0e3bddf5ea4aea75ac8e9fc30057ac9a4b39dee97be38ac8ee0",
28
28
  "p2": "d63d147de5455eea111d000b748d7eef9572a11a08d31f2471d5ff146701342c",
29
29
  "p3": "ff962ac8dbf42cecb2477e2f77bf5ec61f88aa1751b0d4e506bf030fbc5fc6c6",
30
30
  "p4": "43851f41ff482c7a185b75bbb55f9ce8f31af8e9a3adccbfaf57a8d570adbfbf",
31
31
  "p5": "408d67f78f31f6d637a26d2852e0c809a260544e613afdc64b731401c0ba3801",
32
32
  "p6": "1fe9af1a50ba43713bcd780a9993933af52eb0a9acfdab1e9880fc86a4dcfd55",
33
- "p7": "5db6653343b2268c3c6fcd375b67a081a4253cd7a685b57c06909fede9cf7aba",
33
+ "p7": "354f714bc637dd7041193e05fc5f26e6cc9800d614b71533a4019f3d9571a68e",
34
34
  "p8": "3cc054d06715e065fe635b37b7d1bb98bf7989d64453a572ddbb77cec5b830e7"
35
35
  }
36
36
  }
@@ -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 ANSI_RE=/\x1b\[[0-9;]*[A-Za-z]/g,{caps:caps,cellWidth:cellWidth}=require("./caps.js"),cwidth=t=>cellWidth(t);function stripAnsi(t){return String(t).replace(ANSI_RE,"")}function w(t){let e=0;for(const o of stripAnsi(t))e+=cwidth(o);return e}function clip(t,e){if(w(t)<=e)return t;let o="",n=0;for(const i of String(t)){const t=cwidth(i);if(n+t>e)break;o+=i,n+=t}return o}function pad(t,e){const o=clip(t,e);return o+" ".repeat(Math.max(0,e-w(o)))}function padStart(t,e){const o=clip(t,e);return" ".repeat(Math.max(0,e-w(o)))+o}function span(t,e){return{t:e,s:t,w:w(e)}}const lineWidth=t=>t.reduce((t,e)=>t+e.w,0);function padLine(t,e){let o=0;const n=[];for(const i of t){if(o>=e)break;let t=i.t,s=i.w;if(o+s>e){const n=e-o;let i="",r=0;for(const e of[...t]){const t=w(e);if(r+t>n)break;i+=e,r+=t}t=i,s=r}n.push({t:t,s:i.s,w:s}),o+=s}return o<e&&n.push(span(""," ".repeat(e-o))),n}const getSize=()=>{const t=caps();return{cols:t.cols,rows:t.rows}};function wrapLine(t,e,o=""){const n=Math.max(8,e);if(w(t)<=n)return[t];const i=t.split(" "),s=[];let r="";for(const t of i){const e=r?`${r} ${t}`:t;if(w(e)<=n){r=e;continue}if(r&&s.push(r),w(t)<=n){r=t;continue}let o=t;for(;w(o)>n;){const t=clip(o,n);s.push(t),o=o.slice(t.length)}r=o}return!r&&s.length||s.push(r),s}function wrapBlock(t,e,o="",n=!1){const i=[];for(const n of String(t).split("\n"))""!==n?wrapLine(n,e-w(o)).forEach(t=>i.push(o+t)):i.push("");return i}const ESC={hideCursor:"[?25l",showCursor:"[?25h",clearToEnd:"",clearLine:"",clearScreen:"",up:t=>t>0?`[${t}A`:"",down:t=>t>0?`[${t}B`:"",col:t=>`[${t}G`,eraseDown:""},hideCursor=()=>process.stdout.write("[?25l"),showCursor=()=>process.stdout.write("[?25h"),moveTo=(t,e)=>process.stdout.write(`[${t};${e}H`);function clearScreen(){process.stdout.write("")}let inAlt=!1;function enterAltScreen(){inAlt||(inAlt=!0,process.stdout.write("[?1049h"))}function leaveAltScreen(){inAlt&&(inAlt=!1,process.stdout.write("[?1049l"),flushExitNotice())}let exitNotice=null;function queueExitNotice(t){exitNotice=t}function flushExitNotice(){if(null===exitNotice)return;const t=exitNotice;exitNotice=null,process.stdout.write(t)}const hasExitNotice=()=>null!==exitNotice,isAltScreen=()=>inAlt,enableBracketedPaste=()=>process.stdout.write("[?2004h"),disableBracketedPaste=()=>process.stdout.write("[?2004l"),enableMouseTracking=()=>process.stdout.write("[?1000h[?1002h[?1006h"),disableMouseTracking=()=>process.stdout.write("[?1000l[?1002l[?1006l"),SELECT_ON="",SELECT_OFF="";function selectionRange(t,e){return t.row<e.row||t.row===e.row&&t.col<=e.col?{startRow:t.row,startCol:t.col,endRow:e.row,endCol:e.col}:{startRow:e.row,startCol:e.col,endRow:t.row,endCol:t.col}}function sliceLine(t,e,o){const n=[];let i=0;for(const s of t){const t=i;if(i+=s.w,i<=e||t>=o)continue;let r=s.t,c=t;if(c<e){const t=e-c;let o=0,n=0;for(const e of r){if(o>=t)break;o+=w(e),n+=e.length}r=r.slice(n),c+=o}if(c+w(r)>o){let t=0,e="";for(const n of r){const i=w(n);if(c+t+i>o)break;e+=n,t+=i}r=e}r&&n.push({t:r,s:s.s,w:w(r)})}return n}function selectionText(t,e){const o=[];for(let n=e.startRow;n<=e.endRow;n++){const i=t[n]||[],s=n===e.startRow?e.startCol:0,r=n===e.endRow?e.endCol:1/0;o.push(sliceLine(i,s,r).map(t=>t.t).join("").replace(/[ \t]+$/,""))}for(;o.length&&""===o[0];)o.shift();for(;o.length&&""===o[o.length-1];)o.pop();return o.join("\n")}function applySelection(t,e,o){const n=t.slice();for(let t=e.startRow;t<=e.endRow;t++){if(t<0||t>=n.length)continue;const i=padLine(n[t]||[],o),s=t===e.startRow?e.startCol:0,r=t===e.endRow?e.endCol:o,c=sliceLine(i,s,r);c.length&&(n[t]=[...sliceLine(i,0,s),{t:"",s:"",w:0},...c,{t:"",s:"",w:0},...sliceLine(i,r,o)])}return n}function paint(t){const{rows:e,cols:o}=getSize();let n="";for(let i=0;i<e;i++){n+="";const s=t[i];if(s){const t=padLine(s,o);for(const e of t)n+=e.s+e.t;n+=""}else n+="";i<e-1&&(n+="\n")}n+="",process.stdout.write(n)}function paintFrom(t,e){const{rows:o,cols:n}=getSize();let i="";for(let s=0;s<o-e;s++){const o=t[e+s];if(s>0&&(i+="\n"),i+="",i+="",o){const t=padLine(o,n);for(const e of t)i+=e.s+e.t}}i+="",process.stdout.write(i)}function termWidth(t=80){const{cols:e}=getSize();return e>0?e:Math.max(20,t)}class LiveRegion{constructor(t=process.stdout){this.out=t,this.rows=0,this.active=!1}update(t){const e=Math.max(1,getSize().cols),o=t.reduce((t,o)=>t+Math.max(1,Math.ceil(w(o)/e)),0),n=t.map(t=>ESC.col(1)+t+ESC.clearToEnd).join("\n");this.active?this.out.write(ESC.col(1)+ESC.up(this.rows-1)+ESC.eraseDown+n):(this.out.write(n),this.active=!0),this.rows=o}clear(){this.active&&(this.out.write(ESC.col(1)+ESC.up(this.rows-1)+ESC.eraseDown),this.rows=0,this.active=!1)}}module.exports={queueExitNotice:queueExitNotice,flushExitNotice:flushExitNotice,hasExitNotice:hasExitNotice,w:w,clip:clip,pad:pad,padStart:padStart,stripAnsi:stripAnsi,wrapLine:wrapLine,wrapBlock:wrapBlock,span:span,lineWidth:lineWidth,padLine:padLine,paint:paint,paintFrom:paintFrom,getSize:getSize,EC:ESC,hideCursor:hideCursor,showCursor:showCursor,moveTo:moveTo,clearScreen:clearScreen,enterAltScreen:enterAltScreen,leaveAltScreen:leaveAltScreen,isAltScreen:isAltScreen,enableBracketedPaste:enableBracketedPaste,disableBracketedPaste:disableBracketedPaste,enableMouseTracking:enableMouseTracking,disableMouseTracking:disableMouseTracking,SELECT_ON:"",SELECT_OFF:"",selectionRange:selectionRange,sliceLine:sliceLine,selectionText:selectionText,applySelection:applySelection,LiveRegion:LiveRegion,termWidth:termWidth};
3
+ "use strict";const ANSI_RE=/\x1b\[[0-9;]*[A-Za-z]/g,{caps:caps,cellWidth:cellWidth}=require("./caps.js"),cwidth=t=>cellWidth(t);function stripAnsi(t){return String(t).replace(ANSI_RE,"")}function w(t){let e=0;for(const o of stripAnsi(t))e+=cwidth(o);return e}function clip(t,e){if(w(t)<=e)return t;let o="",n=0;for(const i of String(t)){const t=cwidth(i);if(n+t>e)break;o+=i,n+=t}return o}function pad(t,e){const o=clip(t,e);return o+" ".repeat(Math.max(0,e-w(o)))}function padStart(t,e){const o=clip(t,e);return" ".repeat(Math.max(0,e-w(o)))+o}function span(t,e){return{t:e,s:t,w:w(e)}}const lineWidth=t=>t.reduce((t,e)=>t+e.w,0);function padLine(t,e){let o=0;const n=[];for(const i of t){if(o>=e)break;let t=i.t,s=i.w;if(o+s>e){const n=e-o;let i="",r=0;for(const e of[...t]){const t=w(e);if(r+t>n)break;i+=e,r+=t}t=i,s=r}n.push({t:t,s:i.s,w:s}),o+=s}return o<e&&n.push(span(""," ".repeat(e-o))),n}const getSize=()=>{const t=caps();return{cols:t.cols,rows:t.rows}};function wrapLine(t,e,o=""){const n=Math.max(8,e);if(w(t)<=n)return[t];const i=t.split(" "),s=[];let r="";for(const t of i){const e=r?`${r} ${t}`:t;if(w(e)<=n){r=e;continue}if(r&&s.push(r),w(t)<=n){r=t;continue}let o=t;for(;w(o)>n;){const t=clip(o,n);s.push(t),o=o.slice(t.length)}r=o}return!r&&s.length||s.push(r),s}function wrapBlock(t,e,o="",n=!1){const i=[];for(const n of String(t).split("\n"))""!==n?wrapLine(n,e-w(o)).forEach(t=>i.push(o+t)):i.push("");return i}const ESC={hideCursor:"[?25l",showCursor:"[?25h",clearToEnd:"",clearLine:"",clearScreen:"",up:t=>t>0?`[${t}A`:"",down:t=>t>0?`[${t}B`:"",col:t=>`[${t}G`,eraseDown:""},hideCursor=()=>process.stdout.write("[?25l"),showCursor=()=>process.stdout.write("[?25h"),moveTo=(t,e)=>process.stdout.write(`[${t};${e}H`);function clearScreen(){process.stdout.write(""),invalidatePaintCache()}let inAlt=!1;function enterAltScreen(){inAlt||(inAlt=!0,process.stdout.write("[?1049h"),invalidatePaintCache())}function leaveAltScreen(){inAlt&&(inAlt=!1,process.stdout.write("[?1049l"),flushExitNotice())}let exitNotice=null;function queueExitNotice(t){exitNotice=t}function flushExitNotice(){if(null===exitNotice)return;const t=exitNotice;exitNotice=null,process.stdout.write(t)}const hasExitNotice=()=>null!==exitNotice,isAltScreen=()=>inAlt,enableBracketedPaste=()=>process.stdout.write("[?2004h"),disableBracketedPaste=()=>process.stdout.write("[?2004l"),enableMouseTracking=()=>process.stdout.write("[?1000h[?1002h[?1006h"),disableMouseTracking=()=>process.stdout.write("[?1000l[?1002l[?1006l"),SELECT_ON="",SELECT_OFF="";function selectionRange(t,e){return t.row<e.row||t.row===e.row&&t.col<=e.col?{startRow:t.row,startCol:t.col,endRow:e.row,endCol:e.col}:{startRow:e.row,startCol:e.col,endRow:t.row,endCol:t.col}}function sliceLine(t,e,o){const n=[];let i=0;for(const s of t){const t=i;if(i+=s.w,i<=e||t>=o)continue;let r=s.t,c=t;if(c<e){const t=e-c;let o=0,n=0;for(const e of r){if(o>=t)break;o+=w(e),n+=e.length}r=r.slice(n),c+=o}if(c+w(r)>o){let t=0,e="";for(const n of r){const i=w(n);if(c+t+i>o)break;e+=n,t+=i}r=e}r&&n.push({t:r,s:s.s,w:w(r)})}return n}function selectionText(t,e){const o=[];for(let n=e.startRow;n<=e.endRow;n++){const i=t[n]||[],s=n===e.startRow?e.startCol:0,r=n===e.endRow?e.endCol:1/0;o.push(sliceLine(i,s,r).map(t=>t.t).join("").replace(/[ \t]+$/,""))}for(;o.length&&""===o[0];)o.shift();for(;o.length&&""===o[o.length-1];)o.pop();return o.join("\n")}function applySelection(t,e,o){const n=t.slice();for(let t=e.startRow;t<=e.endRow;t++){if(t<0||t>=n.length)continue;const i=padLine(n[t]||[],o),s=t===e.startRow?e.startCol:0,r=t===e.endRow?e.endCol:o,c=sliceLine(i,s,r);c.length&&(n[t]=[...sliceLine(i,0,s),{t:"",s:"",w:0},...c,{t:"",s:"",w:0},...sliceLine(i,r,o)])}return n}function rowCol(t){return`[${Math.max(1,Math.round(t))};1H`}function paintRow(t,e){let o="";if(t){const n=padLine(t,e);for(const t of n)o+=t.s+t.t}return o+""}let paintedRows=null,paintedCols=0,paintedHeight=0;function invalidatePaintCache(){paintedRows=null,paintedCols=0,paintedHeight=0}function paint(t){const{rows:e,cols:o}=getSize(),n=e>0?e:1,i=o>0?o:80,s=null!==paintedRows&&paintedCols===i&&paintedHeight===n,r=new Array(n);let c="";for(let e=0;e<n;e++){const o=paintRow(t[e],i);r[e]=o,s&&paintedRows[e]===o||(c+=rowCol(e+1)+o)}paintedRows=r,paintedCols=i,paintedHeight=n,c&&process.stdout.write(c+"")}function paintFrom(t,e){const{rows:o,cols:n}=getSize(),i=o>0?o:1,s=n>0?n:80,r=null!==paintedRows&&paintedCols===s&&paintedHeight===i,c=r?paintedRows.slice():new Array(i).fill(null);let l="";for(let o=Math.max(0,e);o<i;o++){const e=paintRow(t[o],s);c[o]=e,r&&paintedRows[o]===e||(l+=rowCol(o+1)+e)}paintedRows=c,paintedCols=s,paintedHeight=i,l&&process.stdout.write(l+"")}function termWidth(t=80){const{cols:e}=getSize();return e>0?e:Math.max(20,t)}class LiveRegion{constructor(t=process.stdout){this.out=t,this.rows=0,this.active=!1}update(t){const e=Math.max(1,getSize().cols),o=t.reduce((t,o)=>t+Math.max(1,Math.ceil(w(o)/e)),0),n=t.map(t=>ESC.col(1)+t+ESC.clearToEnd).join("\n");this.active?this.out.write(ESC.col(1)+ESC.up(this.rows-1)+ESC.eraseDown+n):(this.out.write(n),this.active=!0),this.rows=o}clear(){this.active&&(this.out.write(ESC.col(1)+ESC.up(this.rows-1)+ESC.eraseDown),this.rows=0,this.active=!1)}}module.exports={queueExitNotice:queueExitNotice,flushExitNotice:flushExitNotice,hasExitNotice:hasExitNotice,w:w,clip:clip,pad:pad,padStart:padStart,stripAnsi:stripAnsi,wrapLine:wrapLine,wrapBlock:wrapBlock,span:span,lineWidth:lineWidth,padLine:padLine,paint:paint,paintFrom:paintFrom,getSize:getSize,EC:ESC,hideCursor:hideCursor,showCursor:showCursor,moveTo:moveTo,clearScreen:clearScreen,enterAltScreen:enterAltScreen,leaveAltScreen:leaveAltScreen,isAltScreen:isAltScreen,enableBracketedPaste:enableBracketedPaste,disableBracketedPaste:disableBracketedPaste,enableMouseTracking:enableMouseTracking,disableMouseTracking:disableMouseTracking,SELECT_ON:"",SELECT_OFF:"",selectionRange:selectionRange,sliceLine:sliceLine,selectionText:selectionText,applySelection:applySelection,LiveRegion:LiveRegion,termWidth:termWidth};