aegisone 1.0.65 → 1.0.67

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 (43) hide show
  1. package/README.md +1 -1
  2. package/bin/aegis.js +1 -1
  3. package/package.json +1 -1
  4. package/vendor/cli/bin/aegiscode.js +47 -5
  5. package/vendor/cli/package.json +1 -1
  6. package/vendor/cli/src/app.js +1 -1
  7. package/vendor/cli/src/autonomous.js +574 -10
  8. package/vendor/cli/src/commands.js +1 -1
  9. package/vendor/cli/src/dream-cmd.js +3 -0
  10. package/vendor/cli/src/limits.js +1 -1
  11. package/vendor/cli/src/provenance.lock.json +3 -3
  12. package/vendor/cli/src/screen.js +1 -1
  13. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1
  14. package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
  15. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -1
  16. package/vendor/cli/vendor/desktop/main.js +82 -1
  17. package/vendor/cli/vendor/mcp/tools.js +1 -1
  18. package/vendor/desktop/lib/local/autonomous.js +1 -1
  19. package/vendor/desktop/lib/local/integrity.js +1 -1
  20. package/vendor/desktop/lib/local/queue.js +1 -1
  21. package/vendor/desktop/main.js +82 -1
  22. package/vendor/desktop/package.json +1 -1
  23. package/vendor/desktop/preload.js +1 -1
  24. package/vendor/desktop/renderer/app.js +3 -3
  25. package/vendor/desktop/renderer/pty-panel.js +1 -1
  26. package/vendor/desktop/renderer/pty-window.html +72 -0
  27. package/vendor/desktop/renderer/pty-window.js +3 -0
  28. package/vendor/desktop/renderer/stream-policy.js +1 -1
  29. package/vendor/desktop/renderer/style.css +55 -3
  30. package/vendor/desktop/vendor/faces/cli/bin/aegiscode.js +2 -2
  31. package/vendor/desktop/vendor/faces/cli/package.json +1 -1
  32. package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
  33. package/vendor/desktop/vendor/faces/cli/src/autonomous.js +1 -1
  34. package/vendor/desktop/vendor/faces/cli/src/commands.js +1 -1
  35. package/vendor/desktop/vendor/faces/cli/src/dream-cmd.js +3 -0
  36. package/vendor/desktop/vendor/faces/cli/src/limits.js +1 -1
  37. package/vendor/desktop/vendor/faces/cli/src/provenance.lock.json +3 -3
  38. package/vendor/desktop/vendor/faces/cli/src/screen.js +1 -1
  39. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/autonomous.js +1 -1
  40. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
  41. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/queue.js +1 -1
  42. package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +3 -3
  43. package/vendor/desktop/vendor/faces/cli/vendor/mcp/tools.js +1 -1
@@ -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)}`}let ptyPanelCurrent=null;function ptyPanelBuildOverlay(){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-title">Terminal (aegiscode)</span><button type="button" class="pty-panel-close" aria-label="Close terminal">×</button></div><div class="pty-panel-body"><iframe class="pty-panel-frame" title="Terminal (aegiscode)" src="pty-frame.html"></iframe></div></div>',e}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.overlay&&e.overlay.parentNode&&e.overlay.parentNode.removeChild(e.overlay)}}function ptyPanelClose(){if(!ptyPanelCurrent)return;const e=ptyPanelCurrent;ptyPanelCurrent=null,ptyPanelTeardown(e)}function ptyPanelFontFamily(e){try{return e.getComputedStyle(e.document.documentElement).getPropertyValue("--font-mono").trim()||"monospace"}catch{return"monospace"}}function ptyPanelFail(e,n){if(!e||!e.overlay)return;const t=e.overlay.querySelector(".pty-panel-body");if(!t)return;const r=document.createElement("p");r.className="pty-panel-note",r.textContent=n,t.appendChild(r)}function ptyPanelBoot(e){if(!e||e.closed||e.term)return;const n=e.frame&&e.frame.contentWindow,t=n&&n.document,r=t&&t.getElementById("pty-frame-root");if(!n||"function"!=typeof n.Terminal||!r)return void ptyPanelFail(e,"the terminal panel is not available in this build (xterm.js missing)");const o=new n.Terminal({convertEol:!0,cursorBlink:!0,fontSize:13,fontFamily:ptyPanelFontFamily(n)});e.term=o,o.open(r),ptyPanelFit(o,r);const a=e.id;e.unsubscribe=window.aegis.pty.onEvent(a,e=>{const n=e&&e.p;n&&("data"===n.kind?o.write(n.chunk):"exit"===n.kind&&o.write("\r\n[process exited]\r\n"))}),"function"==typeof n.ResizeObserver&&(e.resizeObserver=new n.ResizeObserver(()=>ptyPanelFit(o,r)),e.resizeObserver.observe(r)),o.onData(e=>window.aegis.pty.write(a,e)),o.onResize(({cols:e,rows:n})=>window.aegis.pty.resize(a,e,n)),window.aegis.pty.exec(a,{cols:o.cols,rows:o.rows}).then(e=>{e&&e.ok||o.write(`\r\n[could not start: ${e&&e.e&&e.e.msg||"unknown error"}]\r\n`)}),o.focus()}function ptyPanelOpen(){if(ptyPanelCurrent)return ptyPanelCurrent.overlay&&"function"==typeof ptyPanelCurrent.overlay.focus&&ptyPanelCurrent.overlay.focus(),{ok:!0};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 e=ptyPanelBuildOverlay();document.body.appendChild(e);const n={id:ptyPanelCreateId(),overlay:e,frame:e.querySelector(".pty-panel-frame"),term:null,unsubscribe:null,resizeObserver:null,closed:!1};return ptyPanelCurrent=n,n.frame&&n.frame.addEventListener("load",()=>ptyPanelBoot(n)),e.querySelector(".pty-panel-close").addEventListener("click",ptyPanelClose),e.addEventListener("keydown",e=>{"Escape"===e.key&&ptyPanelClose()}),{ok:!0}}function ptyPanelFit(e,n){const t=e._core,r=t&&t._renderService&&t._renderService.dimensions&&t._renderService.dimensions.css.cell;if(!r||!r.width||!r.height)return null;const o=Math.max(2,Math.floor(n.clientWidth/r.width)),a=Math.max(1,Math.floor(n.clientHeight/r.height));return o===e.cols&&a===e.rows||e.resize(o,a),{cols:o,rows:a}}function ptyPanelIsOpen(){return Boolean(ptyPanelCurrent)}"undefined"!=typeof module&&module.exports&&(module.exports={createId:ptyPanelCreateId,open:ptyPanelOpen,close:ptyPanelClose,isOpen:ptyPanelIsOpen,FRAME_SRC:"pty-frame.html",FRAME_ROOT:"pty-frame-root"}),"undefined"!=typeof window&&(window.aegisPtyPanel={open:ptyPanelOpen,close:ptyPanelClose,isOpen:ptyPanelIsOpen});
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 s=document.createElement("iframe");return s.className="pty-panel-frame",s.title=`Terminal ${e.label} (aegiscode)`,s.src="pty-frame.html",o.appendChild(s),l.appendChild(o),e.tab=a,e.slot=o,e.frame=s,!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"))}ptyPanelShell.active=e.id,e.term&&e.host&&ptyPanelFit(e.term,e.host),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 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:!0,fontSize:13,fontFamily:ptyPanelFontFamily(t)});e.term=a,e.host=l,a.open(l),ptyPanelFit(a,l);const o=e.id;e.unsubscribe=window.aegis.pty.onEvent(o,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"))}),"function"==typeof t.ResizeObserver&&(e.resizeObserver=new t.ResizeObserver(()=>ptyPanelFit(a,l)),e.resizeObserver.observe(l)),a.onData(e=>window.aegis.pty.write(o,e)),a.onResize(({cols:e,rows:t})=>window.aegis.pty.resize(o,e,t)),window.aegis.pty.exec(o,{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"})}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=Math.max(2,Math.floor(t.clientWidth/l.width)),o=Math.max(1,Math.floor(t.clientHeight/l.height));return a===e.cols&&o===e.rows||e.resize(a,o),{cols:a,rows:o}}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});
@@ -0,0 +1,72 @@
1
+ <!doctype html>
2
+ <!--
3
+ * SPDX-License-Identifier: AGPL-3.0-or-later
4
+ * Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
5
+ * AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
6
+ * Conveying a modified copy, or running one as a network service, owes the
7
+ * corresponding source under this licence (§5/§13) — see LICENSING.md.
8
+ -->
9
+ <html lang="en">
10
+ <head>
11
+ <meta charset="utf-8" />
12
+ <!-- ON10 — the terminal as its OWN OS WINDOW.
13
+ The panel (pty-panel.js) drew the same shell in an in-app overlay,
14
+ which covered the chat and could not leave the app's bounds. This
15
+ document is the whole window: nothing from the chat is behind it, so
16
+ the native chat stays usable while several terminals run beside it.
17
+ Same relaxed `style-src` as pty-frame.html and for the same reason —
18
+ xterm injects <style> elements and .style.* attributes (see that
19
+ file's header); this document contains xterm and no app content. -->
20
+ <meta
21
+ http-equiv="Content-Security-Policy"
22
+ content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data:"
23
+ />
24
+ <title>Terminal — aegiscode</title>
25
+ <link rel="stylesheet" href="fonts/fonts.css" />
26
+ <link rel="stylesheet" href="vendor/xterm.css" />
27
+ <style>
28
+ /* --font-mono must be declared HERE, not inherited: this document links
29
+ fonts/fonts.css (which only declares @font-face) and is not the app
30
+ window, so style.css's :root never applies. Without it pty-window.js's
31
+ ptyWinFontFamily() falls back to the host stack and the window draws in
32
+ a different face than the panel — which is the divergence
33
+ renderer-fonts.test.mjs exists to prevent, and which
34
+ pty-window-render.test.mjs caught only because it runs in Electron. */
35
+ :root { color-scheme: dark; --font-mono: 'DM Mono', monospace; }
36
+ html, body { margin: 0; height: 100%; background: #0d1117; color: #c9d1d9; }
37
+ body { display: flex; flex-direction: column; font: 12px/1.4 var(--font-ui, system-ui, sans-serif); }
38
+ #pty-win-chrome {
39
+ display: flex; align-items: center; gap: 4px; padding: 4px 6px;
40
+ background: #161b22; border-bottom: 1px solid #30363d; flex: 0 0 auto;
41
+ -webkit-app-region: drag; user-select: none;
42
+ }
43
+ #pty-win-tabs { display: flex; gap: 4px; overflow-x: auto; flex: 1 1 auto; }
44
+ .pty-win-tab {
45
+ -webkit-app-region: no-drag;
46
+ background: #21262d; color: #8b949e; border: 1px solid #30363d;
47
+ border-radius: 5px 5px 0 0; padding: 3px 10px; font: inherit; cursor: pointer;
48
+ white-space: nowrap;
49
+ }
50
+ .pty-win-tab.is-active { background: #0d1117; color: #e6edf3; border-bottom-color: #0d1117; }
51
+ #pty-win-new {
52
+ -webkit-app-region: no-drag;
53
+ background: transparent; color: #8b949e; border: 1px solid #30363d;
54
+ border-radius: 5px; width: 22px; height: 22px; line-height: 1; cursor: pointer;
55
+ }
56
+ #pty-win-new:hover { color: #e6edf3; border-color: #8b949e; }
57
+ #pty-win-body { flex: 1 1 auto; position: relative; min-height: 0; }
58
+ .pty-win-slot { position: absolute; inset: 0; padding: 4px 6px; box-sizing: border-box; }
59
+ .pty-win-slot[hidden] { display: none; }
60
+ .pty-win-note { padding: 12px; color: #8b949e; white-space: pre-wrap; }
61
+ </style>
62
+ </head>
63
+ <body>
64
+ <div id="pty-win-chrome">
65
+ <div id="pty-win-tabs" role="tablist" aria-label="Terminal sessions"></div>
66
+ <button type="button" id="pty-win-new" aria-label="New terminal" title="New terminal (Ctrl+Shift+T)">+</button>
67
+ </div>
68
+ <div id="pty-win-body"></div>
69
+ <script src="vendor/xterm.js"></script>
70
+ <script src="pty-window.js"></script>
71
+ </body>
72
+ </html>
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const 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 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=Math.max(2,Math.floor(e.clientWidth/i.width)),s=Math.max(1,Math.floor(e.clientHeight/i.height));if(o!==t.cols||s!==t.rows){ptyWinFitting=t;try{t.resize(o,s)}finally{ptyWinFitting=null}}return{cols:o,rows:s}}function ptyWinFontFamily(){return getComputedStyle(document.documentElement).getPropertyValue("--font-mono").trim()||"ui-monospace, SFMono-Regular, Menlo, monospace"}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 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});return r.term=l,l.open(s),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};
@@ -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 STICK_SLOP_PX=48;function nearBottom(t,e){const n=t||{},o=Number.isFinite(e)?e:48;return(Number(n.scrollHeight)||0)-(Number(n.scrollTop)||0)-(Number(n.clientHeight)||0)<=o}function shouldFollow(t,e){const n=e||{};return!!n.force||!n.userScrolledUp&&nearBottom(t,n.slop)}const ABORT_SIGNATURES=[/AbortError/,/\boperation was aborted\b/i,/\buser aborted\b/i,/\brequest\s+aborted\b/i,/\bsignal is aborted\b/i,/\baborted without reason\b/i];function isCancellation(t,e){if((e||{}).userStopped)return!0;if(!t)return!1;if("AbortError"===t.name||"ABORT_ERR"===t.code)return!0;const n="string"==typeof t?t:t.message;return"string"==typeof n&&ABORT_SIGNATURES.some(t=>t.test(n))}function stopAppliesTo(t,e){return null!=t&&t!==e}function salvageTurn(t){const e=t||{},n="string"==typeof e.streamedText?e.streamedText:"",o="string"==typeof e.reasoningText?e.reasoningText:"";return n?{text:n,reasoning:o,kind:"answer"}:o?{text:o,reasoning:"",kind:"reasoning-only"}:{text:"(stopped before any output)",reasoning:"",kind:"empty"}}function replayableContent(t,e){return"reasoning-only"===t?"(stopped: reasoning only)":"empty"===t?"(stopped before any output)":e}function flattenParts(t){if(null==t)return"";if("string"==typeof t)return t;if(!Array.isArray(t))return"";const e=[];for(const n of t)n&&"object"==typeof n&&("string"==typeof n.text?e.push(n.text):"image_url"===n.type&&e.push("[image]"));return e.join("\n")}function joinContent(t,e){if("string"==typeof t&&"string"==typeof e)return`${t}\n\n${e}`;const n=[],o=t=>{if("string"!=typeof t){if(Array.isArray(t))for(const e of t)e&&"object"==typeof e&&("image_url"===e.type?n.push(e):"string"==typeof e.text&&n.push({type:"text",text:e.text}))}else t.trim()&&n.push({type:"text",text:t})};o(t),o(e);const r=n.filter(t=>"text"===t.type).map(t=>t.text),s=n.filter(t=>"image_url"===t.type),i=[];return r.length&&i.push({type:"text",text:r.join("\n\n")}),i.push(...s),1===i.length&&"text"===i[0].type?i[0].text:i}function replayHistory(t){const e=[];for(const n of Array.isArray(t)?t:[]){if(!n)continue;if("user"!==n.role&&"assistant"!==n.role)continue;const t="string"==typeof n.content||Array.isArray(n.content)?n.content:"string"==typeof n.text?n.text:"",o=Array.isArray(t)?flattenParts(t):t;if(!o.trim())continue;if("assistant"===n.role&&isPlaceholderContent(o))continue;const r=e[e.length-1];r&&r.role===n.role?r.content=joinContent(r.content,t):e.push({role:n.role,content:t})}for(;e.length&&"assistant"===e[0].role;)e.shift();return e}function isPlaceholderContent(t){const e="string"==typeof t?t.trim():"";return!!e&&("(stopped: reasoning only)"===e||"(stopped before any output)"===e||"(empty response)"===e||"(no response)"===e)}const LIVE_METER_MIN_GROWTH=32,LIVE_METER_GROWTH_FRACTION=32;function liveMeterDue(t,e){const n=Number(e)||0;if(null==t)return n>0;const o=n-(Number(t)||0);return!(o<=0)&&o>=Math.max(32,Math.floor(n/32))}function toolMark(t){const e=t||{};return!0===e.ok?"✓":!1===e.ok?"✗":"⊘"}"undefined"!=typeof module&&module.exports&&(module.exports={nearBottom:nearBottom,shouldFollow:shouldFollow,isCancellation:isCancellation,stopAppliesTo:stopAppliesTo,salvageTurn:salvageTurn,replayableContent:replayableContent,isPlaceholderContent:isPlaceholderContent,replayHistory:replayHistory,liveMeterDue:liveMeterDue,toolMark:toolMark,STICK_SLOP_PX:48,LIVE_METER_MIN_GROWTH:32,LIVE_METER_GROWTH_FRACTION:32});
3
+ "use strict";const STICK_SLOP_PX=48;function nearBottom(t,e){const n=t||{},o=Number.isFinite(e)?e:48;return(Number(n.scrollHeight)||0)-(Number(n.scrollTop)||0)-(Number(n.clientHeight)||0)<=o}function shouldFollow(t,e){const n=e||{};return!!n.force||!n.userScrolledUp&&nearBottom(t,n.slop)}const ABORT_SIGNATURES=[/AbortError/,/\boperation was aborted\b/i,/\buser aborted\b/i,/\brequest\s+aborted\b/i,/\bsignal is aborted\b/i,/\baborted without reason\b/i];function isCancellation(t,e){if((e||{}).userStopped)return!0;if(!t)return!1;if("AbortError"===t.name||"ABORT_ERR"===t.code)return!0;const n="string"==typeof t?t:t.message;return"string"==typeof n&&ABORT_SIGNATURES.some(t=>t.test(n))}function stopAppliesTo(t,e){return null!=t&&t!==e}function salvageTurn(t){const e=t||{},n="string"==typeof e.streamedText?e.streamedText:"",o="string"==typeof e.reasoningText?e.reasoningText:"";return n?{text:n,reasoning:o,kind:"answer"}:o?{text:o,reasoning:"",kind:"reasoning-only"}:{text:"(stopped before any output)",reasoning:"",kind:"empty"}}function replayableContent(t,e){return"reasoning-only"===t?"(stopped: reasoning only)":"empty"===t?"(stopped before any output)":e}function flattenParts(t){if(null==t)return"";if("string"==typeof t)return t;if(!Array.isArray(t))return"";const e=[];for(const n of t)n&&"object"==typeof n&&("string"==typeof n.text?e.push(n.text):"image_url"===n.type&&e.push("[image]"));return e.join("\n")}function joinContent(t,e){if("string"==typeof t&&"string"==typeof e)return`${t}\n\n${e}`;const n=[],o=t=>{if("string"!=typeof t){if(Array.isArray(t))for(const e of t)e&&"object"==typeof e&&("image_url"===e.type?n.push(e):"string"==typeof e.text&&n.push({type:"text",text:e.text}))}else t.trim()&&n.push({type:"text",text:t})};o(t),o(e);const r=n.filter(t=>"text"===t.type).map(t=>t.text),s=n.filter(t=>"image_url"===t.type),i=[];return r.length&&i.push({type:"text",text:r.join("\n\n")}),i.push(...s),1===i.length&&"text"===i[0].type?i[0].text:i}function replayHistory(t){const e=[];for(const n of Array.isArray(t)?t:[]){if(!n)continue;if("user"!==n.role&&"assistant"!==n.role)continue;const t="string"==typeof n.content||Array.isArray(n.content)?n.content:"string"==typeof n.text?n.text:"",o=Array.isArray(t)?flattenParts(t):t;if(!o.trim())continue;if("assistant"===n.role&&isPlaceholderContent(o))continue;const r=e[e.length-1];r&&r.role===n.role?r.content=joinContent(r.content,t):e.push({role:n.role,content:t})}for(;e.length&&"assistant"===e[0].role;)e.shift();return e}function isPlaceholderContent(t){const e="string"==typeof t?t.trim():"";return!!e&&("(stopped: reasoning only)"===e||"(stopped before any output)"===e||"(empty response)"===e||"(no response)"===e)}const LIVE_METER_MIN_GROWTH=32,LIVE_METER_GROWTH_FRACTION=32;function growthGatedDue(t,e,n,o){if(null==t)return e>0;const r=e-(Number(t)||0);return!(r<=0)&&r>=Math.max(n,Math.floor(e/o))}function liveMeterDue(t,e){return growthGatedDue(t,Number(e)||0,32,32)}const MARKDOWN_RENDER_MIN_GROWTH=32,MARKDOWN_RENDER_GROWTH_FRACTION=32;function markdownRenderDue(t,e){return growthGatedDue(t,Number(e)||0,32,32)}function toolMark(t){const e=t||{};return!0===e.ok?"✓":!1===e.ok?"✗":"⊘"}"undefined"!=typeof module&&module.exports&&(module.exports={nearBottom:nearBottom,shouldFollow:shouldFollow,isCancellation:isCancellation,stopAppliesTo:stopAppliesTo,salvageTurn:salvageTurn,replayableContent:replayableContent,isPlaceholderContent:isPlaceholderContent,replayHistory:replayHistory,liveMeterDue:liveMeterDue,markdownRenderDue:markdownRenderDue,toolMark:toolMark,STICK_SLOP_PX:48,LIVE_METER_MIN_GROWTH:32,LIVE_METER_GROWTH_FRACTION:32,MARKDOWN_RENDER_MIN_GROWTH:32,MARKDOWN_RENDER_GROWTH_FRACTION:32});
@@ -6024,8 +6024,11 @@ body.keys-open {
6024
6024
  */
6025
6025
  /* ── ON9: the embedded terminal panel (renderer/pty-panel.js) ───────────────
6026
6026
  `aegiscode` running inside this window instead of a second OS process.
6027
- One overlay, one xterm.js instance; the close chip and Escape both tear it
6028
- down (pty-panel.js close()), same as the import sheet's backdrop pattern. */
6027
+ ONE overlay holding N terminals (tabs): each (cli) click adds a tab, the
6028
+ close chip tears down the active one, and closing the last removes the
6029
+ overlay (pty-panel.js close()), same as the import sheet's backdrop
6030
+ pattern. The main process was always multi-session — `pty-host.js` keys a
6031
+ Map by id — so the tabs are the whole of the multi-shell fix. */
6029
6032
  .pty-panel-overlay {
6030
6033
  position: fixed;
6031
6034
  inset: 0;
@@ -6050,14 +6053,54 @@ body.keys-open {
6050
6053
  .pty-panel-header {
6051
6054
  display: flex;
6052
6055
  align-items: center;
6053
- justify-content: space-between;
6056
+ gap: var(--s-1, 4px);
6054
6057
  padding: var(--s-2) var(--s-3);
6055
6058
  background: var(--surface3, rgba(255, 255, 255, 0.08));
6056
6059
  color: var(--text);
6057
6060
  font-weight: var(--fw-semibold);
6058
6061
  }
6059
6062
 
6063
+ /* The tab strip. Takes all spare width so + and × stay pinned right. */
6064
+ .pty-panel-tabs {
6065
+ display: flex;
6066
+ align-items: center;
6067
+ gap: var(--s-1, 4px);
6068
+ flex: 1 1 auto;
6069
+ min-width: 0;
6070
+ overflow-x: auto;
6071
+ scrollbar-width: thin;
6072
+ }
6073
+
6074
+ .pty-panel-tab {
6075
+ flex: 0 0 auto;
6076
+ background: none;
6077
+ border: 1px solid transparent;
6078
+ border-radius: var(--r-sm, 6px);
6079
+ color: var(--text-dim, var(--text));
6080
+ font: inherit;
6081
+ font-weight: var(--fw-regular, 400);
6082
+ font-size: var(--fs-sm, 13px);
6083
+ padding: 2px var(--s-2);
6084
+ cursor: pointer;
6085
+ opacity: 0.7;
6086
+ }
6087
+
6088
+ .pty-panel-tab:hover {
6089
+ opacity: 1;
6090
+ background: rgba(255, 255, 255, 0.06);
6091
+ }
6092
+
6093
+ .pty-panel-tab.is-active {
6094
+ opacity: 1;
6095
+ color: var(--text);
6096
+ font-weight: var(--fw-semibold);
6097
+ border-color: var(--border, rgba(255, 255, 255, 0.18));
6098
+ background: rgba(255, 255, 255, 0.1);
6099
+ }
6100
+
6101
+ .pty-panel-new,
6060
6102
  .pty-panel-close {
6103
+ flex: 0 0 auto;
6061
6104
  background: none;
6062
6105
  border: none;
6063
6106
  color: var(--text);
@@ -6067,8 +6110,17 @@ body.keys-open {
6067
6110
  padding: var(--s-1);
6068
6111
  }
6069
6112
 
6113
+ /* One slot per session; exactly one is visible. Every slot fills the body so
6114
+ a hidden tab's iframe keeps a non-zero box once re-shown — the re-fit in
6115
+ ptyPanelActivate() depends on that. */
6116
+ .pty-panel-slot {
6117
+ position: absolute;
6118
+ inset: var(--s-2);
6119
+ }
6120
+
6070
6121
  .pty-panel-body {
6071
6122
  flex: 1;
6123
+ position: relative;
6072
6124
  padding: var(--s-2);
6073
6125
  overflow: hidden;
6074
6126
  /* xterm.js paints its own canvas/rows inside; this just gives it a
@@ -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 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("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 -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}
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"));if(s.version)return process.stdout.write(t.version+"\n"),0;let n=!1;try{const e=require("../src/limits.js");if(n=e.armed(),n&&e.isPrivileged(s.command))return e.refuse()}catch{}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:o,describe:r}=require("../src/caps.js"),i={...process.env};if(!0===s.ascii&&(i.AEGIS_ART="ascii"),!1===s.ascii&&(i.AEGIS_ART="unicode"),!1===s.color&&(i.NO_COLOR="1"),!0===s.color&&(delete i.NO_COLOR,i.FORCE_COLOR="3"),s.width&&(i.AEGIS_WIDTH=String(s.width)),o(null,i),s.terminal){const e=r(),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("provenance"===s.command&&!n)return runProvenance({json:s.json});const{createApp:a}=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 c=require("../src/presence.js");c.start({credentials:require("../src/credentials.js"),queueDepth:c.queueDepthReader()}),process.once("exit",()=>c.stop());let d=s.prompt;if("-"===d){if(process.stdin.isTTY)return process.stderr.write("aegiscode: -p - expects a prompt on stdin\n"),2;if(d=await readStdin(),!d)return process.stderr.write("aegiscode: empty stdin\n"),2}const l=a({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:!d&&Boolean(process.stdin.isTTY),confirmMode:!s.yolo&&void 0,continue:s.continue});if(d)return l.runOnce(d,{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 u=require("../src/screen.js");u.queueExitNotice("\nResume this session with:\n aegiscode --continue (or /resume for the list)\n");const m=()=>{try{u.isAltScreen()&&u.leaveAltScreen(),u.flushExitNotice()}catch{}},p=l.runInteractive();process.once("exit",m);const h=await p;return m(),h}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});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.57",
4
+ "version": "7.0.59",
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"})),{TOOLS:s,toolList:i}=e.tools||createTools(o);let a=!1,l="";async function c(){const e=await autoProvisionApiKey(o,credentials,{app:"cli"});return l=e.key?"":provisionFailureText(e),e}async function d(){if(o.apiKey||a)return;a=!0;const e=await c();e.key&&W(render.renderNotice(v(),"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 u=!1!==e.confirmMode,m=(()=>{try{return autonomous.autoRoundsDefault(process.env)}catch{return!0}})();const f=e.engine||createEngine({client:o,getClass:()=>h.modelClass,getProEnabled:()=>{try{return proEnabled(loadConfig())}catch{return!1}},getConfirmMode:()=>{if(void 0!==e.confirmMode)return u;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 u}},getPermissionMode:()=>{try{return permissionMode()}catch{return null}}}),p=e=>"function"==typeof f.classLabel?f.classLabel(e):String(e||""),y=()=>e.width?e.width():termWidth(),h={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()};h.themeIndex===AUTO_THEME_INDEX&&(h.light=themeIsLight(AUTO_THEME_INDEX));const g=[];let k=!1;const v=()=>({light:h.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 S=null,T=!1;function E(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 C(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 I(){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=C(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=E(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 N(e,{verify:t=!0}={}){const n=credentials.saveApiKey(e);if(!n.ok)return n;o.setApiKey(n.key),_.models=[],_.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 A(){const e=credentials.clearApiKey();return o.setApiKey(""),_.models=[],_.at=0,e}function P(){try{return memoryPersistEnabled()}catch{return!0}}function x(){try{return memoryPersistState()}catch{return{enabled:!0,source:"default",explicit:!1}}}function M(e){return setMemoryPersist(e)}function O(){try{return"config"!==credentials.resolveApiKey().source?[]:credentials.adoptLegacy().adopted}catch{return[]}}const L=3e5,_={at:0,models:[]},R={at:0,models:[],declared:""};async function $({force:e=!1}={}){const t=function(){try{if("function"!=typeof f.userModels)return"";const e=(f.userModels()||{}).map||{};return JSON.stringify(Object.keys(e).sort().map(t=>[t,e[t]]))}catch{return""}}(),n=R.models.length&&Date.now()-R.at<L&&t===R.declared;if(!e&&n)return R.models;if("function"!=typeof f.listModels)return[];const r=await f.listModels("byok");return R.models=(r&&r.models||[]).map(e=>({...e,note:e.configured?"key on this machine":`no key — /byok-key ${e.provider}`})),R.at=Date.now(),R.declared=t,R.models}async function K(e){const t=B();if(e&&!t.includes(e)&&HOST_CLASSES.includes(e))return[];const n=t.includes(e)?e:h.modelClass;try{if("byok"===n){const e=await $();if(!_.models.length)try{await U()}catch{}return j(e,n)}if("pro"===n){const e=await f.listModels("pro");return(e&&e.models||[]).map(e=>({...e,cls:"pro"}))}if("aegis"!==n){const e=await f.listModels(n);return e&&e.models||[]}return await U()}catch{return[]}}function D(){return withAutoRow(pickerEntries(_.models)).map(e=>({...e,cls:"aegis"}))}function j(e,t){const n=B(),r=n.includes(t)?t:h.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 D();const o=Array.isArray(e)?e.map(e=>({...e,cls:"byok"})):pickerEntries(R.models).map(e=>({...e,cls:"byok"}));return[...D(),...o]}function q(){return new Set(claudePro.PRO_MODELS.map(e=>String(e.id).toLowerCase()))}function B(){try{return offeredClasses(proEnabled(loadConfig()))}catch{return offeredClasses(!1)}}async function U({force:e=!1}={}){const t=_.models.length&&Date.now()-_.at<L;if(!e&&t)return _.models;const n=await o.listModels();return _.models=normalizeModelCatalog(n&&n.models),_.at=Date.now(),_.models}async function H(){const e=h.model;if(!e)return null;if("byok"===h.modelClass)return String(e).includes(":")?null:(h.model=null,updateConfig({model:null,currentModelId:null}),W(render.renderNotice(v(),"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"===h.modelClass){if(!q().has(String(e).toLowerCase()))return h.model=null,updateConfig({model:null,currentModelId:null}),W(render.renderNotice(v(),"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:(h.model=null,updateConfig({model:null,currentModelId:null}),W(render.renderNotice(v(),"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 U()}catch{return null}return t.length?String(e).trim().toLowerCase()===AUTO_MODEL_ID||catalogIds(t).has(String(e).toLowerCase())?null:(h.model=null,updateConfig({model:null,currentModelId:null}),W(render.renderNotice(v(),"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 F(){return render.renderBanner(v(),{width:y(),version:VERSION,model:h.model||"server default",base:o.apiBase,key:maskKey(o.apiKey),stream:h.stream})}function W(e){const t="string"==typeof e?[e]:e;for(const e of t)n.write(e+"\n")}async function Y(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,p=0,g=VERBS[Math.floor(Math.random()*VERBS.length)],k=!1,b=!1;const T=()=>{l&&l.update([render.renderWorking(v(),{tick:c++,verb:g,elapsedMs:Date.now()-a,streamed:estimateTokensFromCells(d+m)+p,streamedFloor:p>0})])},E=l?setInterval(T,90):null;E&&E.unref&&E.unref(),T();const C=s||{},I=new Map,N=randomUUID();S=N;let A=!1;const P=()=>{A=!0,f.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&&(p+=e.thinkingTokens,k||(k=!0,g="Reasoning"),(e=>{C.thinkingTokens&&C.thinkingTokens(e)})(e.thinkingTokens),T()),e.reasoning&&(m+=w(e.reasoning),k||(k=!0,g="Reasoning",T()),(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&&T()})(e.delta)),e.tool&&(b=!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);W(render.renderTurn(v(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:defaultOpen(t)},y())),T()})(e.tool)),e.approval){const t=e.approval;l&&l.clear();const n=C.approval||M;Promise.resolve(n(t)).catch(()=>"deny").then(e=>f.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=>f.respondRoundsAsk(t.id,!0===e))}}};try{const n=await f.chat({prompt:e,messages:o,model:h.model||void 0,system:t.system||defaultSystemPrompt(),maxTokens:t.maxTokens,effort:effortRung(h.effort),recallDeep:!0===h.recallDeep||void 0,stream:!1!==h.stream,sessionId:N,sessionKey:h.sessionId,rootSessionId:h.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||h.model||null,ms:Date.now()-a,interrupted:A,reasoningChars:m,usedTools:b}}catch(e){if(A&&u)return{text:u,usage:null,model:h.model||null,ms:Date.now()-a,interrupted:!0,reasoningChars:m,usedTools:b};throw e}finally{E&&clearInterval(E),process.removeListener("SIGINT",x),i&&i.removeEventListener("abort",P),l&&l.clear(),S=null}}function V(e){W(render.renderTurn(v(),e,y()))}async function G(e,{label:t="you"}={}){if(!e)return void W(render.renderNotice(v(),"warn","nothing to ask — give /ask a prompt"));if(o.apiKey||await d(),!o.apiKey)return void W(render.renderNotice(v(),"error",`no AEGIS account key — ${credentials.HOW_TO_SET} (or set $${credentials.KEY_ENV})`));const n=g.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.text}));let r;V({role:"user",text:e,label:t}),g.push({role:"user",text:e});try{r=await Y(e,{history:n})}catch(t){return ie(e,{text:"",error:t.message},"error"),void W(render.renderTurn(v(),{role:"error",text:t.message},y()))}r.text&&g.push({role:"assistant",text:r.text});const s=se(r);let i=null;try{const e=await I();i=e?e.lastCost:null}catch{}ie(e,r,r.interrupted?"stopped":r.error?"error":"done",i),V({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&&W(render.renderNotice(v(),"warn","interrupted — the pool may still be running and billing this call"))}async function z(e,t){const n=s[e];if(!n)throw new Error(`unknown tool: ${e}`);if(o.apiKey||await d(),!o.apiKey)throw new Error(`no AEGIS account key — ${credentials.HOW_TO_SET}`);const r=await n.run(t||{});W(render.renderToolResult(v(),e,r,y()))}function X(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 J(){const e=loadPermissions(),t=confirmPosture();return{version:VERSION,model:h.model||"server default",class:h.modelClass,effort:h.effort,thinking:h.thinking,theme:h.light?"light":"dark",themeIndex:h.themeIndex,vim:h.vim,stream:h.stream,cwd:h.cwd,home:os.homedir(),sessionId:h.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:j(),commands:visibleCommands(),transcript:g.slice(),sessions:[],memory:{},lastRecap:h.lastRecap,backend:h.modelClass,url:o.apiBase}}function Q(e){return Array.isArray(e)?e.map(e=>e&&(e.s||"")+(null==e.t?"":e.t)||"").join(""):String(null==e?"":e)}function Z(e){if(!e||"object"!=typeof e)return;const t=y();switch(e.role){case"panel":{const t=Array.isArray(e.lines)?e.lines:[];for(const e of t)W(Q(e));return}case"note":case"tip":return void W(render.renderNotice(v(),"info",e.text));case"done":return void W(render.renderNotice(v(),"ok",e.text));case"error":return void W(render.renderNotice(v(),"error",e.text));case"user":return void W(render.renderTurn(v(),{role:"user",text:e.text,label:e.label},t));case"assistant":return void W(render.renderTurn(v(),{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 W(render.renderTurn(v(),{role:"tool",label:e.label||e.name,args:e.args,ok:e.ok,diff:e.diff,diffOpen:!!e.diffOpen},t));default:return void W(render.renderNotice(v(),"info",null==e.text?"":String(e.text)))}}function ee(e){return{t:e,s:"",w:w(e)}}async function te(){return!e.readline&&process.stdin.isTTY&&process.stdout.isTTY&&!1!==e.chatflow?screens.showThemePicker(h):(h.light=!h.light,h.themeIndex=h.light?2:1,W(render.renderNotice(v(),"ok","theme: "+(h.light?"light":"dark"))),h.themeIndex)}function ne(){const e={ctx:h,transcript:g,push:e=>Z(e),note:e=>Z({role:"note",text:e}),panel:e=>Z({role:"panel",lines:e}),render:()=>{},openOverlay:e=>function(e){if(!e||"object"!=typeof e)return;const t=y(),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||"",sel:e.sel||0},t,n):"model"===e.type?r=overlays.renderModelPicker(e.items||[],e.sel||0,t,n,null!=e.current?e.current:h.model,e.cls||h.modelClass,p):"effort"===e.type?r=overlays.renderEffortPicker(e.sel||0,t,h.effort):"class"===e.type?r=overlays.renderClassPicker(e.items||[],e.sel||0,t,e.current||h.modelClass,p):"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(v(),e.info||{},t).map(e=>[ee(e)])),r)for(const e of r)W(Q(e))}(e),closeOverlay:()=>{},setAutoRounds:e=>{m=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(v(),{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=>G(e),ask:e=>Y(e),runTool:(e,t)=>z(e,t),loadModels:()=>K(h.modelClass),settings:()=>f.settings||null,byokNamespace:e=>byokNamespace(e),listModelsFor:e=>K(e),refreshByokModels:()=>$({force:!0}),switchClass:e=>function(e){const t=String(null==e?"":e).trim().toLowerCase(),n=B();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=h.modelClass;h.modelClass=t;let o=null;return r!==t&&h.model&&(function(e,t){const n=String(null==t?"":t);return"byok"===e?n.includes(":"):"pro"===e?q().has(n.toLowerCase()):!n.includes(":")}(t,h.model)||(o=h.model,h.model=null)),updateConfig({modelClass:t,model:h.model,currentModelId:h.model}),{ok:!0,class:t,prev:r,cleared:o}}(e),classLabel:e=>p(e),classes:()=>"function"==typeof f.listClasses?f.listClasses():[],refreshSpend:()=>I(),state:()=>J(),setInput:()=>{},exit:()=>{k=!0},client:o,TOOLS:s,saveConfig:e=>updateConfig(e),showThemePicker:()=>te(),keyStatus:()=>credentials.keyStatus(),setApiKey:(e,t)=>N(e,t),forgetApiKey:()=>A(),registerAccount:()=>async function(){return o.apiKey?{alreadyKeyed:!0}:c()}(),readSecret:e=>readSecret(e,{stdin:process.stdin,stdout:n}),cloudsync:cloudsync,cloudSyncEnabled:()=>P(),cloudSyncState:()=>x(),setCloudSync:e=>M(e),adoptLegacyKey:()=>O()};return Object.defineProperty(e,"sessionId",{enumerable:!0,get:()=>h.sessionId,set:e=>{h.sessionId=e}}),e.clearConversationMemory=()=>{f&&"function"==typeof f.clearSessionApprovals&&f.clearSessionApprovals(h.sessionId)},e.listUndoable=()=>f&&"function"==typeof f.listUndoable?f.listUndoable(h.sessionId):[],e.undoMutation=e=>f&&"function"==typeof f.undoMutation?f.undoMutation(h.sessionId,e):{ok:!1,error:"undo is not available on this engine"},e}async function re(e,t=null){const r=parseLine(e);if("empty"===r.kind)return!0;if("prompt"===r.kind)return await G(r.text),!0;if("unknown"===r.kind){const e=X(r.name);return W(render.renderNotice(v(),"error",`unknown command: /${r.name}${e?` — did you mean /${e}?`:" — try /help"}`)),!0}if("unavailable"===r.kind){const e=r.command;if(W(render.renderNotice(v(),"warn",`/${e.name} is not available in aegiscode — ${e.unavailable}`)),e.alt)W(render.renderNotice(v(),"info",`try ${e.alt} instead`));else{const t=X(e.name);t&&W(render.renderNotice(v(),"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 W(render.renderNotice(v(),"error",e.message)),!0}const{tool:n,args:r}=t;if(!n)return W(render.renderNotice(v(),"error","/tool needs a tool name — see /help")),!0;try{await z(n,r)}catch(e){W(render.renderNotice(v(),"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||ne();try{return!1!==await s.handler(r,n)}catch(e){return W(render.renderNotice(v(),"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&&W(render.renderNotice(v(),"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(v());return readSecret(t.gray+e+RESET,{stdin:process.stdin,stdout:n})}(t&&t.prompt||`provider key for ${e.provider}: `);if(!r)return W(render.renderNotice(v(),"warn","empty key — nothing sent")),!0;e={...e,api_key:r}}if("aegis_ask"===s.tool)return await G(e.prompt);await z(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?W(render.renderNotice(v(),"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.`)):W(render.renderNotice(v(),"info",`cloud memory: ${n} of ${r} synced tokens — /cloud memory for the full state`))}()}catch(e){W(render.renderNotice(v(),"error",e.message))}return!0}async function oe(){if(f&&"function"==typeof f.unloadLocalModels)try{await f.unloadLocalModels()}catch{}}function se(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 ie(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||h.model||"").trim();appendHistory({sessionId:h.sessionId,prompt:e,reply:t&&t.text||"",status:n,model:i||void 0,provider:i&&providerForModel({id:i,cls:h.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(h.sessionId,g)}catch{}P()&&o.apiKey&&Promise.resolve().then(()=>cloudsync.push(o)).then(e=>{if(e&&e.failed&&e.failed.length){const t=e.failed[0];if(ae.has(t.kind))return;if(ae.add(t.kind),"quota"===t.kind)return void W(render.renderNotice(v(),"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}`:"";W(render.renderNotice(v(),"error",`cloud sync: ${t.message}${n}`))}}).catch(()=>{})}let ae=new Set;function le(){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 ce(e){if(!e||!e.id)return;const t=readSessionTranscript(e.id);if(t.length){g.length=0;for(const e of t)g.push(e);h.sessionId=e.id,W(render.renderNotice(v(),"ok",`resumed ${e.id} — ${t.length} turn(s)`))}else W(render.renderNotice(v(),"warn",`no stored turns for ${e.id}`))}function de(){return{ctx:h,version:VERSION,transcript:g,session:b,client:o,TOOLS:s,ask:(e,t)=>Y(e,t),makeCommandContext:()=>ne(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=f.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=>U(e),buildState:()=>J(),dispatchLine:(e,t)=>re(e,t),refreshSpend:()=>I(),updateConfig:e=>updateConfig(e),showThemePicker:()=>te(),persistTurn:(e,t,n,r)=>ie(e,t,n,r),nameConversation:(e,t)=>async function(e,{signal:t=null}={}){const n=await naming.nameConversation(e,{signal:t,callModel:(e,n)=>Y(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(h.sessionId,r),r}(e,t),visibleCommands:()=>visibleCommands(),tokensFor:e=>usageTokens(e),recordTurn:e=>se(e),tokenSummary:()=>le(),resumeSession:e=>ce(e),requestExit:()=>{k=!0},wantsExit:()=>k,keyNotice:()=>o.apiKey?"":l,isYolo:()=>{if(!m)return!1;try{return!1===confirmPosture().enabled}catch{return!1}},setAutoRounds:e=>{m=Boolean(e)}}}async function ue(){W(F()),await I(),n.write("\n");const t=e.readline||readline.createInterface({input:process.stdin,output:n,terminal:!0}),r=themeOf(v()).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 re(e)}catch(e){W(render.renderNotice(v(),"error",e.message))}if(!n||k)return T=!0,void t.close();t.resume(),t.prompt()}),t.on("close",()=>{T||n.write("\n"),e(0)})})}function me(){if(e.readline)return;if(!configExists())return;let n;try{n=loadConfig()}catch{return}if(B().includes(n.modelClass)&&(h.modelClass=n.modelClass),t.class){const e=String(t.class).trim().toLowerCase();if(!B().includes(e))throw new Error(`--class ${t.class}: not available on this host (offered: ${B().join(", ")})`);h.modelClass=e}if(!t.model&&n.model&&(h.model=n.model),h.effort=effortRung(t.effort||n.effort),"boolean"==typeof n.vim&&(h.vim=n.vim),n.lastRecap&&(h.lastRecap=n.lastRecap),!t.light&&"number"==typeof n.themeIndex&&THEME_TABLE[n.themeIndex]){h.themeIndex=n.themeIndex,h.light=themeIsLight(n.themeIndex);const e=reconcileThemeIndex(h.themeIndex);if(e.changed){h.themeIndex=e.index,h.light=themeIsLight(e.index),h.themeNotice=e.reason;try{updateConfig({themeIndex:e.index,light:themeIsLight(e.index)})}catch{h.themeNotice+=" (could not save it)"}}}}return{opts:t,session:b,client:o,TOOLS:s,toolList:i,ctx:h,transcript:g,ask:Y,runPrompt:G,handleLine:re,runOnce:async function(e,t={}){try{return await async function(e,{json:t=!1}={}){if(me(),O(),!o.apiKey&&!a){a=!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 I();const s=[],i=[],l=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(v(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:!1},y());for(const e of Array.isArray(n)?n:[n])r.write(e+"\n")}}:null,c=await Y(e,l?{presenter:l}:{});await I();const d=usageTokens(c.usage),u=providerRefusal(c.text,c.usage);if(t)n.write(JSON.stringify({text:c.text,model:c.model,class:h.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(v());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 oe()}},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})}),me(),function(){if(!h.themeNotice)return;const e=h.themeNotice;h.themeNotice="",W(render.renderNotice(v(),"warn",`theme: ${e} (saved)`))}(),O(),o.apiKey||await d();const t=await screens.runOnboarding(h,{continue:!!e.continue,seen:e.seen||configExists,save:e=>updateConfig(e),needsKey:()=>!o.apiKey,submitKey:e=>N(e)});if(!t.ok)return 0;if(t.key&&t.key.set&&W(render.renderNotice(v(),"info",`key saved to ${credentials.credentialsPath()} — no export needed from now on`)),t.key&&t.key.skipped&&!o.apiKey&&W(render.renderNotice(v(),"warn","no key saved — /key <api_key> or `aegiscode login` whenever you are ready")),t.firstRun&&function(){if(!x().enabled)return void W(render.renderNotice(v(),"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)`:"";W(render.renderNotice(v(),"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 H(),e.continue){const e=readOwnSessions(1)[0];e&&(h.continueSession=e.id,await ce({id:e.id}))}return await I(),runAutoModelSync(h).catch(()=>{}),await chatflow.runSession(de()),0}return me(),O(),ue()}()}finally{await oe()}},runLinearRepl:ue,refreshSpend:I,bannerLines:F,makeHost:de,loadModels:U,validatePinnedModel:H,recordTurn:se,persistTurn:ie,restorePrefs:me,setApiKey:N,forgetApiKey:A,adoptLegacyKeyOnce:O,cloudSyncEnabled:P,cloudSyncState:x,setCloudSync:M,cloudsync:cloudsync,keyStatus:()=>credentials.keyStatus(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=f.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:()=>h.sessionId,tokenSummary:le,resumeSession:ce,makeCommandContext:ne,buildState:J,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(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||"",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};