aegisone 1.0.50 → 1.0.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # AEGISONE
2
2
 
3
- Product version: **1.0.50**
3
+ Product version: **1.0.52**
4
4
 
5
5
  One product, two faces: the terminal (`aegiscode`) and the window (`aegis-desktop`),
6
6
  reached through one command — `aegis` — and released as one version.
package/bin/aegis.js CHANGED
@@ -1,4 +1,4 @@
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 fs=require("node:fs"),path=require("node:path"),{spawnSync:spawnSync,spawn:spawn}=require("node:child_process"),{decide:decide,FACE:FACE}=require("../src/dispatch.js"),WIN=require("../src/iface/window.js"),probes=require("../src/probes.js"),release=require("../src/release.js"),productHelp=require("../src/producthelp.js"),EXIT_USAGE=2,PRODUCT=require("../package.json");function faceManifestPaths(e,s){const r=s||__dirname;return[path.join(r,"..","vendor",e.dir,"package.json"),path.join(r,"..","..",e.dir,"package.json")]}function readFaceVersions(e){return release.FACE_LINES.map((s=>{for(const r of faceManifestPaths(s,e))try{return{package:s.package,version:JSON.parse(fs.readFileSync(r,"utf8")).version,source:r}}catch{}return{package:s.package,version:null,source:null}}))}function write(e,s){try{e.write(s.endsWith("\n")?s:s+"\n")}catch{}}function statusOf(e){return"number"==typeof e.status?e.status:"SIGINT"===e.signal?130:"SIGTERM"===e.signal?143:1}function run(e,s){const r=s||{},n=r.stderr||process.stderr,t=r.stdout||process.stdout,i=r.input||probes.collect({argv:e}),o=Array.isArray(e)?{...i,argv:e}:i,a=release.versionRequest(o.argv);if(a){const e=a.verbose?r.readFaceVersions?r.readFaceVersions():readFaceVersions(r.binDir):null;return write(t,release.renderVersion({product:{name:PRODUCT.name,version:PRODUCT.version},faces:e})),0}if((r.helpRequest||productHelp.helpRequest)(o.argv))return write(t,productHelp.renderHelp({version:PRODUCT.version})),0;const c=(o.argv||[]).indexOf("doctor");if(-1!==c&&!(o.argv||[]).slice(0,c).some((e=>!e.startsWith("-")))){const e=r.doctor||require("../src/doctor.js"),s=Object.assign({env:o.env,stdout:t,electron:o._electron||r.electron||null},r.doctorDeps||{}),n=e.main((o.argv||[]).slice(c+1),s);return"number"==typeof n?n:EXIT_USAGE}const d=decide(o),u=r.permissions||require("../src/permissions.js"),p=(o.argv||[]).indexOf(u.SKIP_FLAG||"--dangerously-skip-permissions"),l=Boolean(o.tty&&o.tty.stdin&&o.tty.stdout),g=l?"interactive":"headless",f=r.stored||u.storedPermissionFacts(r.storedOpts||{}),w=u.resolvePosture({rules:void 0!==r.rules?r.rules:f.rules,gate:void 0!==r.gate?r.gate:f.confirmationsOn,permissionMode:void 0!==r.permissionMode?r.permissionMode:f.permissionMode,flag:-1!==p,env:o.env,interactive:l,childKind:g});w.warning&&write(n,`aegis: ${w.warning}`),w.skip&&w.skipFromFlag&&write(n,u.skipReport(w));const h=-1===p?d.args:d.args.filter((e=>e!==(u.SKIP_FLAG||"--dangerously-skip-permissions"))),m=w.skipFromFlag?{AEGISONE_SKIP_PERMISSIONS:"1"}:{};if("1"===(o.env||{}).AEGISONE_PRINT_DECISION&&write(n,"aegis: decision "+JSON.stringify({face:d.face,kind:d.kind,reason:d.reason,args:h,skip:w.skip})),null===d.face)return write(n,`aegis: ${d.error}`),d.hint&&write(n,`aegis: ${d.hint}`),d.code||EXIT_USAGE;d.notice&&write(n,`aegis: ${d.notice} — running the terminal face.`);const v=r.spawnSync||spawnSync,E=r.spawn||spawn,I=Object.assign({},process.env,r.env||{});if(d.face===FACE.TUI){const e=o._cliBin||r.cliBin;return e?statusOf(v(process.execPath,[e,...h],{stdio:"inherit",env:Object.assign({},I,m),argv0:"aegiscode"})||{}):(write(n,"aegis: the terminal face is not installed beside aegisone."),write(n,"aegis: reinstall aegisone, or set AEGISONE_CLI_BIN to bin/aegiscode.js."),127)}const S=o._electron||r.electron,O=o._desktopMain||r.desktopMain,_=WIN.plan({decision:d,electron:Boolean(S),target:r.target||o.target});if(!_||!O)return write(n,"aegis: cannot open the window — Electron or the desktop entry point went missing after the check."),write(n,"aegis: Use --tui for the terminal face."),EXIT_USAGE;delete I.ELECTRON_RUN_AS_NODE;const k=WIN.open(_,{main:O,args:h,env:Object.assign({},I,m)},{openElectron:e=>E(process.execPath,[e.main,...e.args],{stdio:"inherit",env:e.env,detached:!1})});if(!k||!k.ok)return write(n,`aegis: cannot open the window — ${k&&k.msg||"no usable window plan"}.`),write(n,"aegis: Use --tui for the terminal face."),EXIT_USAGE;const y=k.handle;return new Promise((e=>{y.on("error",(s=>{write(n,`aegis: could not start the window: ${s&&s.message}`),e(1)})),y.on("exit",((s,r)=>e(statusOf({status:s,signal:r}))))}))}function main(e){const s=run(e);return"number"==typeof s?(process.exitCode=s,s):s.then((e=>(process.exitCode=e,e)))}if(module.exports={main:main,run:run,statusOf:statusOf,EXIT_USAGE:EXIT_USAGE},require.main===module){const e=main(process.argv.slice(2));e&&"function"==typeof e.then&&e.catch((e=>{write(process.stderr,`aegis: ${e&&e.stack||e}`),process.exitCode=1}))}
4
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{spawnSync:spawnSync,spawn:spawn}=require("node:child_process"),{decide:decide,FACE:FACE}=require("../src/dispatch.js"),WIN=require("../src/iface/window.js"),probes=require("../src/probes.js"),release=require("../src/release.js"),productHelp=require("../src/producthelp.js"),productUpdate=require("../src/productupdate.js"),EXIT_USAGE=2,PRODUCT=require("../package.json");function faceManifestPaths(e,t){const r=t||__dirname;return[path.join(r,"..","vendor",e.dir,"package.json"),path.join(r,"..","..",e.dir,"package.json")]}function readFaceVersions(e){return release.FACE_LINES.map((t=>{for(const r of faceManifestPaths(t,e))try{return{package:t.package,version:JSON.parse(fs.readFileSync(r,"utf8")).version,source:r}}catch{}return{package:t.package,version:null,source:null}}))}function write(e,t){try{e.write(t.endsWith("\n")?t:t+"\n")}catch{}}function runUpdate(e,t,r){const s=t||{},{stdout:n,stderr:i,input:o}=r,a=void 0!==s.installed?s.installed:isInstalledLayout(s.binDir),c=s.updatePlan?s.updatePlan():productUpdate.plan({installed:a,env:o&&o.env||{}});if(!c.ok)return write(i,`aegis: ${c.msg}`),EXIT_USAGE;const u=s.fetchLatest||defaultFetchLatest(s.binDir);return productUpdate.check({current:PRODUCT.version,action:e.action},{fetchImpl:u}).then((t=>{for(const e of t.lines)write(n,e);if("apply"!==e.action)return!0===t.upToDate?0:1;const r=productUpdate.apply(c,t,{runImpl:s.runInstall||defaultRunInstall});if(r.ok){write(n,r.lines?r.lines[0]:"Installed.");for(const e of String(r.output||"").split("\n").slice(-6))e.trim()&&write(n,` ${e}`);return 0}return r.skipped?(write(n,` ${r.msg}`),!0===t.upToDate?0:1):(write(i,`aegis: ${r.msg||"the install failed"}`),r.error&&write(i,`aegis: ${r.error}`),r.command&&write(i,`aegis: run it yourself: ${r.command}`),3)}))}function isInstalledLayout(e){const t=e||__dirname,r=path.join(t,"..");try{return!fs.existsSync(path.join(r,"..","one","package.json"))}catch{return!0}}function defaultFetchLatest(e){const t=e||__dirname,r=path.join(t,".."),s=[path.join(r,"client","update.js"),path.join(r,"vendor","cli","vendor","client","update.js")];for(const e of s)try{const t=require(e);if("function"==typeof t.fetchLatestDetailed)return e=>t.fetchLatestDetailed({...e||{},pkg:productUpdate.PRODUCT_PKG});if("function"==typeof t.fetchLatest)return e=>t.fetchLatest({...e||{},pkg:productUpdate.PRODUCT_PKG})}catch{}return null}function defaultRunInstall(e){try{const t=spawnSync(e.command,e.args,{encoding:"utf8",timeout:18e4,stdio:["ignore","pipe","pipe"],shell:!0===e.shell,windowsHide:!0});return t.error?{ok:!1,error:String(t.error.message||t.error)}:0!==t.status?{ok:!1,error:String((t.stderr||t.stdout||"").trim()||`exited ${t.status}`)}:{ok:!0,output:String(t.stdout||"")}}catch(e){return{ok:!1,error:String(e&&e.message||e)}}}function statusOf(e){return"number"==typeof e.status?e.status:"SIGINT"===e.signal?130:"SIGTERM"===e.signal?143:1}function run(e,t){const r=t||{},s=r.stderr||process.stderr,n=r.stdout||process.stdout,i=r.input||probes.collect({argv:e}),o=Array.isArray(e)?{...i,argv:e}:i,a=release.versionRequest(o.argv);if(a){const e=a.verbose?r.readFaceVersions?r.readFaceVersions():readFaceVersions(r.binDir):null;return write(n,release.renderVersion({product:{name:PRODUCT.name,version:PRODUCT.version},faces:e})),0}if((r.helpRequest||productHelp.helpRequest)(o.argv))return write(n,productHelp.renderHelp({version:PRODUCT.version})),0;const c=(r.updateRequest||productUpdate.updateRequest)(o.argv);if(c&&"help"===c.action)return write(n,productUpdate.renderUsage(PRODUCT.version)),0;if(c)return runUpdate(c,r,{stdout:n,stderr:s,input:o});const u=(o.argv||[]).indexOf("doctor");if(-1!==u&&!(o.argv||[]).slice(0,u).some((e=>!e.startsWith("-")))){const e=r.doctor||require("../src/doctor.js"),t=Object.assign({env:o.env,stdout:n,electron:o._electron||r.electron||null},r.doctorDeps||{}),s=e.main((o.argv||[]).slice(u+1),t);return"number"==typeof s?s:EXIT_USAGE}const d=decide(o),p=r.permissions||require("../src/permissions.js"),l=(o.argv||[]).indexOf(p.SKIP_FLAG||"--dangerously-skip-permissions"),f=Boolean(o.tty&&o.tty.stdin&&o.tty.stdout),g=f?"interactive":"headless",h=r.stored||p.storedPermissionFacts(r.storedOpts||{}),m=p.resolvePosture({rules:void 0!==r.rules?r.rules:h.rules,gate:void 0!==r.gate?r.gate:h.confirmationsOn,permissionMode:void 0!==r.permissionMode?r.permissionMode:h.permissionMode,flag:-1!==l,env:o.env,interactive:f,childKind:g});m.warning&&write(s,`aegis: ${m.warning}`),m.skip&&m.skipFromFlag&&write(s,p.skipReport(m));const w=-1===l?d.args:d.args.filter((e=>e!==(p.SKIP_FLAG||"--dangerously-skip-permissions"))),v=m.skipFromFlag?{AEGISONE_SKIP_PERMISSIONS:"1"}:{};if("1"===(o.env||{}).AEGISONE_PRINT_DECISION&&write(s,"aegis: decision "+JSON.stringify({face:d.face,kind:d.kind,reason:d.reason,args:w,skip:m.skip})),null===d.face)return write(s,`aegis: ${d.error}`),d.hint&&write(s,`aegis: ${d.hint}`),d.code||EXIT_USAGE;d.notice&&write(s,`aegis: ${d.notice} — running the terminal face.`);const I=r.spawnSync||spawnSync,S=r.spawn||spawn,E=Object.assign({},process.env,r.env||{});if(d.face===FACE.TUI){const e=o._cliBin||r.cliBin;return e?statusOf(I(process.execPath,[e,...w],{stdio:"inherit",env:Object.assign({},E,v),argv0:"aegiscode"})||{}):(write(s,"aegis: the terminal face is not installed beside aegisone."),write(s,"aegis: reinstall aegisone, or set AEGISONE_CLI_BIN to bin/aegiscode.js."),127)}const k=o._electron||r.electron,y=o._desktopMain||r.desktopMain,_=WIN.plan({decision:d,electron:Boolean(k),target:r.target||o.target});if(!_||!y)return write(s,"aegis: cannot open the window — Electron or the desktop entry point went missing after the check."),write(s,"aegis: Use --tui for the terminal face."),EXIT_USAGE;delete E.ELECTRON_RUN_AS_NODE;const U=WIN.open(_,{main:y,args:w,env:Object.assign({},E,v)},{openElectron:e=>S(process.execPath,[e.main,...e.args],{stdio:"inherit",env:e.env,detached:!1})});if(!U||!U.ok)return write(s,`aegis: cannot open the window — ${U&&U.msg||"no usable window plan"}.`),write(s,"aegis: Use --tui for the terminal face."),EXIT_USAGE;const O=U.handle;return new Promise((e=>{O.on("error",(t=>{write(s,`aegis: could not start the window: ${t&&t.message}`),e(1)})),O.on("exit",((t,r)=>e(statusOf({status:t,signal:r}))))}))}function main(e){const t=run(e);return"number"==typeof t?(process.exitCode=t,t):t.then((e=>(process.exitCode=e,e)))}if(module.exports={main:main,run:run,statusOf:statusOf,EXIT_USAGE:EXIT_USAGE,isInstalledLayout:isInstalledLayout,defaultFetchLatest:defaultFetchLatest},require.main===module){const e=main(process.argv.slice(2));e&&"function"==typeof e.then&&e.catch((e=>{write(process.stderr,`aegis: ${e&&e.stack||e}`),process.exitCode=1}))}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegisone",
3
3
  "productName": "AEGISONE",
4
- "version": "1.0.50",
4
+ "version": "1.0.52",
5
5
  "description": "AEGISONE — one product, two faces. `aegis` opens the window when there is nothing else to do and runs the terminal otherwise; `aegiscode` keeps behaving exactly as it always has.",
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 HELP_REQUESTS=new Set(["--help","-h","help"]);function helpRequest(e){const n=(Array.isArray(e)?e:[]).map(String);return 1===n.length&&HELP_REQUESTS.has(n[0])}function renderHelp(e){const n=e||{};return[`aegis ${n.version?String(n.version):"unknown"} — one product, two faces`,"","Usage:"," aegis open the window (falls back to the terminal when it cannot)"," aegis desktop open the window, and fail loudly if it cannot"," aegis code [args…] run the terminal face, forwarding args to it"," aegis --tui [args…] the same thing, spelled as a flag"," aegis doctor [--json] report on this install; exit 0 healthy, 1 warn, 2 broken"," aegis --version [--verbose] this product's version, and each face's with --verbose","","Anything else with arguments — a prompt, a verb, a flag — goes to the terminal face.","Run `aegis code --help` for that face's own flags, or `aegis doctor` when something looks wrong."].join("\n")+"\n"}module.exports={helpRequest:helpRequest,renderHelp:renderHelp,HELP_REQUESTS:HELP_REQUESTS};
3
+ "use strict";const HELP_REQUESTS=new Set(["--help","-h","help"]);function helpRequest(e){const n=(Array.isArray(e)?e:[]).map(String);return 1===n.length&&HELP_REQUESTS.has(n[0])}function renderHelp(e){const n=e||{};return[`aegis ${n.version?String(n.version):"unknown"} — one product, two faces`,"","Usage:"," aegis open the window (falls back to the terminal when it cannot)"," aegis desktop open the window, and fail loudly if it cannot"," aegis code [args…] run the terminal face, forwarding args to it"," aegis --tui [args…] the same thing, spelled as a flag"," aegis doctor [--json] report on this install; exit 0 healthy, 1 warn, 2 broken"," aegis update [check|apply] check for a newer release (apply: install it now)"," aegis --version [--verbose] this product's version, and each face's with --verbose","","Anything else with arguments — a prompt, a verb, a flag — goes to the terminal face.","Run `aegis code --help` for that face's own flags, or `aegis doctor` when something looks wrong."].join("\n")+"\n"}module.exports={helpRequest:helpRequest,renderHelp:renderHelp,HELP_REQUESTS:HELP_REQUESTS};
@@ -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 PRODUCT_PKG="aegisone",ACTION=Object.freeze({CHECK:"check",APPLY:"apply"}),CODE=Object.freeze({BAD_INPUT:"bad_input",NO_CHANNEL:"no_channel",NO_APPROACH:"no_approach",NOTHING:"nothing_to_apply",INSTALL_FAILED:"install_failed",SOURCE_LIKE:"source_like"}),HELP_WORDS=new Set(["--help","-h","help"]),ACTIONS=Object.freeze({"":ACTION.CHECK,check:ACTION.CHECK,status:ACTION.CHECK,apply:ACTION.APPLY,install:ACTION.APPLY});function updateRequest(e){const t=(Array.isArray(e)?e:[]).map(String);if(0===t.length)return null;if("update"!==t[0])return null;if(1===t.length)return{action:ACTION.CHECK};if(2!==t.length)return null;const n=t[1].trim().toLowerCase();return HELP_WORDS.has(n)?{action:"help"}:Object.prototype.hasOwnProperty.call(ACTIONS,n)&&n?{action:ACTIONS[n]}:null}function compareVersions(e,t){const n=e=>String(null==e?"0":e).trim().replace(/^v/,"").split("-")[0].split(".").map((e=>Number.parseInt(e,10)||0)),r=n(e),o=n(t);for(let e=0;e<Math.max(r.length,o.length);e++){const t=(r[e]||0)-(o[e]||0);if(t)return t>0?1:-1}return 0}function plan(e){const t=e||{},n=t.env||{};return"source"===String(n.AEGIS_INSTALL_METHOD||"").trim().toLowerCase()||!1===t.installed?{ok:!1,code:CODE.SOURCE_LIKE,msg:"this copy is a source checkout: updating it means `git pull && npm ci`, not a self-update"}:{ok:!0,channel:"npm",selfUpdate:!0,reason:`installed from npm, so \`npm i -g ${PRODUCT_PKG}@latest\` owns this copy`}}function advice(e){const t=e||{},n=String(null==t.current?"":t.current),r=`npm i -g ${t.pkg||PRODUCT_PKG}@latest`;if(!t.latest)return{upToDate:null,command:null,lines:[` Installed: ${n}`," Published: (could not read the npm registry)",` Upgrade: ${r} — run it yourself; this check needs the registry`]};const o=String(t.latest);return compareVersions(o,n)>0?{upToDate:!1,command:r,lines:[` Installed: ${n}`,` Published: ${o}`,` Upgrade: ${r}`," (or run `aegis update apply` to do it here)"]}:{upToDate:!0,command:null,lines:[` Installed ${n} is the published ${o} — nothing to upgrade.`]}}async function check(e,t){const n=e||{},r=t||{},o=String(null==n.current?"":n.current),a=n.pkg||PRODUCT_PKG,s=r.fetchImpl;let l=null,i=null;if("function"==typeof s)try{const e=await s({pkg:a});e&&"object"==typeof e?(l=e.latest?String(e.latest):null,i=e.reason?String(e.reason):null):e&&(l=String(e))}catch{l=null,i="network"}else i="no_approach";const c=advice({current:o,latest:l,pkg:a,action:n.action});return{ok:Boolean(l),current:o,latest:l,upToDate:c.upToDate,command:c.command,lines:c.lines,reason:i}}function apply(e,t,n){const r=n||{};if(!e||!e.ok)return{ok:!1,code:e&&e.code||CODE.BAD_INPUT,msg:e&&e.msg||"no usable update plan"};if(!e.selfUpdate)return{ok:!1,code:CODE.NO_CHANNEL,msg:`the ${e.channel} channel is not self-updating: ${e.reason}`};if(!t||!0!==t.ok||!1!==t.upToDate||!t.command){const e=t?!0===t.upToDate?"nothing to apply: this copy is already the published version":"nothing to apply: the registry could not be read, so no newer version was established":"nothing to apply: no newer version was established";return{ok:!1,code:CODE.NOTHING,skipped:!0,msg:e}}const o=r.runImpl;if("function"!=typeof o)return{ok:!1,code:CODE.NO_APPROACH,msg:"no install step was injected",instruction:t.command};const a=r.spawnSpec||{command:"npm",args:["i","-g",`${r.pkg||PRODUCT_PKG}@latest`],shell:!1};let s;try{s=o(a)}catch(e){return{ok:!1,code:CODE.INSTALL_FAILED,command:t.command,error:String(e&&(e.stderr||e.message)||e).trim()}}return s&&!0===s.ok?{ok:!0,command:t.command,output:String(s&&s.output||"").trim(),lines:[`Installed ${t.latest}. Restart \`aegis\` to use it.`]}:{ok:!1,code:CODE.INSTALL_FAILED,command:t.command,error:String(s&&(s.error||s.stderr)||"the installer exited non-zero").trim()}}function renderUsage(e){return["aegis update — check for, or install, a newer published AEGISONE","","Usage:"," aegis update report the installed and published versions"," aegis update check the same report"," aegis update apply install the newer release, if there is one","",` Package: ${PRODUCT_PKG}${e?` Installed: ${e}`:""}`," A source checkout is refused: there, updating means `git pull && npm ci`."].join("\n")+"\n"}module.exports={PRODUCT_PKG:PRODUCT_PKG,ACTION:ACTION,ACTIONS:ACTIONS,HELP_WORDS:HELP_WORDS,CODE:CODE,updateRequest:updateRequest,compareVersions:compareVersions,plan:plan,advice:advice,check:check,apply:apply,renderUsage:renderUsage};
@@ -1,29 +1,40 @@
1
- # aegiscode — the terminal host
1
+ # aegiscode — the assistant in your terminal
2
2
 
3
- `aegiscode` in your shell — the command-line version of AEGIS One. The same
4
- tool surface the Claude Code plugin exposes over MCP, plus a terminal instead of
5
- an editor — built on the same two shared pieces and no others:
3
+ `aegiscode` is the command-line version of AEGIS One. You type what you want in
4
+ plain English — *"why does the build fail?"*, *"rename this function
5
+ throughout"*, *"summarise what changed this week"* — and it reads your files,
6
+ runs commands, edits code and answers. It is the same assistant, in a terminal
7
+ window instead of a window with buttons.
6
8
 
7
- | Shared piece | What it is |
8
- |---|---|
9
- | `client/aegis.js` | The thin transport. Holds the API key, speaks HTTP/SSE. No brain logic. |
10
- | `mcp/tools.js` | The tool registry — names, JSON schemas, result formatting. |
11
- | `desktop/renderer/usage.js` | The token-usage → number mapping, shared with the GUI so the two can never disagree. |
12
- | `desktop/lib/local/` | The agent-loop engine — persistent-shell exec, read/write/edit/glob/grep, Task subagents. The CLI runs the same loop the GUI does, scoped to the AEGIS class. |
9
+ There is nothing to configure before you start and no project to set up.
13
10
 
14
- Routing, model tiers, memory and billing all stay behind aegiscloud.org.
11
+ **You need two things:**
12
+
13
+ 1. **[Node.js 22 or newer](https://nodejs.org/en/download)** — the runtime that
14
+ runs the app. On macOS or Windows the installer is a double-click; on Linux
15
+ use your package manager. Check yours with `node -v`.
16
+ 2. **A free AEGIS key** from <https://aegiscloud.org> — this is what lets it
17
+ think. You paste it once, in step 2 below.
18
+
19
+ If you have never used a terminal before: it is the plain window where you type
20
+ commands and press Enter. On macOS it is called **Terminal**; on Windows,
21
+ **PowerShell**. Open it and type the grey boxes below exactly as written.
15
22
 
16
23
  ## Quick start
17
24
 
18
25
  Four steps, in order. Everything past this section is the fuller reference for
19
26
  each one.
20
27
 
21
- **1. Install** — requires Node 22+.
28
+ **1. Install** — needs Node 22+ (see above if you are not sure).
22
29
 
23
30
  ```bash
24
31
  npm install -g aegiscode
25
32
  ```
26
33
 
34
+ `npm` comes with Node.js. `-g` means *"install this so I can run it from any
35
+ folder"*. This one line downloads the app and puts the `aegiscode` command on
36
+ your machine.
37
+
27
38
  **2. Log in** — get a key at <https://aegiscloud.org> if you don't have one.
28
39
 
29
40
  ```bash
@@ -56,7 +67,7 @@ product, so they are one name now:
56
67
 
57
68
  | Name | Status |
58
69
  |---|---|
59
- | `aegiscode` | **this host**, v6.0.0. Installs a single binary, `aegiscode`. |
70
+ | `aegiscode` | **this host**. Installs a single command, `aegiscode`. Run `aegiscode version` for the version you have. |
60
71
  | `aegis-terminal` | deprecated — the 0.1.x spelling of this package, folded into `aegiscode`. |
61
72
  | `aegiscode-cli` | 4.0.3, an earlier name of this CLI's predecessor line. Untouched. |
62
73
  | `aegis-cli` | 0.4.8 (unrelated). |
@@ -249,22 +260,28 @@ launch, and an explicit flag (`-m`, `--light`) always outranks the stored value.
249
260
 
250
261
  In a session, plain text is a prompt. `/help` lists commands, grouped by
251
262
  category, the way the reference does. The registry is that client's, ported
252
- command for command — 87 entries across nine categories:
263
+ command for command — 96 entries across eight categories:
253
264
 
254
265
  | Category | Commands |
255
266
  |---|---|
256
- | Session & context | `/schedule` `/clear` `/compact` `/context` `/todos` `/config` `/exit` `/recap` `/resume` `/rewind` `/agents` `/status` `/teleport` `/version` `/new` `/skills` `/multiyolo` `/multi` `/research` `/debate` |
257
- | Workspace | `/run` `/build` `/cd` `/init` `/clone` |
258
- | Model & behavior | `/ping` `/effort` `/model` `/models` `/model-add` `/model-rm` `/theme` `/terminal` `/vim` `/permissions` `/hooks` `/credentials` `/install-github-app` `/thinking` `/mcp` `/memory` `/memory-deep` `/confirm` `/automode` *(alias `/yolo`)* `/router` `/class` |
259
- | Data | `/copy` `/cost` `/export` `/tokens` `/sync` |
260
- | Auth | `/login` `/logout` `/key` `/byok` `/byok-set` `/byok-rm` `/byok-key` `/byok-rm-key` |
261
- | Support | `/help` `/doctor` `/upgrade` `/troubleshooting` `/feedback` `/bug` `/issue` `/onboarding` `/shell-completion` `/terminal-setup` `/pr-comments` `/prs` `/review` `/benchmark` `/billing` `/topup` `/cloud` `/gmail` `/release-notes` |
267
+ | Session & context | `/schedule` `/clear` `/undo` `/compact` `/context` `/todos` `/config` `/exit` `/recap` `/resume` `/rewind` `/agents` `/status` `/teleport` `/version` `/new` `/skills` `/multiyolo` `/multi` `/research` `/debate` |
268
+ | Workspace | `/run` `/build` `/cd` `/sandbox` `/init` `/clone` |
269
+ | Model & behavior | `/ping` `/effort` `/model` `/theme` `/terminal` `/vim` `/permissions` `/hooks` `/credentials` `/install-github-app` `/thinking` `/mcp` `/memory` `/memory-deep` `/confirm` `/automode` *(alias `/yolo`)* `/router` `/class` `/models` `/model-add` `/model-discover` `/model-rm` |
270
+ | Data | `/copy` `/cost` `/export` `/tokens` `/sync` `/drive` |
271
+ | Auth | `/login` `/logout` `/key` `/byok` `/byok-set` `/byok-rm` `/byok-list` `/byok-key` `/byok-rm-key` |
272
+ | Support | `/help` `/license` `/credits` `/doctor` `/upgrade` `/troubleshooting` `/feedback` `/bug` `/issue` `/onboarding` `/shell-completion` `/terminal-setup` `/pr-comments` `/prs` `/review` `/benchmark` `/billing` `/topup` `/cloud` `/gmail` `/release-notes` |
262
273
  | Fun | `/radio` `/waifu` |
263
274
  | Aegis plugin | `/aegis-status` `/aegis-ask` `/aegis-recall` `/aegis-remember` `/aegis-council` `/aegis-print` `/aegis-multi` `/tool` `/aegis-import` |
264
275
 
276
+ There are 96 commands in eight categories; the ninth category in the registry,
277
+ `Custom`, holds none by default. `/yolo` is an **alias** of `/automode`, not a
278
+ command of its own — it never appears as its own row.
279
+
265
280
  The table above is generated from `cli/src/commands.js` (`COMMANDS` +
266
- `CATEGORIES`), which is the only authority on what exists — a hand-kept copy is
267
- how it came to claim 75 entries while the code held 84 before this port.
281
+ `CATEGORIES`), which is the only authority on what exists, and
282
+ `test/readme-claims.test.mjs` asserts that every name here matches the registry
283
+ exactly. A hand-kept copy is how it came to claim 75 entries while the code held
284
+ 84 before this port.
268
285
 
269
286
  `/help` shows the live list with hints; aliases are searchable in the `/`
270
287
  palette exactly as they are there (`/ask` → `/aegis-ask`, `?` → `/help`,
@@ -647,7 +664,7 @@ alternate-screen frame of header rule, transcript viewport, spinner/effort line,
647
664
  input line and status line, driven by a raw key stream.
648
665
 
649
666
  ```
650
- ╭───────────────────────────── AEGIS Code v6.3.0 ─────────────────────────────╮
667
+ ╭────────────────────────── AEGIS Code v<version> ────────────────────────────╮
651
668
  ❯ summarise what changed in the token accounting
652
669
  ● Three things changed, and one of them was costing you money:
653
670
 
@@ -717,6 +734,18 @@ node cli/scripts/demo.mjs # from a source checkout
717
734
 
718
735
  ## Design notes
719
736
 
737
+ **Four shared pieces, and no others.** The CLI is not a second implementation;
738
+ it is the same parts the other faces use:
739
+
740
+ | Shared piece | What it is |
741
+ |---|---|
742
+ | `client/aegis.js` | The thin transport. Holds the API key, speaks HTTP/SSE. No brain logic. |
743
+ | `mcp/tools.js` | The tool registry — names, JSON schemas, result formatting. |
744
+ | `desktop/renderer/usage.js` | The token-usage → number mapping, shared with the GUI so the two can never disagree. |
745
+ | `desktop/lib/local/` | The agent-loop engine — persistent-shell exec, read/write/edit/glob/grep, Task subagents. The CLI runs the same loop the GUI does, scoped to the AEGIS class. |
746
+
747
+ Routing, model tiers, memory and billing all stay behind aegiscloud.org.
748
+
720
749
  **It looks like the reference on purpose.** The gold/coral/lavender palette,
721
750
  the `✦`-studded welcome mark (mascot, crescent moon and diving whale), the `❯`
722
751
  prompt, the `⎿` hook rows and the `✻` spinner line are the reference's
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "7.0.42",
4
+ "version": "7.0.44",
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,4 +1,4 @@
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
- import{readdirSync as s}from"node:fs";import{spawnSync as t}from"node:child_process";import{dirname as e,join as o,resolve as r}from"node:path";import{fileURLToPath as n}from"node:url";const i=r(e(n(import.meta.url)),"..","..","test"),a=s(i).filter((s=>/^cli-.*\.test\.mjs$/.test(s))).sort();0===a.length&&(process.stderr.write(`no cli-*.test.mjs found in ${i}\n`),process.exit(1));const c=[],p=[];for(const s of a){const e=o(i,s);process.stdout.write(`\n── ${s} ${"─".repeat(Math.max(0,60-s.length))}\n`);const r=t(process.execPath,[e],{stdio:"inherit"});0===r.status?p.push(s):c.push({f:s,status:r.status,signal:r.signal})}if(process.stdout.write(`\n${"═".repeat(64)}\n`),process.stdout.write(`cli suite: ${p.length}/${a.length} files passed\n`),c.length){process.stdout.write(`\nFAILED (${c.length}):\n`);for(const{f:s,status:t,signal:e}of c)process.stdout.write(` ✗ ${s}${e?` (signal ${e})`:` (exit ${t})`}\n`);process.exit(1)}
4
+ import{readdirSync as s}from"node:fs";import{spawnSync as t}from"node:child_process";import{dirname as e,join as o,resolve as r}from"node:path";import{fileURLToPath as n}from"node:url";const i=r(e(n(import.meta.url)),"..","..","test"),a=s(i).filter((s=>/^cli-.*\.test\.mjs$/.test(s))).sort();0===a.length&&(process.stderr.write(`no cli-*.test.mjs found in ${i}\n`),process.exit(1));const c=[],p=[],l=["AEGIS_REDUCED_MODE","AEGIS_SKIP_PERMISSIONS","AEGISONE_SKIP_PERMISSIONS","AEGIS_NO_PROVENANCE_CHECK","AEGIS_SKIP_PROVENANCE","AEGIS_NO_INTERLOCK"],E={...process.env};for(const s of l)delete E[s];for(const s of a){const e=o(i,s);process.stdout.write(`\n── ${s} ${"─".repeat(Math.max(0,60-s.length))}\n`);const r=t(process.execPath,[e],{stdio:"inherit",env:E});0===r.status?p.push(s):c.push({f:s,status:r.status,signal:r.signal})}if(process.stdout.write(`\n${"═".repeat(64)}\n`),process.stdout.write(`cli suite: ${p.length}/${a.length} files passed\n`),c.length){process.stdout.write(`\nFAILED (${c.length}):\n`);for(const{f:s,status:t,signal:e}of c)process.stdout.write(` ✗ ${s}${e?` (signal ${e})`:` (exit ${t})`}\n`);process.exit(1)}
@@ -2,7 +2,7 @@
2
2
  "name": "aegis-desktop",
3
3
  "productName": "aegis one",
4
4
  "desktopName": "aegis-desktop",
5
- "version": "1.0.42",
5
+ "version": "1.0.44",
6
6
  "description": "Thin Electron host for AEGIS — a local chat UI over the shared client/aegis.js transport. Ships transport + UI only; engine logic stays server-side.",
7
7
  "author": {
8
8
  "name": "AEGIS Code",
@@ -2,6 +2,6 @@
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
3
  "use strict";!function(){const e=window.aegis,t=window.models,n=window.sync,o=window.quickLauncher,s=window.queue,a=window.auto,i="nexus",r="Nexus — auto-route";if(!e||!t)throw document.body.textContent="This page must run inside the AEGIS Electron host (window.aegis/window.models missing).",new Error("window.aegis/window.models unavailable — not running under Electron");const c={updateBanner:"update-banner",updateBannerText:"update-banner-text",updateDownloadBtn:"update-download-btn",updateRestartBtn:"update-restart-btn",updateRetryBtn:"update-retry-btn",updateLaterBtn:"update-later-btn",accountBanner:"account-banner",accountBannerText:"account-banner-text",accountRetryBtn:"account-retry-btn",keysAccount:"keys-account",keysAccountRetry:"keys-account-retry",connDot:"conn-dot",connText:"conn-text",app:"st-app",client:"st-client",base:"st-base",key:"st-key",plan:"st-plan",balance:"st-balance",upgradePlan:"upgrade-plan",topupBtn:"topup-btn",topupAmount:"topup-amount",billingHint:"billing-hint",apiKeyInput:"api-key-input",apiKeySave:"api-key-save",apiKeyVerify:"api-key-verify",apiKeyHint:"api-key-hint",classSelect:"class-select",modelSelect:"model-select",providerMark:"provider-mark",ptSearch:"pt-search",ptRefresh:"pt-refresh",ptList:"pt-list",ptCount:"pt-count",ptHint:"pt-hint",companionCard:"companion-card",companionText:"companion-text",companionDismiss:"companion-dismiss",modelFree:"model-input",budgetHint:"budget-hint",autonomousToggle:"autonomous-toggle",autonomousToggleWrap:"autonomous-toggle-wrap",autonomousControls:"autonomous-controls",effortSelect:"effort-select",autonomousWorkers:"autonomous-workers",modelHint:"model-hint",settingsList:"settings-list",settingsHint:"settings-hint",customBaseUrl:"custom-base-url",customKey:"custom-key",customModel:"custom-model",customSave:"custom-save",customRemove:"custom-remove",customStatus:"custom-status",quickLauncherEnabled:"quick-launcher-enabled",quickLauncherShortcut:"quick-launcher-shortcut",quickLauncherSave:"quick-launcher-save",quickLauncherHint:"quick-launcher-hint",permRulesList:"perm-rules-list",permRulesForm:"perm-rules-form",permRulesInput:"perm-rules-input",permRulesListSelect:"perm-rules-list-select",permRulesAdd:"perm-rules-add",permRulesStatus:"perm-rules-status",permRulesHint:"perm-rules-hint",sandboxMode:"sandbox-mode-select",sandboxNetwork:"sandbox-network-toggle",sandboxStatus:"sandbox-policy-status",confirmMode:"confirm-mode-toggle",confirmModeHint:"confirm-mode-hint",fontScale:"font-scale-select",fontScaleHint:"font-scale-hint",accentSelect:"accent-select",accentHint:"accent-hint",planMode:"plan-mode-toggle",planModeHint:"plan-mode-hint",autoMode:"auto-mode-toggle",autoModeLabel:"auto-mode-label",autoModeHint:"auto-mode-hint",sessionsRefresh:"sessions-refresh",sessionsExport:"sessions-export",sessionsList:"sessions-list",sessionsHint:"sessions-hint",sessionsFilter:"sessions-filter",sessionsCount:"sessions-count",syncNow:"sync-now",syncStatus:"sync-status",sessionMeter:"session-meter",newChat:"new-chat",openCliFace:"open-cli-face",chatCanvas:"chat-canvas",railAutomations:"rail-automations",railSettings:"rail-settings",avatarPaneMount:"avatar-pane-mount",settingsView:"settings-view",automationsView:"automations-view",automationsBack:"automations-back",queueModelField:"queue-model-field",conversationsView:"conversations-view",sideScroll:"side-scroll",settingsBack:"settings-back",settingsJump:"settings-jump",memorySearchForm:"memory-search-form",memoryQuery:"memory-query",memoryResults:"memory-results",memoryEntry:"memory-entry",memorySaveBtn:"memory-save-btn",importSessionBtn:"import-session-btn",importOverlay:"import-overlay",importBackdrop:"import-backdrop",importClose:"import-close",importHint:"import-hint",importList:"import-list",importCount:"import-count",importSync:"import-sync",importSessionsBtn:"import-sessions-btn",importMemoryBtn:"import-memory-btn",memoryHint:"memory-hint",memoryOpen:"memory-open",memoryBox:"memory-box",memoryQuiet:"memory-quiet",memoryQuietFloor:"memory-quiet-floor",paneTabs:"pane-tabs",tabSessions:"tab-sessions",tabMemory:"tab-memory",paneSessions:"pane-sessions",paneMemory:"pane-memory",memoryOverlay:"memory-overlay",memoryBackdrop:"memory-backdrop",memoryClose:"memory-close",memoryFilters:"memory-filters",memoryOverlayQuery:"memory-overlay-query",memoryFiltersClear:"memory-filters-clear",memoryChips:"memory-chips",memoryList:"memory-list",memoryCount:"memory-count",memoryOverlayEntry:"memory-overlay-entry",memoryOverlaySave:"memory-overlay-save",sessionOverlay:"session-overlay",sessionBackdrop:"session-backdrop",sessionClose:"session-close",sessionFilters:"session-filters",sessionQuery:"session-query",sessionClear:"session-clear",sessionHint:"session-hint",sessionList:"session-list",sessionCount:"session-count",paletteOverlay:"palette-overlay",paletteBackdrop:"palette-backdrop",paletteInput:"palette-input",composerMenu:"composer-menu",composerMenuList:"composer-menu-list",composerMenuHint:"composer-menu-hint",paletteList:"palette-list",paletteEmpty:"palette-empty",findBar:"find-bar",findInput:"find-input",findCount:"find-count",findPrev:"find-prev",findNext:"find-next",findClose:"find-close",side:"side",creditsOverlay:"credits-overlay",creditsBackdrop:"credits-backdrop",creditsClose:"credits-close",creditsBody:"credits-body",creditsStatus:"credits-status",creditsLicenceTag:"credits-licence-tag",fpCardStatus:"fp-card-status",fpOpen:"fp-open",fpOverlay:"fp-overlay",messages:"messages",scrollBottom:"scroll-bottom",composer:"composer",prompt:"prompt",send:"send",attachRow:"attach-row",attachNote:"attach-note",dropVeil:"drop-veil",exploreToggle:"explore-toggle",queueTask:"queue-task",queueClassSelect:"queue-class-select",queueModelSelect:"queue-model-select",queueModelInput:"queue-model-input",queueModelHint:"queue-model-hint",queueCwd:"queue-cwd",queueCommit:"queue-commit",queueEnqueue:"queue-enqueue",queueDrain:"queue-drain",queueProceed:"queue-proceed",queueStop:"queue-stop",queueList:"queue-list",queueHint:"queue-hint",queueFanout:"queue-fanout",queueFanoutLabel:"queue-fanout-label",queueAuto:"queue-auto",queueAutoLabel:"queue-auto-label",queueAutoInterval:"queue-auto-interval",queueAutoHint:"queue-auto-hint",queueBoundary:"queue-boundary",queueUpgrade:"queue-upgrade",queueCard:"queue-card",shortcutsOverlay:"shortcuts-overlay",shortcutsBackdrop:"shortcuts-backdrop",shortcutsClose:"shortcuts-close",shortcutsBody:"shortcuts-body",shortcutsCount:"shortcuts-count",keysOverlay:"keys-overlay",keysBackdrop:"keys-backdrop",keysClose:"keys-close",keysCount:"keys-count",keysRowAegis:"keys-row-aegis",keysRowByok:"keys-row-byok",keysAegisState:"keys-aegis-state",keysByokState:"keys-byok-state",keysGotoAegis:"keys-goto-aegis",keysGotoByok:"keys-goto-byok",keysHint:"keys-hint",keysDismiss:"keys-dismiss"},l={};for(const[e,t]of Object.entries(c))Object.defineProperty(l,e,{get:()=>document.getElementById(t),enumerable:!0,configurable:!0});const d="aegis.class",u="aegis.queueClass",m="aegis.autonomous",p="aegis.effort",f="aegis.autonomousWorkers",h="aegis.explore",y="aegis.welcomeConnectDismissed",g="aegis",v=new Set(["__aegis","aegis"]),C="local",k="custom",b="http://localhost:11434",w="https://aegiscloud.org/key?s=desktop&c=key_prompt",x="The autonomous queue keeps running after you close the laptop.",S="https://aegiscloud.org",E=/^[a-z0-9][a-z0-9_-]{0,63}$/;function $(e,t){const n=new URL(`${S}/go/${e}`);n.searchParams.set("s","desktop");const o=null==t?"":String(t).trim().toLowerCase();return E.test(o)&&n.searchParams.set("c",o),n.toString()}function L(e){return $("upgrade",e)}function q(e){return $("topup",e)}const M={welcome_cloud:"welcome",queue_cap:"queue",memory_quota:"memory",status_card:"status",topup_bank:"topup"},A="upgrade_prompt_rendered",N="upgrade_prompt_clicked";let H=!1;function B(e,t){try{const n=M[t];if(!n)return;const o=window.aegis;if(!o||"function"!=typeof o.telemetryEvent)return;const s=o.telemetryEvent(e,{campaign:t,surface:n});s&&"function"==typeof s.catch&&s.catch((()=>{}))}catch(e){if(!H){H=!0;try{console.debug("telemetry: prompt event failed (suppressed)",e)}catch{}}}}function I(e,t,n,o){const s=document.createElement("a");return s.href=function(e,t){const n="topup_bank"===t?q(t):L(t);if(!e)return n;let o;try{o=new URL(e,S)}catch{return e}return o.origin!==S||o.searchParams.get("s")||o.searchParams.get("utm_source")?e:/topup/.test(o.pathname)?q(t):n}(t,n),s.target="_blank",s.rel="noreferrer noopener",s.textContent=o,s.addEventListener("click",(()=>B(N,n))),e.appendChild(s),!1===e.isConnected||e.hidden||B(A,n),s}let R=null,T=null,O=null,F=[],D=[],P=new Map;const U=new Map;function _(e,t,n={}){const o=e||"",s=rollTurn(function(e){const t=e||"";return U.has(t)||U.set(t,emptyRoll()),U.get(t)}(o),t,n);return U.set(o,s),K(o),s}function K(e,t){const n=l.sessionMeter,o=t?function(e){const t="string"==typeof e.reply?e.reply:"",n="string"==typeof e.reasoning?e.reasoning:"",o="number"==typeof e.measuredReasoningTokens&&e.measuredReasoningTokens>0?e.measuredReasoningTokens:0;if(!t&&!n&&!o)return"↓0 tokens";let s=0;try{const o=estimatedBuckets(e.prompt,t,n);o&&"number"==typeof o.output&&o.output>0&&(s=o.output)}catch(e){}if(!s){let e=0;for(const o of[t,n]){let t=0;for(;t<o.length;)t+=o.codePointAt(t)>65535?2:1,e+=1}s=Math.ceil(e/4)}return s+=o,s?`↓${o>0?"≥":""}${Math.round(s)} tokens`:""}(t):"",s=t?function(){if(!R)return null;let e=R.querySelector(".typing-tokens");return e||(e=document.createElement("span"),e.className="typing-tokens",e.hidden=!0,R.appendChild(e)),e}():null;if(s&&(s.textContent=o,s.hidden=!o),!n)return;if(O!==e)return void(n.hidden=!0);let a=U.get(e||"");t&&(a=rollTurn(a||emptyRoll(),void 0,{prompt:t.prompt,reply:t.reply,reasoning:t.reasoning,measuredReasoningTokens:t.measuredReasoningTokens}));const i=a?fmtRoll(a):"";return n.textContent=i,n.hidden=!i,n.classList.toggle("live",!!t&&!!i),i&&(n.title="This session, counted the way the CLI counts it — every turn rolled into one running total"),a}function j(e,t,n,o){const s=ledgerRow(e,n,{model:t,costUsd:n&&n.real&&"number"==typeof n.cost?n.cost:void 0,calls:o&&o.calls,prompt:o&&o.prompt,reply:o&&o.reply,reasoning:o&&o.reasoning}),a=s?Object.assign({},s):{};return t&&(a.model=t),a}const V="You are the exploratory half of a chat assistant. The user is reading the main answer elsewhere, so never restate it. Be concrete and brief: one lead line naming the path, then 3-5 tight bullets. Never pad.",G=[{key:"alternate",badge:"A",title:"Alternative angle",hint:"Answer the request from a genuinely different angle: another method, school of thought or genre. Name the angle in one line, then 3-5 bullets of how it actually plays out. Do not restate the main answer."},{key:"discovery",badge:"B",title:"Unexpected discovery",hint:"Act as a scout, not an assistant. Surface ONE non-obvious connection, adjacent field or surprise finding the user did not ask for but which reframes the request. One line naming the discovery, then 2-4 bullets on why it matters and how to test it. Flag uncertainty honestly."},{key:"genre",badge:"C",title:"New genre",hint:"Recast the request in an unfamiliar genre or discipline — pick one that fits oddly well (e.g. field biology, contract law, ecology, jazz, logistics, restoration). Name the genre in one line, then 3-5 bullets of what that discipline would do first."}];let Q=0;const W=new Set;function z(){for(const e of W)try{t.cancel(e)}catch{}W.clear()}let Y=0,J=null,X=null,Z=null;function ee(e){return!!Z&&Z.follow(e)}let te=null;function ne(){if(!T)return!1;if(!stopAppliesTo(J,X))return!1;X=J;const e=T;te={sessionId:e,at:Date.now(),state:"requested"};try{const n=t.cancel(e);n&&"function"==typeof n.then&&n.then((t=>{te={sessionId:e,at:Date.now(),state:"settled",accepted:!t||!1!==t.ok,result:void 0===t?null:t}}),(t=>{te={sessionId:e,at:Date.now(),state:"rejected",accepted:!1,error:t&&t.message||String(t)}}))}catch(t){te={sessionId:e,at:Date.now(),state:"threw",accepted:!1,error:t&&t.message||String(t)}}if(R){const e=R.querySelector(".cancel-btn");e&&(e.disabled=!0,e.textContent="stopping…")}return!0}function oe(){const e=l.autonomousToggle;return Boolean(e&&e.checked)}function se(){if(!l.autonomousControls)return;const e=l.autonomousToggleWrap&&!l.autonomousToggleWrap.hidden;l.autonomousControls.hidden=!(e&&oe())}function ae(){if(l.modelFree&&!l.modelFree.hidden){const e=l.modelFree.value.trim();if(e)return e}return l.modelSelect.value}function ie(e,t){const n=void 0===t?ae():t;l.budgetHint&&(l.budgetHint.textContent=function(e,t){const n=ce(),o=n,s=n;return e===g?`budget: ${{low:16384,medium:32768,high:65536,max:65536}[o].toLocaleString()} tokens from effort (${s}), summed across the worker fan-out by the Aegis Cloud pool — no max_tokens is sent.`:DEEPSEEK_REASONING_MODEL_RE.test(String(t||""))?`budget: ${EFFORT_TOKEN_BUDGET[o].toLocaleString()} tokens from effort (${s}) — this model reasons against its own output budget, and the length of the answer is not predictable from the prompt.`:`no token cap is sent (effort: ${s}) — output length cannot be predicted from the prompt, so this app states no max_tokens and the provider's own limit applies.`}(e,n)),re()}function re(){if(!l.providerMark||!window.aegisProviderMark)return;const e=ae(),t="local"===(l.classSelect?l.classSelect.value:"")?"ollama":"";window.aegisProviderMark.paint(l.providerMark,e,"",t)}function ce(){const e=l.effortSelect&&l.effortSelect.value;return"low"===e||"medium"===e||"max"===e?e:"high"}function le(e,t){l.connDot.classList.toggle("ok",Boolean(e)),l.connText.textContent=t}let de=null,ue=!1;function me(e){if(!e)return de=null,ue=!1,void le(!1,"IPC unavailable");de=Boolean(e.keyConfigured),ue=Boolean(e.providerConfigured),l.app.textContent=e.appVersion?`v${e.appVersion}`:"–",l.client.textContent=e.clientVersion||"–",l.base.textContent=e.apiBase||"–",l.key.textContent=e.keyConfigured?e.keyMask:"not set",le(e.keyConfigured,e.keyConfigured?"key configured":"no API key"),to(),jn(),Wn(),function(){const e=document.getElementById("keys-overlay");if(!e)return;let t=!1;try{t="on"===localStorage.getItem(ho)}catch{}t||null===de?e.hidden=!0:(yo(),Boolean(T)?vo():!0!==de||!0!==ue?go():vo())}()}let pe=null,fe=null;function he(e){if(!l.updateBanner)return;pe=e;try{gt()}catch{}const t=e&&e.status,n=!t||"idle"===t||"disabled"===t||"checking"===t||"up-to-date"===t||"unavailable"===t;if("decomposed"===t){l.updateBanner.hidden=!1;const t=e.version?`v${e.version} `:"";return void(l.updateBanner.textContent=`This version is DECOMPOSED — update to the latest release.${t}`)}if(n||t===fe)return void(l.updateBanner.hidden=!0);let o="",s=!1,a=!1,i=!1;const r=e.version?`v${e.version} `:"";if("available"===t)o=e.command?e.commandIsSentence?`Update ${r}available. ${e.command}`:`Update ${r}available — run: ${e.command}`:`Update ${r}available.`,s=!!e.canDownload,s&&(o=`Update ${r}available.`);else if("downloading"===t)o=`Downloading update${"number"==typeof e.progress?` (${Math.round(e.progress)}%)`:""}…`;else if("downloaded"===t)o=`Update ${r}downloaded — restart to install.`,a=!0;else{if("error"!==t)return void(l.updateBanner.hidden=!0);o=`Update check failed: ${e.error||"unknown error"}`,e.transient&&(o+=" — will retry automatically."),i=!0}l.updateBannerText.textContent=o,l.updateDownloadBtn.hidden=!s,l.updateRestartBtn.hidden=!a,l.updateRetryBtn&&(l.updateRetryBtn.hidden=!i),l.updateBanner.hidden=!1}let ye=null;function ge(e){ye=e&&"no-key"===e.status?e.reason:null,yo(),l.accountBanner&&(ye?(l.accountBannerText.textContent=`No AEGIS account key on this machine: ${ye}.`,l.accountBanner.hidden=!1):l.accountBanner.hidden=!0)}function ve(t){t.disabled=!0,e.registerAccount().then((e=>{if(ge(e),!e)return be()})).catch((e=>ge({status:"no-key",reason:String(e&&e.message||e)}))).finally((()=>{t.disabled=!1}))}async function Ce(){try{const t=await e.verifyApiKey();t&&t.ok?l.plan.textContent=t.valid?t.plan||"active":"invalid key":l.plan.textContent="unavailable"}catch{l.plan.textContent="unavailable"}try{const t=await e.tokenBankBalance();l.balance.textContent=t&&null!=t.balance_eur?`€${t.balance_eur}`:"–"}catch{l.balance.textContent="unavailable"}}async function ke(t){const n=Math.round(Number(l.topupAmount&&l.topupAmount.value)||10),o="topup"===t?l.topupBtn:l.upgradePlan;if(o&&(o.disabled=!0),"topup"===t&&!1===de)return o&&(o.disabled=!1),void(l.billingHint.textContent="add your AEGIS API key above — a top-up is credited to your account");l.billingHint.textContent="topup"===t?`creating a €${n} top-up…`:"creating checkout…";try{const o="topup"===t?await e.tokenBankTopup(n):await e.billingCheckout();if(!o||!0!==o.ok||!o.url)return void function(e,t){const n="topup"===t?"top-up":"upgrade";if(401!==e.status&&403!==e.status)return e.upgrade?(l.billingHint.textContent=`free plan cap reached — ${n} lifts it. `,void I(l.billingHint,e.upgrade.url,"topup"===t?"topup_bank":"status_card","See plans →")):void(e.setupRequired?l.billingHint.textContent="checkout is not configured on the server yet (no Stripe price id)":l.billingHint.textContent=`${n} failed: ${e.reason||"the server returned no checkout URL"}`);l.billingHint.textContent=`add your AEGIS API key above — a ${n} needs an account`}(o||{},t);l.billingHint.textContent="opening checkout…";const s=await e.openExternal(o.url);if(s&&!1===s.ok)return void(l.billingHint.textContent=`could not open the checkout page: ${s.reason||"unknown reason"}`);l.billingHint.textContent="topup"===t?"checkout opened in your browser — the bank is credited when Stripe confirms":"checkout opened in your browser — your plan updates when Stripe confirms"}catch(e){l.billingHint.textContent=`billing failed: ${e&&e.message?e.message:e}`}finally{o&&(o.disabled=!1)}}async function be(){try{me(await e.status())}catch{me(null)}await Io(),await Ce()}async function we(){const t=l.apiKeyInput.value.trim();l.apiKeySave.disabled=!0,l.apiKeyVerify.disabled=!0,l.apiKeyHint.textContent="saving…";try{const n=await e.setApiKey(t);if(!n||!n.ok)throw new Error(n&&n.error||"save failed");l.apiKeyInput.value="",l.apiKeyHint.textContent=t?`saved (${n.keyMask?n.keyMask:"configured"})`:"key cleared",await be()}catch(e){l.apiKeyHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{l.apiKeySave.disabled=!1,l.apiKeyVerify.disabled=!1}}async function xe(){l.apiKeyVerify.disabled=!0,l.apiKeyHint.textContent="verifying…";try{const t=await e.verifyApiKey();if(!t||!t.ok)throw new Error(t&&t.error||"verify failed");l.apiKeyHint.textContent=t.valid?`valid (${t.plan||"active"})`:"invalid key"}catch(e){l.apiKeyHint.textContent=`verify failed: ${e&&e.message?e.message:e}`}finally{l.apiKeyVerify.disabled=!1}}function Se(e){if(!e)return;l.quickLauncherEnabled.checked=Boolean(e.enabled),l.quickLauncherShortcut.value=e.shortcut||"",l.quickLauncherShortcut.placeholder=e.shortcut||"CmdOrCtrl+Shift+Space";const t=[];e.packaged&&t.push("always on in this packaged build"),t.push(e.active?`active — press ${e.shortcut} anywhere`:"inactive"),e.reason&&t.push(e.reason),l.quickLauncherHint.textContent=t.join(" · ")}async function Ee(){if(o){l.quickLauncherSave.disabled=!0,l.quickLauncherHint.textContent="saving…";try{Se(await o.setConfig({enabled:l.quickLauncherEnabled.checked,shortcut:l.quickLauncherShortcut.value.trim()}))}catch(e){l.quickLauncherHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{l.quickLauncherSave.disabled=!1}}}function $e(e){if(!l.confirmMode||!e)return;const t=!1!==e.enabled;l.confirmMode.checked=t,l.confirmModeHint.textContent=t?"On — exec, writeFile and editFile ask for your approval before they run.":"Off — the agent runs exec, writeFile and editFile without asking.",Le(t)}function Le(e){if(!l.autoMode)return;const t=!e;l.autoMode.setAttribute("aria-pressed",t?"true":"false"),l.autoMode.classList.toggle("is-auto",t),l.autoModeLabel&&(l.autoModeLabel.textContent=t?"auto mode":"ask before tools"),l.autoModeHint&&(l.autoModeHint.textContent=t?"on — tools run without asking. Click to require approval.":"off — click for auto mode, or use Settings → Tool approvals.")}function qe(e){const t=Number(e),n=Number.isFinite(t)?Math.min(1.3,Math.max(.85,t)):1;if(document.documentElement.style.setProperty("--app-font-scale",String(n)),l.fontScale){const e=Array.from(l.fontScale.options||[]);let t=null;for(const o of e){const e=Number(o.value);Number.isFinite(e)&&(!t||Math.abs(e-n)<Math.abs(Number(t.value)-n))&&(t=o)}t&&(l.fontScale.value=t.value)}l.fontScaleHint&&(l.fontScaleHint.textContent=`Interface text at ${Math.round(100*n)}%.`)}function Me(e){const t=["default","cobalt","amber"].includes(String(e))?String(e):"default";if(document.body.dataset.accent=t,l.accentSelect&&(l.accentSelect.value=t),l.accentHint){const e={default:"teal",cobalt:"cobalt",amber:"amber"}[t];l.accentHint.textContent=`Accent set to ${e}.`}}async function Ae(t){if(l.confirmMode){l.confirmMode.disabled=!0,l.autoMode&&(l.autoMode.disabled=!0);try{$e(await e.setConfirmMode(t))}catch(e){l.confirmMode.checked=!t,l.confirmModeHint.textContent=`save failed: ${e&&e.message?e.message:e}`,Le(l.confirmMode.checked)}finally{l.confirmMode.disabled=!1,l.autoMode&&(l.autoMode.disabled=!1)}}}function Ne(e){if(!l.planMode||!e)return;const t="plan"===e.mode;l.planMode.checked=t,l.planModeHint&&(l.planModeHint.textContent=t?"On — writeFile, editFile and mutating exec calls are refused; read-only shell and search still run.":'Off — tool calls follow "confirm before running tools" above, as usual.')}const He=["deny","allow","ask"];function Be(e){if(!l.permRulesList)return;l.permRulesList.innerHTML="";const t=e&&!0===e.ok,n=t&&e.rules?e.rules:null;if(!n){const n=document.createElement("li");return n.className="rules-row rules-row-muted",n.textContent=t?"no stored rules":`rules unavailable: ${e&&e.reason||"the permission store could not be read"}`,l.permRulesList.appendChild(n),void(l.permRulesHint&&(l.permRulesHint.dataset.residual=""))}let o=0;for(const e of He){const t=Array.isArray(n[e])?n[e]:[];for(const n of t){o+=1;const t=document.createElement("li");t.className="rules-row",t.dataset.list=e,t.dataset.rule=n;const s=document.createElement("span");s.className=`rules-tag rules-tag-${e}`,s.textContent=e,t.appendChild(s);const a=document.createElement("code");a.className="rules-pattern",a.textContent=n,t.appendChild(a);const i=document.createElement("button");i.type="button",i.className="ghost-btn danger rules-remove",i.textContent="Remove",i.addEventListener("click",(()=>Ie(e,n))),t.appendChild(i),l.permRulesList.appendChild(t)}}if(!o){const e=document.createElement("li");e.className="rules-row rules-row-muted",e.textContent="no stored rules",l.permRulesList.appendChild(e)}var s;l.permRulesHint&&(l.permRulesHint.textContent=`A rule is tool(pattern) — exec(npm test), exec(npm run *), writeFile(src/**). Deny beats allow. ${s=n.defaultMode,"allow"===s?"unmatched calls run without asking":"deny"===s?"unmatched calls are refused":"unmatched calls ask"}.`)}async function Ie(t,n){if(e.permRulesRemove)try{const o=await e.permRulesRemove(t,n);o&&!0===o.ok?(Be(o),l.permRulesStatus&&(l.permRulesStatus.textContent=!1===o.removed?`already gone: ${n}`:`removed: ${n}`)):l.permRulesStatus&&(l.permRulesStatus.textContent=`remove failed: ${o&&o.reason||"the store refused it"}`)}catch(e){l.permRulesStatus&&(l.permRulesStatus.textContent=`remove failed: ${e&&e.message?e.message:e}`)}}const Re={"workspace-write":"Commands may write inside the open workspace and /tmp; everything else is read-only.","read-only":"Commands may write nothing at all. Every path is mounted read-only.",off:"No sandbox. Commands run with your full user permissions."};function Te(e){if(!l.sandboxMode)return;const t=e&&"string"==typeof e.mode?e.mode:"workspace-write",n=e&&"open"===e.network?"open":"restricted";if(Array.isArray(e&&e.modes)&&e.modes.length&&Array.from(l.sandboxMode.options).map((e=>e.value)).join("\0")!==e.modes.join("\0")){l.sandboxMode.innerHTML="";for(const t of e.modes){const e=document.createElement("option");e.value=t,e.textContent=t,l.sandboxMode.appendChild(e)}}l.sandboxMode.value=t,l.sandboxNetwork&&(l.sandboxNetwork.checked="open"===n),l.sandboxStatus&&(l.sandboxStatus.textContent=e&&!1!==e.ok?function(e){const t=e&&"string"==typeof e.mode?e.mode:"workspace-write",n=e&&"open"===e.network?"open":"restricted",o=e&&"string"==typeof e.sentence?e.sentence:null,s=e?e.enforced:null;if(!1===s)return`${o||`sandbox: OFF — no mechanism available (mode ${t} is not being enforced)`}. Commands are NOT confined.`;if(null===s||!o){const e=null===s?"the sandbox probe could not be completed":"no mechanism reported";return`${Re[t]||t} Sandbox status unknown: ${e}, so this posture may not be enforced.`}return`${null!==o?o:""} ${Re[t]||t} Network: ${"open"===n?"allowed":"blocked"}.`.trim()}(e):`could not read the posture: ${e&&e.reason||"unknown error"}`)}async function Oe(){if(l.sandboxMode&&e.getSandboxPolicy)try{Te(await e.getSandboxPolicy())}catch(e){Te({ok:!1,reason:e&&e.message||String(e)})}}async function Fe(t,n){if(e.setSandboxPolicy)try{Te(await e.setSandboxPolicy(t,n))}catch(e){l.sandboxStatus&&(l.sandboxStatus.textContent=`not saved: ${e&&e.message?e.message:e}`),Oe()}}let De="",Pe=!1;function Ue(e){De=e||"",l.queueHint&&(l.queueHint.textContent=De)}function _e(e){const t=document.createElement("li");t.className="queue-task",t.dataset.status=e.status;const n=document.createElement("div");n.className="queue-task-head";const o=document.createElement("span");o.className="queue-task-id",o.textContent=`#${e.id}`,n.appendChild(o);const s=document.createElement("span");s.className="queue-task-pill",s.textContent=String(e.status||"pending"),n.appendChild(s);const a=document.createElement("div");if(a.className="queue-task-actions","done"===e.status||"error"===e.status){const t=document.createElement("button");t.type="button",t.className="ghost-btn",t.textContent="Retry",t.title="Put this task back in line and run it again",t.addEventListener("click",(()=>Je("retry",e.id))),a.appendChild(t)}if("running"!==e.status){const t=document.createElement("button");t.type="button",t.className="ghost-btn",t.textContent="Remove",t.addEventListener("click",(()=>Je("remove",e.id))),a.appendChild(t)}a.childNodes.length&&n.appendChild(a),t.appendChild(n);const i=document.createElement("p");i.className="queue-task-prompt",i.textContent=String(e.task||"").trim()||"(no prompt)",t.appendChild(i);const r=document.createElement("p");r.className="queue-task-meta",r.textContent=function(e){const t=[];if(e.model&&t.push(e.model),t.push(!1===e.singlePass||!0===e.autonomous?"fan-out":"single pass"),e.cwd&&t.push(e.cwd),"running"===e.status)t.push(e.startedAt?`started ${vt(e.startedAt)}`:"working");else if("pending"===e.status)e.attempts&&t.push(`${e.attempts} attempt${1===e.attempts?"":"s"}`),e.created&&t.push(`queued ${vt(e.created)}`);else{e.attempts>1&&t.push(`${e.attempts} attempts`);const n=e.finishedAt||e.startedAt||e.created;n&&t.push(vt(n))}return t.join(" · ")}(e),t.appendChild(r);let c="";if("error"===e.status?c=e.error?String(e.error):"failed — no reason recorded":"done"===e.status&&(c=(e.result&&e.result.output?String(e.result.output):"").trim()),c){const n=document.createElement("p");n.className="error"===e.status?"queue-task-result is-error":"queue-task-result",n.textContent=c,t.appendChild(n)}const l=e.result&&Array.isArray(e.result.files)?e.result.files:[];if(l.length){const e=document.createElement("ul");e.className="queue-task-files";for(const t of l){const n=document.createElement("li");n.textContent=String(t),e.appendChild(n)}t.appendChild(e)}return t}function Ke(e){if(!l.queueList||!e||"object"!=typeof e)return;Pe=Boolean(e.draining),l.queueCwd&&!l.queueCwd.value&&(l.queueCwd.value=e.defaultCwd||""),l.queueEnqueue&&(l.queueEnqueue.disabled=Pe),l.queueDrain&&(l.queueDrain.disabled=Pe),l.queueProceed&&(l.queueProceed.disabled=Pe),l.queueStop&&(l.queueStop.hidden=!Pe);const t=Array.isArray(e.items)?e.items:[];if(l.queueList.innerHTML="",t.length)for(const e of t)l.queueList.appendChild(_e(e));else{const e=document.createElement("li");e.className="empty",e.textContent="queue is empty",l.queueList.appendChild(e)}const n=[];e.running?n.push(`running #${e.running.id}`):Pe&&n.push("draining…"),n.push(`${e.pending||0} pending`),e.defaultModel&&n.push(`Aegis Cloud · ${e.defaultModel}`),Pe&&e.stopping&&n.push("stopping after this task"),function(e){const t=e&&e.entitlement?e.entitlement:null,n=Boolean(t&&t.source&&"unresolved"!==t.source),o=Boolean(t&&t.entitled);if(l.queueFanout&&(l.queueFanout.disabled=!o,o||(l.queueFanout.checked=!1)),l.queueBoundary&&(l.queueBoundary.textContent=n?o?t.pro?`${t.tierName||"Pro"} — the cloud drain and the fan-out are unlocked.`:"Balance on your account — the cloud drain and the fan-out are unlocked.":t.refusal||"":""),l.queueUpgrade&&(l.queueUpgrade.innerHTML="",n&&!o)){const e="balance"===t.wall;I(l.queueUpgrade,t.upgradeUrl,t.campaign,e?"Top up your balance ↗":"See what Pro covers ↗")}}(e),l.queueHint&&(l.queueHint.textContent=[De,n.join(" · ")].filter(Boolean).join(" · "))}async function je(){if(!s||!l.queueList)return null;try{const e=await s.list();return Ke(e),e}catch(e){return Ue(`queue list failed: ${e&&e.message?e.message:e}`),null}}let Ve=null,Ge=!1;async function Qe(){if(Ve=null,!Ge){Ge=!0;try{await je()}finally{Ge=!1}}}async function We(){if(!s||!l.queueTask)return;const e=l.queueTask.value.trim();if(e){l.queueEnqueue&&(l.queueEnqueue.disabled=!0),Ue("queueing…");try{const t=await s.enqueue({task:e,cwd:l.queueCwd?l.queueCwd.value.trim():"",class:l.queueClassSelect?l.queueClassSelect.value:void 0,model:To(),commit:!!l.queueCommit&&l.queueCommit.checked});t&&t.ok?(l.queueTask.value="",Ue(`queued #${t.item.id}`)):Ue(t&&t.reason||"enqueue failed"),Ke(t)}catch(e){Ue(`enqueue failed: ${e&&e.message?e.message:e}`)}finally{l.queueEnqueue&&(l.queueEnqueue.disabled=Pe)}}else Ue("type a task first")}async function ze(e){if(s){Pe=!0,Ue("one"===e?"running one task…":"draining the queue…"),l.queueDrain&&(l.queueDrain.disabled=!0),l.queueProceed&&(l.queueProceed.disabled=!0),l.queueEnqueue&&(l.queueEnqueue.disabled=!0),l.queueStop&&(l.queueStop.hidden=!1);try{const t=await("one"===e?s.drain():s.proceed());Ue(function(e){if(!e||"object"!=typeof e)return"the drain did not answer";if(e.locked){const t=e.holder&&e.holder.pid;return"another drain is already running"+(t?` (pid ${t})`:"")}if(!1===e.ok)return e.reason||"the drain did not run";const t=Array.isArray(e.ran)?e.ran:[];if(!t.length)return e.stopped?"stopped before the next task":"nothing pending";const n=t.filter((e=>!e.ok)),o=[`ran ${t.length} — ${t.length-n.length} done`];return n.length&&o.push(`failed #${n.map((e=>e.id)).join(", #")}`),e.stopped&&o.push("stopped"),o.join(" · ")}(t)),Ke(t)}catch(e){Pe=!1,l.queueDrain&&(l.queueDrain.disabled=!1),l.queueProceed&&(l.queueProceed.disabled=!1),l.queueEnqueue&&(l.queueEnqueue.disabled=!1),l.queueStop&&(l.queueStop.hidden=!0),Ue(`drain failed: ${e&&e.message?e.message:e}`)}}}async function Ye(){if(s){l.queueStop&&(l.queueStop.disabled=!0),Ue("stopping…");try{const e=await s.stop(),t=e&&e.cancelled&&e.cancelled.ok;De=t?"stopped the running task":"stop requested",Ke(e)}catch(e){Ue(`stop failed: ${e&&e.message?e.message:e}`)}finally{l.queueStop&&(l.queueStop.disabled=!1)}}}async function Je(e,t){if(s){Ue(`${e} #${t}…`);try{const n=await s[e](t);n&&!1===n.ok?Ue(n.reason||`${e} failed`):Ue(`${"retry"===e?"re-queued":"removed"} #${t}`),Ke(n)}catch(t){Ue(`${e} failed: ${t&&t.message?t.message:t}`)}}}function Xe(e){e&&"object"==typeof e&&e.drain&&function(e){if(!l.queueAuto||!e||"object"!=typeof e)return;const t=!0===e.enabled;if(l.queueAuto.checked=t,l.queueAutoInterval){l.queueAutoInterval.disabled=!t;const n=Number(e.intervalMs);Number.isFinite(n)&&(l.queueAutoInterval.value=String(n))}if(l.queueAutoLabel&&(l.queueAutoLabel.textContent=t?`drain automatically · ${function(e){const t=Number(e);if(!Number.isFinite(t)||t<=0)return"every interval";if(t<6e4)return`every ${Math.round(t/1e3)}s`;const n=t/6e4;return Number.isInteger(n)?`every ${n} min`:`every ${n.toFixed(1)} min`}(e.intervalMs)}`:"drain automatically"),!l.queueAutoHint)return;if(!t)return void(l.queueAutoHint.textContent="off — Run one / Drain all are the only triggers");const n=[];e.busy?n.push("a drain is running"):e.armed&&n.push("armed"),e.ticks&&n.push(`${e.ticks} tick${1===e.ticks?"":"s"}`),e.drains&&n.push(`${e.drains} drained`);const o=e.lastSkip&&e.lastSkip.reason;o?n.push(`last check skipped: ${function(e,t={}){if("empty"===e)return"queue is empty";if("busy"===e)return"the previous drain is still running";if("locked"===e){const e=t.holder&&t.holder.pid;return e?`another drain holds the lock (pid ${e})`:"another drain holds the lock"}return"disabled"===e?"switched off":"no queue access"===e?"this window has no queue access":String(e)}(o,e.lastSkip)}`):e.ticks||n.push("first check one interval after arming"),l.queueAutoHint.textContent=n.join(" · ")}(e.drain)}async function Ze(){if(!a||"function"!=typeof a.status)return null;try{const e=await a.status();return Xe(e),e}catch(e){return l.queueAutoHint&&(l.queueAutoHint.textContent=`automation status unavailable: ${e&&e.message?e.message:e}`),null}}async function et(e){if(!a||"function"!=typeof a.setDrain)return;const t={enabled:Boolean(e)};l.queueAutoInterval&&l.queueAutoInterval.value&&(t.intervalMs=Number(l.queueAutoInterval.value));try{const e=await a.setDrain(t);e&&!1===e.ok&&l.queueAutoHint&&(l.queueAutoHint.textContent=e.error||"could not save that"),Xe(e)}catch(e){l.queueAutoHint&&(l.queueAutoHint.textContent=`could not save that: ${e&&e.message?e.message:e}`)}}function tt(e){if(!e||"object"!=typeof e)return;const t=null==e.taskId?"":`#${e.taskId} `;if("start"===e.type)Ue(`${t}running${e.model?` on ${e.model}`:""}…`);else if("tool"===e.type&&e.tool)Ue(`${t}${Mo(e.tool)}`);else if("finish"===e.type)Ue(`${t}${e.ok?"done":"failed"} — refreshing`),je(),Ze();else if("recovered"===e.type){const t=Array.isArray(e.ids)?e.ids:[];Ue(`recovered ${t.length} stalled task${1===t.length?"":"s"}`),Ze()}else"locked"===e.type?(Ue("another drain is already running"),Ze()):"queued"===e.type&&Ue(`queued phase ${e.phase}`)}function nt(e){const t=e&&e.prompt,o=e&&e.response;if(!t||!o)return;O||(O=Bo());const s=O,a=e&&e.model||"",i=e&&e.class||"",r=i||a?[i?i.toUpperCase():"",a].filter(Boolean).join(" · "):void 0;bo("user",t),bo("assistant",o,r,s),F.push({role:"user",content:t}),F.push({role:"assistant",content:o}),n.append(s,{role:"user",content:t}).catch((()=>{})),n.append(s,{role:"assistant",content:o}).catch((()=>{}))}const ot=10,st=6,at=50,it={entries:[],query:"",source:"",role:"",error:"",upgrade:null,local:!1,loading:!1};function rt(){if(ct())return!0;if(Rt())return!0;if(jt())return!0;if(zt())return!0;if(en())return!0;if(cn())return!0;if(wn())return!0;if(Hn())return!0;if(lt())return!0;if(dt&&"function"==typeof dt.isOpen)try{return!!dt.isOpen()}catch(e){return!1}return!1}function ct(){return!!l.memoryOverlay&&!l.memoryOverlay.hidden}function lt(){return!!l.keysOverlay&&!l.keysOverlay.hidden}let dt=null,ut=null,mt=!1;async function pt(e){if(!ut)return;if(mt&&!e)return;l.ptHint&&(l.ptHint.textContent="listing providers…");const n=await async function(){let e=[];try{e=await t.listClasses()||[]}catch(e){return l.ptHint.textContent=`listClasses failed: ${e&&e.message?e.message:e}`,[]}const n=[];for(const o of e){if(!o||!o.class)continue;let e=null;try{e=await t.listModels(o.class)}catch(t){e={models:[],error:t&&t.message||String(t)}}n.push({class:o.class,classLabel:o.label,classConfigured:Boolean(o.configured),list:e})}return n}();mt=!0,ut.set(n)}function ft(e){e&&e.class&&Array.from(l.classSelect.options).some((t=>t.value===e.class))&&(l.classSelect.value=e.class,localStorage.setItem(d,e.class),ie(e.class),Ro(e.class).then((()=>{e.model&&Array.from(l.modelSelect.options).some((t=>t.value===e.model))&&(l.modelSelect.value=e.model,l.modelSelect.dispatchEvent(new Event("change")))})))}const ht="aegis.companion.dismissed";function yt(){const e={keyConfigured:null===de?void 0:de};return Array.isArray(it.entries)&&it.entries.length&&(e.memoryCount=it.entries.length),pe&&"downloaded"===pe.status&&pe.version&&(e.updatePending=String(pe.version)),D.length&&l.modelSelect&&l.modelSelect.options.length>1&&(e.modelCount=l.modelSelect.options.length),e}function gt(){if(!window.aegisCompanion||!l.companionCard||!l.companionText)return;const e=new Date;let t=null;try{t=JSON.parse(localStorage.getItem(ht)||"null")}catch{t=null}if(window.aegisCompanion.dismissedToday(t,e))return void(l.companionCard.hidden=!0);const n=window.aegisCompanion.pickMessage(yt(),e);n&&n.text?(l.companionText.textContent=n.text,l.companionCard.dataset.kind=n.kind,l.companionCard.dataset.messageId=n.id,l.companionCard.hidden=!1):l.companionCard.hidden=!0}function vt(e){if(!Number.isFinite(e))return"";const t=Math.round((Date.now()-e)/1e3);if(t<45)return"just now";const n=Math.round(t/60);if(n<60)return`${n}m ago`;const o=Math.round(n/60);if(o<24)return`${o}h ago`;const s=Math.round(o/24);if(s<30)return`${s}d ago`;const a=Math.round(s/30);return a<12?`${a}mo ago`:`${Math.round(a/12)}y ago`}function Ct(e){const t=e&&"object"==typeof e?e:{},n=e=>Array.isArray(e)?e.filter((e=>null!=e&&""!==e)):[],o=e=>"string"==typeof e?e:"",s=e=>Number.isFinite(Number(e))?Number(e):null,a=o(t.content)||o(t.text)||o(t.entry);return{id:null!=t.id?String(t.id):"",content:a,source:o(t.source)||"(unknown source)",role:o(t.role),tags:n(t.tags),entities:n(t.entities),session:o(t.session),sentiment:o(t.sentiment),importance:s(t.importance),tokenCount:s(t.tokenCount),summary:!0===t.summary,createdAt:s(t.createdAt),timestamp:o(t.timestamp)}}async function kt(t,n){try{const o=t?await e.memorySearch(t,n):await e.memoryList(n),s=o&&(o.entries||o.results),a=Array.isArray(s)?s.map(Ct):[];return o&&o.upgrade?{entries:a,error:"",upgrade:o.upgrade,local:!0===o.local}:{entries:a,error:"",upgrade:null,local:o&&!0===o.local}}catch(e){const t=e&&e.status,n=e&&e.data&&e.data.error;return 402===t||"free_session_limit_reached"===n?{entries:[],error:"",upgrade:{url:e.data&&e.data.upgradeUrl||L("memory_quota"),used:e.data&&(null!=e.data.tokensUsed?e.data.tokensUsed:e.data.sessionsUsed),limit:e.data&&(null!=e.data.tokenLimit?e.data.tokenLimit:e.data.freeSessionLimit)}}:{entries:[],error:`search failed: ${e&&e.message?e.message:e}`,upgrade:null,local:!1}}}function bt(e){if(null==e||isNaN(e))return"?";const t=Number(e);return t>=1e6?`${(t/1e6).toFixed(t%1e6==0?0:1)}M`:t>=1e4?`${Math.round(t/1e3)}k`:t.toLocaleString("en-US")}function wt(e,t,n,o,s){if(!e)return;const a=null!=t.used?bt(t.used):"?",i=null!=t.limit?bt(t.limit):"?";e.textContent=`${n||"sync limit reached"} — ${a} of ${i} tokens synced. Nothing was lost. ${x} `,I(e,t.url,s||"memory_quota",o||"See what Pro covers →")}function xt(e,t){wt(l.memoryHint,e,t)}async function St(e){l.memoryHint.textContent="searching…";const t=await kt(e,ot);(function(e,t,n,o=!1){l.memoryResults.innerHTML="";const s=Array.isArray(e)?e:[],a=function(e,t,n,o){return!o||!(!t&&!n)||e.some((e=>function(e){return e&&null!=e.importance?e.importance:5}(e)>=st))}(s,t,n,o),i=!!o&&!t&&!n&&s.length>0&&!a;if(function(e){const t=!!e.hasAny,n=!!e.hasBox,o=!!e.quietNotice;l.tabMemory&&(l.tabMemory.hidden=!(t||n||o)),l.memoryBox&&(l.memoryBox.hidden=!n),l.memoryQuiet&&(l.memoryQuiet.hidden=!o),l.tabMemory&&l.tabMemory.hidden&&"memory"===Qo&&Wo("sessions")}({hasAny:s.length>0,hasBox:a,quietNotice:i}),a){if(n){const e=document.createElement("li");return e.className="empty mem-side-upgrade",l.memoryResults.appendChild(e),void I(e,n.url,"memory_quota","Free plan limit reached — see what Pro covers →")}if(t){const e=document.createElement("li");return e.className="empty",e.textContent=t,void l.memoryResults.appendChild(e)}if(!s.length){const e=document.createElement("li");return e.className="empty",e.textContent="no memory entries",void l.memoryResults.appendChild(e)}for(const e of s){const t=document.createElement("li"),n=document.createElement("span");n.className="mem-side-src",n.textContent=e.source;const o=document.createElement("span");o.className="mem-side-body",o.textContent=e.content||"(empty)",t.appendChild(n),t.appendChild(o),l.memoryResults.appendChild(t)}}})(t.entries,t.error,t.upgrade,""===e),t.upgrade?xt(t.upgrade,"cloud memory needs an active plan"):t.local?l.memoryHint.textContent=Et:l.memoryHint.textContent=t.error||""}const Et="offline — showing this device’s saved copy";function $t(e,t){const n=document.createElement("span");return n.className="mem-chip"+(t?` ${t}`:""),n.textContent=e,n}function Lt(e){const t=document.createElement("li");t.className="mem-card";const n=document.createElement("div");n.className="mem-card-head",n.appendChild($t(e.source,"src")),e.role&&n.appendChild($t(e.role,"role")),null!=e.importance&&n.appendChild($t(`imp ${e.importance}`,"imp")),e.sentiment&&n.appendChild($t(e.sentiment,"sent")),e.summary&&n.appendChild($t("summary","flag"));const o=document.createElement("span");o.className="mem-card-meta";const s=[],a=vt(e.createdAt);a?s.push(a):e.timestamp&&s.push(e.timestamp),e.session&&s.push(`session ${e.session}`),null!=e.tokenCount&&s.push(`${e.tokenCount} tokens`),o.textContent=s.join(" · "),n.appendChild(o),t.appendChild(n);const i=document.createElement("p");i.className="mem-card-body",i.textContent=e.content||"(empty)",t.appendChild(i);const r=[...e.tags,...e.entities];if(r.length){const e=document.createElement("div");e.className="mem-card-pills";for(const t of r)e.appendChild($t(t,"pill"));t.appendChild(e)}return i.addEventListener("click",(()=>{window.getSelection&&String(window.getSelection())||t.classList.toggle("expanded")})),t}function qt(e){const t=new Map;for(const n of it.entries){const o=n[e];o&&t.set(o,(t.get(o)||0)+1)}return[...t.entries()].sort(((e,t)=>t[1]-e[1]))}function Mt(){if(!ct())return;const e=it.entries.length;if(l.memoryList.innerHTML="",function(){if(l.memoryChips.innerHTML="",it.upgrade||it.error)return;const e=[["source","source",qt("source")],["role","role",qt("role")]];for(const[t,n,o]of e){if(o.length<2)continue;const e=document.createElement("div");e.className="mem-chip-group";const s=document.createElement("span");s.className="mem-chip-label",s.textContent=n,e.appendChild(s);for(const[n,s]of o){const o=document.createElement("button");o.type="button",o.className="mem-chip btn"+(it[t]===n?" on":""),o.textContent=`${n} ${s}`,o.addEventListener("click",(()=>{it[t]=it[t]===n?"":n,Mt()})),e.appendChild(o)}l.memoryChips.appendChild(e)}}(),it.loading)return void(l.memoryCount.textContent="loading…");if(it.upgrade){l.memoryCount.textContent="";const e=document.createElement("li");e.className="mem-empty mem-upgrade";const t=document.createElement("strong");t.textContent="Cloud memory is paused on the free plan";const n=document.createElement("span"),o=null!=it.upgrade.used?bt(it.upgrade.used):"?",s=null!=it.upgrade.limit?bt(it.upgrade.limit):"?";return n.textContent=`This account has used ${o} of ${s} tokens of synced conversation. Saved memory is still readable — only new saves are paused until there is room again. `+x,e.appendChild(t),e.appendChild(n),l.memoryList.appendChild(e),void I(e,it.upgrade.url,"memory_quota","Open subscribe page ↗")}if(it.error){l.memoryCount.textContent="";const e=document.createElement("li");return e.className="mem-empty",e.textContent=it.error,void l.memoryList.appendChild(e)}if(!e){l.memoryCount.textContent="0 entries";const e=document.createElement("li");return e.className="mem-empty",e.textContent="No memory entries yet — save a note below, or import from other AI tools.",void l.memoryList.appendChild(e)}const t=it.query.trim().toLowerCase(),n=it.entries.filter((e=>(!it.source||e.source===it.source)&&(!it.role||e.role===it.role)&&(!t||function(e,t){return[e.content,e.source,e.role,e.session,e.sentiment,...e.tags,...e.entities].join("\n").toLowerCase().includes(String(null==t?"":t).toLowerCase())}(e,t)))),o=new Set(it.entries.map((e=>e.source))).size,s=it.local?`offline · saved on this device · ${o} source${1===o?"":"s"}`:`${o} source${1===o?"":"s"}`;if(l.memoryCount.textContent=`${n.length} of ${e} shown · ${s}`+(e>=at?` · newest ${at}`:""),!n.length){const e=document.createElement("li");return e.className="mem-empty",e.textContent="Nothing matches those filters.",void l.memoryList.appendChild(e)}for(const e of n)l.memoryList.appendChild(Lt(e))}async function At(e){it.loading=!0,it.error="",it.upgrade=null,it.local=!1,Mt();const t=await kt(e,at);it.entries=t.entries,it.error=t.error,it.upgrade=t.upgrade,it.local=!0===t.local,it.loading=!1,Mt()}function Nt(){l.memoryOverlay&&(xn({kind:"memory"}),l.memoryOverlay.hidden=!1,document.body.classList.add("memory-open"),l.memoryOverlayQuery.value=l.memoryQuery?l.memoryQuery.value.trim():"",it.query=l.memoryOverlayQuery.value,it.source="",it.role="",Mt(),At(it.query),l.memoryOverlayQuery&&l.memoryOverlayQuery.focus())}function Ht(){l.memoryOverlay&&(l.memoryOverlay.hidden=!0,document.body.classList.remove("memory-open"),l.memoryOpen&&l.memoryOpen.focus())}let Bt=null,It="";function Rt(){return!!l.sessionOverlay&&!l.sessionOverlay.hidden}function Tt(e,t){const n=document.createElement("li");n.className="session-row",n.tabIndex=0;const o=document.createElement("span");o.className="session-title",o.textContent=e&&e.title||e&&e.id||"untitled",n.appendChild(o);const s=document.createElement("span");s.className="session-meta";const a=[],i=e&&Array.isArray(e.messages)&&e.messages.length||0;i&&a.push(`${i} msg${1===i?"":"s"}`),e&&e.updatedAt&&a.push(vt(new Date(e.updatedAt).getTime())||String(e.updatedAt)),t&&e&&e.reason&&a.push(`match: ${e.reason}`),s.textContent=a.join(" · "),n.appendChild(s);const r=()=>{_t(),ms(e.id)};return n.addEventListener("click",r),n.addEventListener("keydown",(e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),r())})),n}function Ot(e){const t=document.createElement("li");t.className="session-row mem-result-row",t.tabIndex=0;const n=document.createElement("span");n.className="session-title mem-result-body",n.textContent=e&&e.content||"(empty)",t.appendChild(n);const o=document.createElement("span");o.className="session-meta";const s=[];if(e&&e.scope&&s.push(e.scope),e&&e.updated){const t=vt(new Date(e.updated).getTime());s.push(t||String(e.updated))}e&&Array.isArray(e.tags)&&e.tags.length&&s.push(e.tags.slice(0,4).join(", ")),o.textContent=s.join(" · "),t.appendChild(o);const a=()=>{_t(),Nt(),l.memoryOverlayQuery&&Bt&&(l.memoryOverlayQuery.value=Bt,it.query=Bt,Mt(),At(Bt))};return t.addEventListener("click",a),t.addEventListener("keydown",(e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),a())})),t}function Ft(e,t){const n=document.createElement("li");return n.className="session-section-head",n.setAttribute("role","presentation"),n.textContent=null==t?e:`${e} · ${t}`,n}async function Dt(e){const t=String(null==e?"":e).trim();if(Bt=t,l.sessionHint&&(l.sessionHint.textContent=t?`searching “${t}”…`:""),!n||"function"!=typeof n.searchSessions)return void(l.sessionHint&&(l.sessionHint.textContent="session search is unavailable in this build."));let o=null;try{o=await n.searchSessions(t,50)}catch(e){return void(l.sessionHint&&(l.sessionHint.textContent=`search failed: ${e&&e.message||e}`))}t===Bt&&(l.sessionHint&&(l.sessionHint.textContent=""),function(e,t){if(!l.sessionList)return;l.sessionList.innerHTML="";const n=e&&e.sessions||[],o=e&&e.memory||[],s=e&&e.memoryStatus||"ok",a="ok"!==s,i="memory"!==It,r=i?n:[];if(l.sessionCount){const t=[`${r.length} session${1===r.length?"":"s"}`];a?t.push("unavailable"===s?"memory needs Node ≥ 22.5":"memory index unreadable"):t.push(`${o.length} memor${1===o.length?"y":"ies"}`),e&&Number.isInteger(e.total)&&e.total>r.length&&i&&(t[0]=`${r.length} of ${e.total} sessions`),l.sessionCount.textContent=t.join(" · ")}if(r.length||o.length){if(r.length){l.sessionList.appendChild(Ft("Sessions",r.length));for(const e of r)l.sessionList.appendChild(Tt(e,t))}if(o.length){l.sessionList.appendChild(Ft("Memory",o.length));for(const e of o)l.sessionList.appendChild(Ot(e))}}else{const e=document.createElement("li");if(e.className="empty",a){const t="unavailable"===s?"needs Node ≥ 22.5":"index could not be read";e.textContent=i?`no matching sessions — memory search ${t}`:`memory search ${t}`}else e.textContent=t?`nothing matches “${t}”`:"nothing to search yet — start a conversation or save a memory";l.sessionList.appendChild(e)}}(o,t))}function Pt(e){l.sessionOverlay&&(It="memory"===e?"memory":"",l.sessionOverlay.hidden=!1,document.body.classList.add("memory-open"),l.sessionQuery&&(l.sessionQuery.value="",l.sessionQuery.focus()),l.sessionHint&&(l.sessionHint.textContent="memory"===It?"memory only — clear to search everything":""),Dt(""))}function Ut(){Pt("memory")}function _t(){l.sessionOverlay&&(l.sessionOverlay.hidden=!0,document.body.classList.remove("memory-open"))}let Kt=null;function jt(){return!!l.importOverlay&&!l.importOverlay.hidden}function Vt(){l.importOverlay&&(l.importOverlay.hidden=!0,document.body.classList.remove("memory-open"),l.importSessionBtn&&l.importSessionBtn.focus())}function Gt(e){const t=document.createElement("li");t.className="import-row";const n=document.createElement("span");n.className="import-source",n.textContent=e.label||e.id,t.appendChild(n);const o=document.createElement("span");if(o.className="session-meta",e.present)if(e.unreadable)o.textContent="found, store not readable yet",t.classList.add("import-absent");else if(e.count){const t=e.messages?` · ${e.messages} msg${1===e.messages?"":"s"}`:"";o.textContent=`${e.count} session${1===e.count?"":"s"}${t}${e.verified?"":" · best-effort"}`}else o.textContent="found, no conversations";else o.textContent="not installed",t.classList.add("import-absent");return t.appendChild(o),t}async function Qt(){l.importOverlay&&(l.importOverlay.hidden=!1,document.body.classList.add("memory-open"),l.importList&&(l.importList.innerHTML=""),l.importSessionsBtn&&(l.importSessionsBtn.disabled=!0),l.importHint&&(l.importHint.textContent="scanning this machine…"),await async function(){if(!n||"function"!=typeof n.sessionsImportScan)return l.importHint&&(l.importHint.textContent="import is unavailable in this build."),null;l.importHint&&(l.importHint.textContent="scanning this machine…");try{Kt=await n.sessionsImportScan()}catch(e){return l.importHint&&(l.importHint.textContent=`scan failed: ${e&&e.message||e}`),null}return function(e){if(!l.importList)return;l.importList.innerHTML="";const t=e&&e.sources||[],n=e&&e.totals||{};if(l.importCount&&(l.importCount.textContent=`${n.sessions||0} session(s), ${n.messages||0} msg(s)`),!t.length){const e=document.createElement("li");return e.className="empty",e.textContent="no other AI tools were looked for",void l.importList.appendChild(e)}for(const e of t)l.importList.appendChild(Gt(e));const o=(n.sessions||0)>0;l.importSessionsBtn&&(l.importSessionsBtn.disabled=!o),l.importHint&&(l.importHint.textContent=o?"read-only scan — nothing is copied until you press Import sessions":"nothing importable was found; the Memory card can still import memory fragments")}(Kt),Kt}())}async function Wt(){if(!n||"function"!=typeof n.sessionsImport)return;const e=l.importSessionsBtn;e&&(e.disabled=!0),l.importHint&&(l.importHint.textContent="copying sessions into AEGIS…");try{const e=await n.sessionsImport({confirm:!0,limit:500,sync:!(!l.importSync||!l.importSync.checked)});if(!e||!e.ok)return void(l.importHint&&(l.importHint.textContent=`import stopped: ${e&&e.reason||"unknown error"}`));const t=e.skippedExisting?`, ${e.skippedExisting} already here`:"";l.importHint&&(l.importHint.textContent=`imported ${e.imported} session(s)${t}.`),await os()}catch(e){l.importHint&&(l.importHint.textContent=`import failed: ${e&&e.message||e}`)}finally{e&&(e.disabled=!1)}}
4
4
  // at all before this: the AGPL lived in file headers and LICENSE, the plain
5
- function zt(){return!!l.creditsOverlay&&!l.creditsOverlay.hidden}function Yt(e,t){const n=document.createElement("section");n.className="credits-section";const o=document.createElement("h3");o.textContent=e,n.appendChild(o);const s=document.createElement("ul");s.className="credits-rows";for(const e of t){const t=document.createElement("li");t.className="credits-row";const n=document.createElement("span");n.className="credits-name",n.textContent=e.name||"",t.appendChild(n);const o=document.createElement("span");if(o.className="credits-meta",o.textContent=[e.version,e.licence,e.copyright].filter(Boolean).join(" · "),t.appendChild(o),e.url){const n=document.createElement("a");n.href=e.url,n.textContent=e.url.replace(/^https?:\/\//,""),n.target="_blank",n.rel="noopener noreferrer",t.appendChild(n)}s.appendChild(t)}return n.appendChild(s),n}function Jt(e){if(!l.creditsBody)return;l.creditsBody.innerHTML="";const t=e&&"object"==typeof e?e:{},n=t.program||{};l.creditsLicenceTag&&(l.creditsLicenceTag.textContent=n.licence||"");const o=document.createElement("section");o.className="credits-section";const s=document.createElement("h3");s.textContent="This program",o.appendChild(s);const a=document.createElement("p");if(a.className="credits-line",a.textContent=`${n.name||"AGPL"} — ${n.licence||""}`,o.appendChild(a),n.copyright){const e=document.createElement("p");e.className="credits-line",e.textContent=n.copyright,o.appendChild(e)}if(n.url){const e=document.createElement("p");e.className="credits-line";const t=document.createElement("a");t.href=n.url,t.textContent="Full licence text",t.target="_blank",t.rel="noopener noreferrer",e.appendChild(t),o.appendChild(e)}if(n.source){const e=document.createElement("p");e.className="credits-line";const t=document.createElement("a");t.href=n.source,t.textContent="Corresponding source",t.target="_blank",t.rel="noopener noreferrer",e.appendChild(t),o.appendChild(e)}if(n.notice){const e=document.createElement("pre");e.className="credits-notice",e.textContent=n.notice,o.appendChild(e)}if(l.creditsBody.appendChild(o),Array.isArray(t.code)&&t.code.length&&l.creditsBody.appendChild(Yt("Vendored third-party code",t.code)),Array.isArray(t.fonts)&&t.fonts.length&&l.creditsBody.appendChild(Yt("Vendored webfonts",t.fonts)),Array.isArray(t.missing)&&t.missing.length){const e=document.createElement("p");e.className="hint",e.textContent=`Could not read: ${t.missing.join(", ")} — the in-app attribution list may be incomplete.`,l.creditsBody.appendChild(e)}}function Xt(){l.creditsOverlay&&(xn({kind:"credits"}),l.creditsOverlay.hidden=!1,document.body.classList.add("memory-open"),async function(){if(!l.creditsBody)return;if(l.creditsStatus&&(l.creditsStatus.textContent="loading…"),!e||"function"!=typeof e.credits)return Jt(null),void(l.creditsStatus&&(l.creditsStatus.textContent=""));let t=null;try{t=await e.credits()}catch(e){return void(l.creditsStatus&&(l.creditsStatus.textContent=`could not read the licence files: ${e&&e.message||e}`))}l.creditsStatus&&(l.creditsStatus.textContent=""),Jt(t)}())}function Zt(){l.creditsOverlay&&(l.creditsOverlay.hidden=!0,document.body.classList.remove("memory-open"))}function en(){return!!l.shortcutsOverlay&&!l.shortcutsOverlay.hidden}function tn(){l.shortcutsOverlay&&(xn({kind:"shortcuts"}),function(){if(!l.shortcutsBody)return;const e=window.aegisShortcuts,t=window.aegis&&window.aegis.platform||navigator.platform||"";if(l.shortcutsBody.textContent="",!e||!Array.isArray(e.SHORTCUTS)){const e=document.createElement("p");return e.className="hint",e.textContent="The shortcut table failed to load (renderer/shortcuts.js).",void l.shortcutsBody.appendChild(e)}let n=0;for(const o of e.groups()){const s=e.rowsFor(o),a=document.createElement("section");a.className="shortcuts-section";const i=document.createElement("h3");i.className="shortcuts-group",i.textContent=o,a.appendChild(i);const r=document.createElement("div");r.className="keys-rows";for(const o of s){n+=1;const s=document.createElement("div");s.className="keys-row";const a=document.createElement("span");a.className="keys-state shortcuts-chord",a.textContent=e.platformize(o.chord,t);const i=document.createElement("div");i.className="keys-body";const c=document.createElement("b");c.textContent=o.label,i.appendChild(c);const l=o.note||o.where;if(l&&i.appendChild(document.createTextNode(` — ${l}`)),o.hidden){const e=document.createElement("span");e.className="hint shortcuts-hidden-note",e.textContent=" Not in the menu; the chord still works.",i.appendChild(e)}s.appendChild(a),s.appendChild(i),r.appendChild(s)}a.appendChild(r),l.shortcutsBody.appendChild(a)}l.shortcutsCount&&(l.shortcutsCount.textContent=`${n} chord${1===n?"":"s"}`)}(),l.shortcutsOverlay.hidden=!1,document.body.classList.add("memory-open"))}function nn(){l.shortcutsOverlay&&(l.shortcutsOverlay.hidden=!0,document.body.classList.remove("memory-open"))}let on=[],sn=-1;function an(){return{cliFace:void 0!==e&&e&&"function"==typeof e.openCliFace}}function rn(){return globalThis.AegisPaletteFilter||null}function cn(){return!!l.paletteOverlay&&!l.paletteOverlay.hidden}function ln(e){if(!l.paletteList)return;const t=rn(),n=function(){const e=globalThis.AegisCommands;return e&&Array.isArray(e.COMMANDS)?e.availableCommands(e.COMMANDS,an()):[]}();on=t?t.filterCommands(n,e):n.slice(),sn=t?t.initialIndex(on):on.length?0:-1,l.paletteList.replaceChildren();for(let e=0;e<on.length;e+=1){const t=on[e],n=document.createElement("li");n.className="palette-row"+(e===sn?" is-active":""),n.id=`palette-row-${e}`,n.setAttribute("role","option"),n.setAttribute("aria-selected",e===sn?"true":"false"),n.dataset.index=String(e);const o=document.createElement("span");if(o.className="palette-row-label",o.textContent=t.label,n.appendChild(o),t.hint){const e=document.createElement("span");e.className="palette-row-hint",e.textContent=t.hint,n.appendChild(e)}n.addEventListener("mousedown",(n=>{n.preventDefault(),sn=e,Pn(t.action)})),l.paletteList.appendChild(n)}l.paletteEmpty&&(l.paletteEmpty.hidden=on.length>0),dn()}function dn(){if(!l.paletteList)return;const e=l.paletteList.children;for(let t=0;t<e.length;t+=1){const n=t===sn;e[t].classList.toggle("is-active",n),e[t].setAttribute("aria-selected",n?"true":"false")}l.paletteInput&&(sn>=0?l.paletteInput.setAttribute("aria-activedescendant",`palette-row-${sn}`):l.paletteInput.removeAttribute("aria-activedescendant"));const t=e[sn];t&&"function"==typeof t.scrollIntoView&&t.scrollIntoView({block:"nearest"})}function un(e){const t=rn();t&&(sn=t.moveIndex(sn,on.length,e),dn())}function mn(){l.paletteOverlay&&(l.paletteOverlay.hidden=!1,document.body.classList.add("memory-open"),l.paletteInput&&(l.paletteInput.value="",l.paletteInput.focus()),ln(""))}function pn(){l.paletteOverlay&&(l.paletteOverlay.hidden=!0,document.body.classList.remove("memory-open"),on=[],sn=-1)}function fn(){if(!l.side)return;const e=l.side.classList.toggle("is-collapsed");l.side.setAttribute("aria-hidden",e?"true":"false")}let hn={query:"",matches:[],index:-1,texts:[]},yn=AegisNavHistory.createHistory(),gn=!1;function vn(){return globalThis.AegisFindInConversation||null}function Cn(){const e="undefined"!=typeof CSS&&CSS.highlights?CSS.highlights:null;if(!e)return;e.delete("find-match"),e.delete("find-match-current");const t=[],n=[];for(let e=0;e<hn.matches.length;e+=1){const o=hn.matches[e],s=hn.texts[o.textIndex];if(!s)continue;const a=document.createRange();a.setStart(s,o.start),a.setEnd(s,o.end),t.push(a),e===hn.index&&n.push(a)}t.length&&e.set("find-match",new Highlight(...t)),n.length&&e.set("find-match-current",new Highlight(...n))}function kn(e){const t=vn();if(!t)return;hn.texts=function(){const e=l.messages;if(!e||"function"!=typeof document.createTreeWalker)return[];const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null),n=[];let o=t.nextNode();for(;o;)o.nodeValue&&o.nodeValue.trim()&&n.push(o),o=t.nextNode();return n}();const n=hn.texts.map((e=>e.nodeValue||""));hn.matches=t.findMatches(n,hn.query,{caseSensitive:!1}),hn.index=hn.matches.length?0:-1,Cn(),l.findCount&&(l.findCount.textContent=t.matchLabel(hn.index,hn.matches.length)),e&&bn()}function bn(){const e=hn.matches[hn.index];if(!e)return;const t=hn.texts[e.textIndex];if(!t)return;const n=t.parentElement;n&&"function"==typeof n.scrollIntoView&&n.scrollIntoView({block:"center",behavior:"smooth"})}function wn(){return!!l.findBar&&!l.findBar.hidden}function xn(e){gn||(yn=AegisNavHistory.pushEntry(yn,e),Sn())}function Sn(){e.setNavState&&e.setNavState({back:AegisNavHistory.canGoBack(yn),forward:AegisNavHistory.canGoForward(yn)}).catch((()=>{}))}function En(e){if(e){gn=!0;try{!function(){for(const e of[l.memoryOverlay,l.creditsOverlay,l.shortcutsOverlay,l.keysOverlay])e&&(e.hidden=!0);document.body.classList.remove("memory-open","keys-open")}(),"settings"===e.kind?ao():"automations"===e.kind?io():"session"===e.kind&&e.id?ms(e.id,{fromNav:!0}):"memory"===e.kind?Nt():"credits"===e.kind?Xt():"shortcuts"===e.kind?tn():"keys"===e.kind?go():ro()}finally{gn=!1}}}function $n(){const e=AegisNavHistory.back(yn);e?(yn=e.state,En(e.entry),Sn()):l.sessionsHint.textContent="already at the start of the history"}function Ln(){const e=AegisNavHistory.forward(yn);e?(yn=e.state,En(e.entry),Sn()):l.sessionsHint.textContent="already at the newest place"}function qn(){l.findBar&&(l.findBar.hidden=!1,l.findInput&&(l.findInput.focus(),"function"==typeof l.findInput.select&&l.findInput.select()),hn.query&&kn(!0))}function Mn(){l.findBar&&(l.findBar.hidden=!0,"undefined"!=typeof CSS&&CSS.highlights&&(CSS.highlights.delete("find-match"),CSS.highlights.delete("find-match-current")),l.prompt&&"function"==typeof l.prompt.focus&&l.prompt.focus())}let An={kind:"",rows:[],index:-1,span:null,query:""};function Nn(){return globalThis.AegisComposerTriggers||null}function Hn(){return!!l.composerMenu&&!l.composerMenu.hidden}const Bn=new Set(["exportJson","toggleSidebar","keys","credits","find"]);function In(){An={kind:"",rows:[],index:-1,span:null,query:""},l.composerMenu&&(l.composerMenu.hidden=!0),l.composerMenuHint&&(l.composerMenuHint.hidden=!0),l.composerMenuList&&l.composerMenuList.replaceChildren()}function Rn(){if(!l.composerMenuList)return;l.composerMenuList.replaceChildren();const e=An.rows;for(let t=0;t<e.length;t+=1){const n=e[t],o=document.createElement("li");o.className="composer-menu-row"+(t===An.index?" is-active":""),o.id=`composer-row-${t}`,o.setAttribute("role","option"),o.setAttribute("aria-selected",t===An.index?"true":"false"),o.dataset.index=String(t);const s=document.createElement("span");if(s.className="composer-menu-label",s.textContent=n.label,o.appendChild(s),n.hint){const e=document.createElement("span");e.className="composer-menu-hint-text",e.textContent=n.hint,o.appendChild(e)}o.addEventListener("mousedown",(e=>{e.preventDefault(),An.index=t,On()})),l.composerMenuList.appendChild(o)}const t=l.composerMenuList.children[An.index];if(t&&"function"==typeof t.scrollIntoView&&t.scrollIntoView({block:"nearest"}),l.composerMenu&&(l.composerMenu.hidden=0===e.length),l.composerMenuHint){const t=0===e.length;l.composerMenuHint.hidden=!t,t&&(l.composerMenuHint.textContent="mention"===An.kind?An.query?`nothing matches “${An.query}”`:"no sessions or memories to mention yet":"no command matches")}e.length&&function(){if(!l.composerMenu)return;const e=l.composer||l.prompt&&l.prompt.parentElement;if(!e)return;const t=e.getBoundingClientRect(),n=l.composerMenu.offsetHeight||0;l.composerMenu.style.left=`${Math.round(t.left)}px`,l.composerMenu.style.width=`${Math.round(t.width)}px`,l.composerMenu.style.top=`${Math.round(t.top-n-6)}px`}()}async function Tn(){const e=Nn(),t=l.prompt;if(!e||!t)return;const o=e.activeTrigger(t.value,t.selectionStart);if(!o)return void(Hn()&&In());const s={start:o.start,end:o.end};let a;if(An.kind=o.kind,An.span=s,An.query=o.query,"slash"===o.kind)a=e.rankRows(function(){const e=globalThis.AegisCommands;return e&&Array.isArray(e.COMMANDS)?e.availableCommands(e.COMMANDS,an()).filter((e=>!Bn.has(e.action))).map((e=>({label:`/${e.label}`,hint:e.hint||"",keywords:e.keywords||"",action:e.action,row:"command"}))):[]}(),o.query);else{a=e.rankRows(await async function(e){if(!n||"function"!=typeof n.searchSessions)return[];let t=null;try{t=await n.searchSessions(e,8)}catch(e){return[]}const o=[],s=Array.isArray(t&&t.memory)?t.memory:[];for(const e of s){const t=String(e&&e.content||"").replace(/\s+/g," ").trim();t&&o.push({label:t.length>72?`${t.slice(0,71)}…`:t,hint:e.scope?`memory · ${e.scope}`:"memory",keywords:Array.isArray(e.tags)?e.tags.join(" "):"",action:"stageMemory",row:"memory",memory:e})}const a=Array.isArray(t&&t.sessions)?t.sessions:[];for(const e of a){const t=String(e&&e.title||"").trim()||"(untitled)";o.push({label:t,hint:"session · open",keywords:"",action:"openSessionRow",row:"session",session:e})}return o}(o.query),o.query);const i=e.activeTrigger(t.value,t.selectionStart);if(!i||"mention"!==i.kind||i.start!==s.start)return}An.rows=a,An.index=a.length?0:-1,Rn()}async function On(){const e=An.rows[An.index],t=l.prompt;if(!e||!t)return void In();const n=An.span,o=An.kind,s=t.value,a=Math.max(0,Math.min(n?n.start:s.length,s.length)),i=Math.max(a,Math.min(n?n.end:s.length,s.length)),r=s.slice(i);if("slash"===o)return t.value=(s.slice(0,a)+r).replace(/\s{2,}/g," ").trimStart(),In(),void Pn(e.action);if(In(),"openSessionRow"===e.action&&e.session)return t.value=(s.slice(0,a)+r).replace(/\s{2,}/g," ").trimStart(),void ms(e.session.id);if("stageMemory"===e.action&&e.memory){const n=e.memory,o=String(n.content||"");Cs.some((e=>"text"===e.kind&&e.text===o))||(Cs.push({kind:"text",name:n.scope?`memory: ${n.scope}`:"memory",path:"",size:o.length,mime:"text/plain",text:o,truncated:!1}),xs());const i=n.scope?`@${n.scope}`:"@memory";t.value=s.slice(0,a)+i+r;const c=a+i.length;t.setSelectionRange(c,c),t.focus()}}function Fn(e){const t=Nn();t&&An.rows.length&&(An.index=t.stepRow(An.rows.length,An.index,e),Rn())}function Dn(e){const t=vn();t&&hn.matches.length&&(hn.index=t.stepMatch(hn.index,hn.matches.length,e),Cn(),l.findCount&&(l.findCount.textContent=t.matchLabel(hn.index,hn.matches.length)),bn())}function Pn(e){switch(pn(),e){case"newChat":return void fs();case"go-back":return void $n();case"go-forward":return void Ln();case"search":return void Pt("");case"find":return void qn();case"settings":return void ao();case"customizations":return ao(),void oo(l.confirmMode);case"automations":return void Promise.all([Ze().catch((()=>{})),je().catch((()=>{}))]).then((()=>io()));case"cli":return void(l.openCliFace&&l.openCliFace.click());case"import":return void(l.importSessionBtn&&l.importSessionBtn.click());case"exportMarkdown":return void ps("markdown");case"exportJson":return void ps("json");case"memory":return void Nt();case"fingerprint":return void(dt&&"function"==typeof dt.open&&dt.open());case"shortcuts":return void tn();case"keys":return void go();case"credits":return void Xt();case"toggleSidebar":return void fn();default:throw new Error(`palette: unknown action ${e}`)}}async function Un(){const t=ct()&&l.memoryOverlayEntry?l.memoryOverlayEntry:l.memoryEntry;if(!t)return;const n=t.value.trim();if(n){l.memorySaveBtn.disabled=!0,l.memoryOverlaySave&&(l.memoryOverlaySave.disabled=!0),l.memoryHint.textContent="saving…";try{const o=await e.memorySave({text:n,source:"aegis-desktop"});if(o&&o.upgrade)return xt(o.upgrade,"free plan limit reached"),void await _n();t.value="",l.memoryHint.textContent=o&&o.queued?"saved offline — syncs when AEGIS is reachable.":"saved.",await _n()}catch(e){l.memoryHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{l.memorySaveBtn.disabled=!1,l.memoryOverlaySave&&(l.memoryOverlaySave.disabled=!1)}}}async function _n(){const e=l.memoryQuery?l.memoryQuery.value.trim():"";await St(e),ct()&&await At(it.query)}function Kn(){const e=yt();return void 0===e.keyConfigured&&delete e.keyConfigured,e}function jn(){const e=document.getElementById("welcome-personal");if(!e)return;const t=function(e){const t=window.aegisCompanion;if(!t||"function"!=typeof t.pickMessage)return null;const n=t.pickMessage(Kn(),new Date);return n&&n.text?{text:n.text,kind:n.kind||"tip"}:null}();if(!t)return e.textContent="",void(e.hidden=!0);e.textContent=t.text,e.dataset.kind=t.kind,e.hidden=!1}const Vn="aegis.welcomeRowsDismissed";function Gn(){const e=window.aegisWelcomeRows;if(!e)return[];try{return e.parseDismissed(localStorage.getItem(Vn))}catch{return[]}}function Qn(e){const t=document.createElement("div");t.className="welcome-row",t.dataset.rowId=e.id;const n=document.createElement("button");n.type="button",n.className="welcome-row-go";const o=document.createElement("span");if(o.className="welcome-row-label",o.textContent=e.label,n.appendChild(o),e.hint){const t=document.createElement("span");t.className="welcome-row-hint",t.textContent=e.hint,n.appendChild(t)}n.addEventListener("click",(()=>function(e){switch(e){case"update":l.updateRestartBtn&&l.updateRestartBtn.click();break;case"sessions":Pt("");break;case"memory":Nt();break;case"cli":l.openCliFace&&l.openCliFace.click()}}(e.action))),t.appendChild(n);const s=document.createElement("button");return s.type="button",s.className="welcome-row-x",s.setAttribute("aria-label",`Dismiss: ${e.label}`),s.textContent="✕",s.addEventListener("click",(()=>function(e){const t=window.aegisWelcomeRows;if(t){try{localStorage.setItem(Vn,t.withDismissed(Gn(),e))}catch{}Wn()}}(e.id))),t.appendChild(s),t}function Wn(){const t=document.getElementById("welcome-rows"),n=window.aegisWelcomeRows;if(!t||!n)return;const o=n.pickRows(function(){const t=Kn();return es.length&&(t.sessionCount=es.length),void 0!==e&&e&&"function"==typeof e.openCliFace&&(t.cliAvailable=!0),t}(),Gn());if(t.innerHTML="",o.length){for(const e of o)t.appendChild(Qn(e));t.hidden=!1}else t.hidden=!0}const zn="aegis.welcomeAiLine",Yn=120,Jn=200;function Xn(e){const t=e instanceof Date?e:new Date(null==e?Date.now():e);if(Number.isNaN(t.getTime()))return"";const n=e=>String(e).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}`}function Zn(e){const t=(new Date).getHours(),n=t>=5&&t<12?"morning":t>=12&&t<17?"afternoon":t>=17&&t<22?"evening":"late night",o=[];return"number"==typeof e.memoryCount&&o.push(`${e.memoryCount} entries saved in the user's memory`),"number"==typeof e.modelCount&&o.push(`${e.modelCount} models available`),"string"==typeof e.updatePending&&o.push(`update ${e.updatePending} is downloaded and installs on quit`),!0===e.keyConfigured&&o.push("the account key is connected"),!1===e.keyConfigured&&o.push("no account key is connected yet"),["Write the one sentence shown at the top of a coding assistant's empty",`chat panel. It is ${n} for the person reading it.`,o.length?`What you know about their setup: ${o.join("; ")}.`:"","Rules: one sentence, at most 25 words, second person, no greeting cliché",'like "Welcome back", no exclamation marks, no quotes, no preamble, no',"markdown. Say something specific and useful about their work right now, or","ask one short question that helps them start. Reply with the sentence only."].filter(Boolean).join(" ")}function eo(){const e=document.getElementById("welcome-template");if(!e)return;l.messages.innerHTML="",l.messages.appendChild(e.content.cloneNode(!0)),function(){const e=document.getElementById("chat-greeting");if(!e)return;const t=(new Date).getHours();e.textContent=t>=5&&t<12?"Good morning":t>=12&&t<17?"Good afternoon":t>=17&&t<22?"Good evening":"Working late?"}(),jn(),async function(){const e=document.getElementById("welcome-personal");if(!e)return;if(void 0===t||!t||"function"!=typeof t.chat)return;if(!(!0===de||l.modelSelect&&l.modelSelect.options&&l.modelSelect.options.length>1))return;const n=new Date,o=function(e){let t=null;try{t=JSON.parse(localStorage.getItem(zn)||"null")}catch{t=null}return t&&"string"==typeof t.text&&t.text?t.day!==Xn(e)?null:t.text:null}(n);if(o)return e.textContent=o,e.dataset.kind="ai",void(e.hidden=!1);const s=Kn(),a=l.classSelect&&l.classSelect.value?l.classSelect.value:"aegis",i=l.modelSelect&&l.modelSelect.value?l.modelSelect.value:"",r={class:a,prompt:Zn(s),maxTokens:Yn,tools:!1,singlePass:!0,effort:"low",bestEffort:!0};i&&(r.model=i);let c=null;try{c=await t.chat(r)}catch{return}const d=c&&c.choices&&c.choices[0]||{},u=function(e){let t,n=String(null==e?"":e).trim();if(!n)return"";n=n.replace(/^(assistant|greeting|response)\s*:\s*/i,"");do{t=n,n=n.replace(/^(?:sure|certainly|of course|absolutely|okay|ok|got it|no problem|here(?:'s| is)\b[^.!?:]*)\s*[.!?:,—–-]\s*/i,"")}while(n!==t&&n);const o=n.match(/^["'“”'']([\s\S]+)["'“”'']$/);o&&(n=o[1].trim()),n=n.replace(/\s+/g," ");const s=n.match(/^[\s\S]*?[.!?](?=\s|$)/);if(s&&(n=s[0].trim()),n.length>Jn){const e=n.slice(0,Jn),t=Math.max(e.lastIndexOf(". "),e.lastIndexOf("! "),e.lastIndexOf("? "));n=t>40?e.slice(0,t+1):`${e.replace(/[,;:\s]+$/,"")}…`}return n.length>=12?n:""}(d.message&&d.message.content||"");if(!u)return;const m=document.getElementById("welcome-personal");if(m){m.textContent=u,m.dataset.kind="ai",m.hidden=!1;try{localStorage.setItem(zn,JSON.stringify({day:Xn(n),text:u}))}catch{}}}();const n=document.getElementById("welcome-byok");n&&n.addEventListener("click",uo);const o=document.getElementById("welcome-cloud");o&&o.addEventListener("click",mo);const s=document.getElementById("welcome-dismiss");s&&s.addEventListener("click",fo),to(),Wn()}function to(){const e=document.getElementById("welcome-connect");if(!e)return;let t=!1;try{t="on"===localStorage.getItem(y)}catch{}const n=!0!==de,o=!0!==ue;e.hidden=t||!n&&!o,no("welcome-cloud",!n),no("welcome-cloud-note",!n),no("welcome-byok",!o),no("welcome-byok-note",!o)}function no(e,t){const n=document.getElementById(e);n&&(n.hidden=t)}function oo(e){if(!e)return;const t=e.closest("label")||e;let n=t.parentElement;for(;n;){const e=getComputedStyle(n).overflowY;if("auto"===e||"scroll"===e)break;n=n.parentElement}if(n){const e=n.querySelector(":scope > .settings-view-header"),o=e?e.offsetHeight:0,s=()=>t.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-o,a=()=>n.scrollTo({top:Math.max(0,s()),behavior:"smooth"});a();const i=Date.now()+3e3;let r=s();const c=()=>{const e=s();Math.abs(e-r)>=1&&(r=e,a()),Date.now()<i&&requestAnimationFrame(c)};requestAnimationFrame(c)}else try{t.scrollIntoView({block:"start",behavior:"smooth"})}catch{t.scrollIntoView()}t.classList.add("flash"),setTimeout((()=>t.classList.remove("flash")),1200)}let so=!1;function ao(){l.settingsView&&(l.settingsView.hidden=!1,l.settingsView.scrollTop=0),l.automationsView&&(l.automationsView.hidden=!0),l.chatCanvas&&(l.chatCanvas.hidden=!0),co(l.railSettings),xn({kind:"settings"}),function(){if(so)return;const t=l.avatarPaneMount;if(!t)return;const n="undefined"!=typeof window?window.AegisAvatarPane:null;if(!n||"function"!=typeof n.buildPane)return void(t.textContent="companion pane unavailable in this build");const o="function"==typeof e.personaRead?e.personaRead:null,s="function"==typeof e.personaPatch?e.personaPatch:null;if(!o||!s)return void(t.textContent="companion pane unavailable in this build");let a;try{a=o()}catch(e){return void(t.textContent=`could not read the persona: ${e&&e.message||e}`)}Promise.resolve(a).then((e=>{const o=e&&!1!==e.ok?e:null;let a;try{a=n.buildPane({doc:document,persona:o&&o.persona,capabilities:o&&o.capabilities,onPatch:e=>s(e)})}catch(e){return void(t.textContent=`could not build the pane: ${e&&e.message||e}`)}t.appendChild(a.root),so=!0,o&&Array.isArray(o.warnings)&&o.warnings.length?a.setStatus(`repaired — ${o.warnings.join("; ")}`):o||a.setStatus(e&&e.reason||"could not read the persona")}),(e=>{t.textContent=`could not read the persona: ${e&&e.message||e}`}))}()}function io(){l.automationsView&&(l.automationsView.hidden=!1,l.automationsView.scrollTop=0),l.settingsView&&(l.settingsView.hidden=!0),l.chatCanvas&&(l.chatCanvas.hidden=!0),co(l.railAutomations),xn({kind:"automations"})}function ro(){l.settingsView&&(l.settingsView.hidden=!0),l.automationsView&&(l.automationsView.hidden=!0),l.chatCanvas&&(l.chatCanvas.hidden=!1),co(null),xn({kind:"conversations"})}function co(e){for(const t of[l.railAutomations,l.railSettings]){if(!t)continue;const n=t===e;t.classList.toggle("is-active",n),n?t.setAttribute("aria-current","true"):t.removeAttribute("aria-current")}}function lo(e){if(!e)return;const t=e.closest("section.card")||e;try{t.scrollIntoView({block:"center",behavior:"smooth"})}catch{t.scrollIntoView()}t.classList.add("flash"),setTimeout((()=>t.classList.remove("flash")),1200)}async function uo(){if(po("byok"),Array.from(l.classSelect.options).some((e=>"byok"===e.value))&&"byok"!==l.classSelect.value&&(l.classSelect.value="byok",l.classSelect.dispatchEvent(new Event("change"))),ao(),lo(l.settingsList),!1===de&&l.apiKeyHint&&(l.apiKeyHint.textContent="BYOK needs an AEGIS key too — the handling fee is billed to it. Paste one above, then add your provider key below."),!1===de&&l.apiKeyInput)return l.apiKeyInput.focus(),void lo(l.apiKeyInput);const e=l.settingsList?l.settingsList.querySelector('.setting-row input[type="password"]'):null;e&&e.focus()}function mo(){po("cloud"),ao(),lo(l.apiKeyInput),l.apiKeyInput&&l.apiKeyInput.focus()}function po(e){const t=l.apiKeyHint;if(!t)return;t.textContent="","byok"===e?t.appendChild(document.createTextNode("Bring your own key: everything on this machine stays free, and a local model server needs no account at all. A key relayed through AEGIS is a cloud turn, so it bills a small handling fee — paste the AEGIS key here, then add the provider key in Provider settings. No key yet? ")):t.appendChild(document.createTextNode(`Connect AEGIS Cloud: ${x} Paste your AEGIS key, then Save. Free key at `));const n=document.createElement("a");n.href=w,n.target="_blank",n.rel="noreferrer noopener",n.textContent="aegiscloud.org",t.appendChild(n),t.appendChild(document.createTextNode("."))}function fo(){try{localStorage.setItem(y,"on")}catch{}const e=document.getElementById("welcome-connect");e&&(e.hidden=!0)}const ho="aegis.keysPopupDismissed";function yo(){const e=!0===de,t=!0===ue;l.keysAegisState&&(l.keysAegisState.textContent=e?"set":"not set"),l.keysByokState&&(l.keysByokState.textContent=t?"set":"not set"),l.keysRowAegis&&l.keysRowAegis.classList.toggle("set",e),l.keysRowByok&&l.keysRowByok.classList.toggle("set",t),l.keysCount&&(l.keysCount.textContent=(e?1:0)+(t?1:0)+" / 2"),l.keysAccount&&(l.keysAccount.hidden=!ye,l.keysAccount.textContent=ye?`The AEGIS account key could not be set up: ${ye}.`:""),l.keysAccountRetry&&(l.keysAccountRetry.hidden=!ye),l.keysHint&&(l.keysHint.textContent=e&&t?"Both keys are on this machine — both surfaces run.":`Missing: ${[e?null:"the AEGIS key",t?null:"your provider (BYOK) key"].filter(Boolean).join(" and ")}. Add it above, then both aegis one and the aegiscode CLI run.`)}function go(){l.keysOverlay&&(yo(),l.keysOverlay.hidden&&(xn({kind:"keys"}),l.keysOverlay.hidden=!1,document.body.classList.add("keys-open")))}function vo(){l.keysOverlay&&(l.keysOverlay.hidden=!0,document.body.classList.remove("keys-open"))}function Co(){try{localStorage.setItem(ho,"on")}catch{}vo()}function ko(e,t,n){"assistant"===t&&window.AegisMarkdown?(e.classList.add("md-body"),window.AegisMarkdown.renderInto(e,n)):(e.classList.remove("md-body"),e.textContent=n)}function bo(e,t,n,o,s){!function(){const e=document.getElementById("chat-welcome");e&&e.remove()}();const a=document.createElement("div");a.className=`msg ${e}`;const i=document.createElement("div");if(i.className="body",ko(i,e,t),Array.isArray(s)&&s.length){const e=document.createElement("div");e.className="tool-activity";for(const t of s){const n=document.createElement("div");n.textContent=Mo(t),e.appendChild(n)}a.appendChild(e)}if(a.appendChild(i),n){const e=document.createElement("div");e.className="meta",e.textContent=n,a.appendChild(e)}if("assistant"===e&&o){const e=document.createElement("button");e.type="button",e.className="copy-btn",e.textContent="copy",e.addEventListener("click",(()=>async function(e,t){try{await navigator.clipboard.writeText(e),t&&(t.textContent="copied!")}catch(e){t&&(t.textContent="copy failed")}finally{t&&setTimeout((()=>{t.textContent="copy"}),1500)}}(t,e))),a.appendChild(e)}return l.messages.appendChild(a),ee(),a}function wo(e,n,o){const s=document.createElement("article");s.className="flow-card pending",s.dataset.path=e.key;const a=document.createElement("div");a.className="flow-head";const i=document.createElement("span");i.className="flow-badge",i.textContent=e.badge;const r=document.createElement("span");r.className="flow-title",r.textContent=e.title;const c=document.createElement("span");c.className="flow-state",c.textContent="queued",a.appendChild(i),a.appendChild(r),a.appendChild(c);const l=document.createElement("div");l.className="flow-body",l.textContent="…";const d=document.createElement("div");d.className="flow-meta";const u=document.createElement("button");u.type="button",u.className="ghost-btn flow-abort",u.textContent="stop",u.addEventListener("click",(()=>{s.dataset.session&&t.cancel(s.dataset.session),c.textContent="stopped",s.classList.remove("pending"),s.classList.add("stopped"),u.remove()})),s.appendChild(a),s.appendChild(l),s.appendChild(d),s.appendChild(u);const m=n.querySelector(".flow-add");return m?n.insertBefore(s,m):n.appendChild(s),async function(e,n){const o=`${n.parentSessionId}::flow${++Q}`;e.dataset.session=o,W.add(o);const s=e.querySelector(".flow-body"),a=e.querySelector(".flow-state"),i=e.querySelector(".flow-meta");let r="";const c=t=>{if(t&&t.approval)return e.classList.contains("pending")&&(e.classList.remove("pending"),a.textContent="needs approval"),void Ho(e,t.approval,".flow-body");if(t&&t.tool)return e.classList.contains("pending")&&(e.classList.remove("pending"),a.textContent="streaming…"),"run"===t.tool.phase?void qo(t.tool):void Ao(e,t.tool,"flow-tools",".flow-body");const n=t&&("string"==typeof t.delta?t.delta:t.content);n&&(e.classList.contains("pending")&&(e.classList.remove("pending"),a.textContent="streaming…"),r+=n,s.textContent=r,function(e){return e.parentElement}(e)&&function(e){const t=e.nextElementSibling;return!t||t.classList.contains("flow-add")}(e)&&e.scrollIntoView({block:"nearest",inline:"end"}))};try{const l=await t.chat({class:n.cls,system:`${V}\n\n${n.path.hint}`,prompt:`Original request:\n${n.prompt}\n\n${n.path.hint}`,model:n.model,maxTokens:Math.min(n.maxTokens||1024,1024),tools:!1,singlePass:!0,sessionId:o,bestEffort:!0},c),d=l&&l.choices&&l.choices[0]||{};if(l&&l.bestEffortFailed)throw new Error(l.message||"the provider did not answer");if(l&&l.aborted){const e=new Error(l.message||"This operation was aborted");throw e.name="AbortError",e.code="ABORT_ERR",e}const u=d.message&&d.message.content||r||"(no path found)";ko(s,"assistant",u),e.classList.remove("pending"),e.classList.add("done"),a.textContent="done";const m=[n.path.title];l&&l.model?m.push(l.model):n.model&&m.push(n.model);const p=turnAccounting(l&&l.usage,n.model,{costUsd:l&&"number"==typeof l.costUsd?l.costUsd:void 0}),f=displayTokens(p);null!=f&&m.push(`${f} tokens`),null!=p.cost&&m.push(fmtCost(p.cost,p.real));const h=_(n.parentSessionId,l&&l.usage,{model:n.model,costUsd:l&&"number"==typeof l.costUsd?l.costUsd:void 0,calls:l&&l.calls,turns:0,prompt:`Original request:\n${n.prompt}\n\n${n.path.hint}`,reply:u}),y=fmtRoll(h);y&&m.push(`session: ${y}`),i.textContent=m.join(" · ")}catch(t){const o=t&&t.message?t.message:String(t);e.classList.remove("pending"),e.classList.add("stopped"),a.textContent="stopped",s.textContent=r||`Path unavailable: ${o}`,i.textContent=n.path.title}finally{W.delete(o);const t=e.querySelector(".flow-abort");t&&t.remove()}}(s,{...o,path:e}),s}function xo(){return R||(R=bo("assistant",""),R.classList.remove("pending"),R)}function So(e,{cancellable:t}={}){if(l.send.disabled=e,l.prompt.disabled=e,e){R=bo("assistant",""),R.classList.add("pending");const e=document.createElement("span");e.className="typing-dots";for(let t=0;t<3;t++)e.appendChild(document.createElement("span"));R.querySelector(".body").appendChild(e);const n=document.createElement("span");if(n.className="typing-tokens",n.hidden=!0,R.appendChild(n),t){const e=document.createElement("button");e.type="button",e.className="cancel-btn",e.textContent="cancel",e.addEventListener("click",(()=>ne())),R.appendChild(e)}}else R&&(R.remove(),R=null)}const Eo=72,$o=new Set(["editFile","writeFile","Edit","Write","MultiEdit"]),Lo=new Map;function qo(e){if(!e||!$o.has(e.name)||null==e.id)return;const t=e.cwd,n=editPreview(e.name,e.args,{cwd:t,readFile:e=>function(e,t){try{const n="undefined"!=typeof window?window.aegis:null;if(n&&"function"==typeof n.readTextFile)return n.readTextFile(e,t)}catch{}}(e,t)});n&&Lo.set(e.id,n)}function Mo(e){const{name:t,args:n}=e||{},o=toolMark(e),s=n||{};if("task"===t){const e=s.subagent_type&&"general"!==s.subagent_type?s.subagent_type:"general";return`→ task ▸ ${s.description||"subagent"} (${e}) ${o}`}const a=s.file_path||s.path||s.command||s.pattern||s.query||s.description||"",i=String(a).replace(/\s+/g," ").trim(),r=i.length>Eo?`${i.slice(0,Eo-1)}…`:i;return`→ ${t}${r?` ${r}`:""} ${o}`}function Ao(t,n,o,s){if(!t)return;let a=t.querySelector(`.${o}`);if(!a){a=document.createElement("div"),a.className=o;const e=s?t.querySelector(s):null;e?t.insertBefore(a,e):t.appendChild(a)}const i=n&&null!=n.id?Lo.get(n.id):null;if(i){Lo.delete(n.id);const t=renderDiffBlock(i,document);if(t)return a.appendChild(t),function(t,n){if(!t||!n||null==n.id||!1===n.ok)return;if("writeFile"!==n.name&&"editFile"!==n.name)return;if(!e||"function"!=typeof e.undoMutation)return;const o=document.createElement("div");o.className="diff-undo-row";const s=document.createElement("span");s.className="diff-undo-link",s.textContent="⎿ undo this edit",s.setAttribute("role","button"),s.tabIndex=0;const a=async()=>{s.removeEventListener("click",a),s.tabIndex=-1,s.textContent="⎿ undoing…";try{const t=await e.undoMutation(O,n.id);s.textContent=t&&t.ok?"⎿ "+("deleted"===t.restored?"undone — file deleted (it was new)":"undone — content restored"):`⎿ undo failed — ${t&&t.error||"unknown error"}`,s.className=t&&t.ok?"diff-undo-link diff-undo-done":"diff-undo-link diff-undo-failed"}catch(e){s.textContent=`⎿ undo failed — ${e&&e.message||e}`,s.className="diff-undo-link diff-undo-failed"}};s.addEventListener("click",a),s.addEventListener("keydown",(e=>{!e||"Enter"!==e.key&&" "!==e.key||("function"==typeof e.preventDefault&&e.preventDefault(),a())})),o.appendChild(s),t.appendChild(o)}(a,n),a}const r=document.createElement("div");return r.textContent=Mo(n),a.appendChild(r),a}function No(e){return e.startsWith("@@")?"diff-hunk":e.startsWith("+++")||e.startsWith("---")?"diff-file":e.startsWith("+")?"diff-add":e.startsWith("-")?"diff-del":"diff-ctx"}function Ho(e,n,o){if(!e||!n)return;const s=document.createElement("div");s.className="approval-card",s.dataset.approvalId=n.id;const a=document.createElement("div");a.className="approval-title",a.textContent=`${n.tool} wants to run — review before it executes`,s.appendChild(a);const i=function(e,t){const n=t||{};return"exec"===e?n.description?`${n.command} — ${n.description}`:n.command||"":n.file_path||""}(n.tool,n.args);if(i){const e=document.createElement("div");e.className="approval-summary",e.textContent=i,s.appendChild(e)}if(n.diff){const e=document.createElement("pre");e.className="approval-diff";for(const t of n.diff.split("\n")){const n=document.createElement("div");n.className=No(t),n.textContent=t,e.appendChild(n)}s.appendChild(e)}const r=document.createElement("div");r.className="approval-actions";const c=(e,o,a)=>{const i=document.createElement("button");return i.type="button",i.className=`approval-btn ${o}`,i.textContent=e,i.addEventListener("click",(()=>(e=>{for(const e of r.querySelectorAll("button"))e.disabled=!0;s.classList.add("resolved");const o=document.createElement("div");o.className="approval-decision",o.textContent="deny"===e?"Denied":"session"===e?"Allowed for this session":"always"===e?"Always allowed":"Allowed once",s.appendChild(o),t.respondApproval(n.id,e)})(a))),i};if(r.appendChild(c("Allow once","allow","once")),r.appendChild(c("Allow for this session","allow-session","session")),n.canPersist){const e=c("Always allow this command","allow-always","always");e.title="Stores a rule in ~/.aegiscode/permissions.json, shared with the terminal face",r.appendChild(e)}r.appendChild(c("Deny","deny","deny")),s.appendChild(r);let l=e.querySelector(".approval-slot");if(!l){l=document.createElement("div"),l.className="approval-slot";const t=o?e.querySelector(o):null;t?e.insertBefore(l,t):e.appendChild(l)}return l.appendChild(s),s}function Bo(){try{if(globalThis.crypto&&"function"==typeof globalThis.crypto.randomUUID)return globalThis.crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}async function Io(){try{D=await t.listClasses()||[]}catch(e){D=[],l.modelHint.textContent=`listClasses failed: ${e&&e.message?e.message:e}`}l.classSelect.innerHTML="";for(const e of D){const t=document.createElement("option");t.value=e.class,t.textContent=e.configured?e.label:`${e.label} (not configured)`,l.classSelect.appendChild(t)}const e=localStorage.getItem(d);e&&D.some((t=>t.class===e))&&(l.classSelect.value=e),await Ro(l.classSelect.value)}async function Ro(e){if(l.autonomousToggleWrap&&(l.autonomousToggleWrap.hidden=e!==g),se(),ie(e),l.modelSelect.hidden=!1,l.modelSelect.disabled=!1,l.modelFree.hidden=!0,l.modelFree.value="",l.modelHint.textContent="",l.modelSelect.innerHTML="",P=new Map,"aegis"===e){const e=document.createElement("option");e.value=i,e.textContent=r,l.modelSelect.appendChild(e)}try{const n=await t.listModels(e),o=Array.isArray(n&&n.models)?n.models:[],s=Boolean(n&&n.needsKey),a=Boolean(n&&n.needsDaemon),i=!(n&&!1===n.listed),r=Boolean(n&&n.providersFailed),c=Array.isArray(n&&n.unmatchedProviders)?n.unmatchedProviders:[];l.modelFree.hidden=!("local"===e&&(a||!i));for(const e of o){P.set(e.id,e);const t=document.createElement("option");t.value=e.id,t.textContent=e.label||e.id,l.modelSelect.appendChild(t)}let d;if(re(),s)d=null;else if(a)d=`No local model server at ${n&&n.baseURL||"the configured address"} — start Ollama, or set Base URL below to llama.cpp / LM Studio, then Refresh.`;else if("local"!==e||i)if("byok"===e&&r)d="Provider catalog unreachable — your saved keys and declared models are unaffected. Refresh to try again."+(n&&n.providersError?` (${n.providersError})`:"");else if(o.length)if("byok"===e&&n&&n.needsAegisKey){const e=n&&n.fee||null;d=`${o.length} model${1===o.length?"":"s"} available — `+(e&&e.require_balance?"an AEGIS account key and a funded balance are required: the BYOK handling fee is billed there.":"an AEGIS account key is required: the BYOK handling fee is billed there.")}else d="byok"===e&&n&&n.needsProviderKey?`${o.length} model${1===o.length?"":"s"} available — add a provider key in Provider settings below to use one.`:`${o.length} model${1===o.length?"":"s"} available.`;else d="local"===e?"No models on this server yet — pull one first (ollama pull llama3.2).":"aegis"===e?"No models to pin — this class runs the pooled route on the server's own default. Use Bring your own key for a per-provider model.":"No models listed.";else d="That address answered but listed no models — not Ollama? Type the model tag in the box above and send.";"byok"===e&&!r&&c.length&&(d=`${d} Not shown: ${c.join(", ")} — declared in models.json, but not in the provider catalog. Check the provider name in Settings.`);const u=maxTokensCeiling(P.get(ae()));if(s){l.modelHint.textContent="Connect Aegis Cloud to load its models: paste your AEGIS API key in the Status card above (";const e=document.createElement("a");return e.href=w,e.target="_blank",e.rel="noreferrer noopener",e.textContent="free key at aegiscloud.org",l.modelHint.appendChild(e),void l.modelHint.appendChild(document.createTextNode("), then Save."))}l.modelHint.textContent=u<FLAT_CEILING?`${d} · max output: ${u.toLocaleString()}`:d}catch(e){P=new Map,l.modelHint.textContent=`listModels failed: ${e&&e.message?e.message:e}`,re()}}function To(){if(l.queueModelInput&&!l.queueModelInput.hidden){const e=l.queueModelInput.value.trim();if(e)return e}return l.queueModelSelect?l.queueModelSelect.value:""}async function Oo(e){if(l.queueModelSelect){if(function(e){const t=l.queueFanout&&l.queueFanout.closest("label");t&&(t.hidden="aegis"!==e)}(e),l.queueModelSelect.hidden=!1,l.queueModelSelect.disabled=!1,l.queueModelInput&&(l.queueModelInput.hidden=!0,l.queueModelInput.value=""),l.queueModelField&&(l.queueModelField.hidden=!0),l.queueModelHint&&(l.queueModelHint.textContent=""),l.queueModelSelect.innerHTML="","aegis"===e){const e=document.createElement("option");e.value="",e.textContent="server default (auto)",l.queueModelSelect.appendChild(e)}try{const n=await t.listModels(e),o=Array.isArray(n&&n.models)?n.models:[],s=Boolean(n&&n.needsKey),a=Boolean(n&&n.needsDaemon),i=!(n&&!1===n.listed);l.queueModelInput&&(l.queueModelInput.hidden=!("local"===e&&(a||!i))),l.queueModelField&&(l.queueModelField.hidden=!("local"===e&&(a||!i)));for(const e of o){const t=document.createElement("option");t.value=e.id,t.textContent=e.label||e.id,l.queueModelSelect.appendChild(t)}if(!l.queueModelHint)return;s?l.queueModelHint.textContent="Connect this class in the Model card above (API key / provider key), then Refresh.":a?l.queueModelHint.textContent=`No local model server at ${n&&n.baseURL||"the configured address"} — start it, then reopen this picker.`:"local"!==e||i?o.length?"byok"===e&&n&&n.needsProviderKey&&(l.queueModelHint.textContent="A provider key is required before a queued task on this model can run — add one in the Model card above."):l.queueModelHint.textContent="local"===e?"No models on this server yet — pull one first (ollama pull llama3.2).":"aegis"===e?"No models to pin — this runs the pooled route on the server's own default.":"No models listed.":l.queueModelHint.textContent="That address answered but listed no models — type the model tag above."}catch(e){l.queueModelHint&&(l.queueModelHint.textContent=`listModels failed: ${e&&e.message?e.message:e}`)}}}function Fo({provider:e,name:t,cfg:n,onSave:o,onRemove:s}){const a=document.createElement("div");a.className="setting-row",a.dataset.provider=e;const i=document.createElement("div");i.className="setting-name",i.textContent=t,a.appendChild(i);const r=document.createElement("input");r.type="password",r.className="setting-input",r.placeholder=n.configured?`key ${n.keyMask} (blank = keep)`:"API key",a.appendChild(r);const c=document.createElement("div");c.className="setting-status",c.textContent=n.configured?`configured (${n.keyMask})`:"no key",c.dataset.state=n.configured?"configured":"unset",a.appendChild(c);const l=document.createElement("div");l.className="setting-actions";const d=document.createElement("button");d.type="button",d.className="ghost-btn btn-primary btn-sm",d.textContent="Save",d.addEventListener("click",(()=>o(r.value))),l.appendChild(d);const u=document.createElement("button");return u.type="button",u.className="ghost-btn danger",u.textContent="Remove",u.disabled=!n.configured,u.addEventListener("click",s),l.appendChild(u),a.appendChild(l),a}async function Do(e){l.settingsHint.textContent="saving…";try{const n=String(null==e?"":e).trim()||b,o=await t.settings.set(C,{baseURL:n}),s=o&&o.baseURL||n;l.settingsHint.textContent=`saved: local model server at ${s}`,await Po(),await Ro(l.classSelect.value)}catch(e){l.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function Po(){l.settingsList.innerHTML="";const e=[];let n=[];try{n=await t.settings.get()||[]}catch{}Array.isArray(n)&&(n=n.filter((e=>e&&!v.has(e.provider))));{const e=n.find((e=>e&&e.provider===C))||{provider:C,baseURL:"",configured:!1,keyMask:null};l.settingsList.appendChild(function(e){const t=C,n=document.createElement("div");n.className="setting-row",n.dataset.provider=t;const o=document.createElement("div");o.className="setting-name",o.textContent="Local model server",n.appendChild(o);const s=document.createElement("input");s.type="text",s.className="setting-input",s.id="local-base-url",s.autocomplete="off",s.spellcheck=!1,s.placeholder=b,s.value=e.baseURL||"",s.addEventListener("keydown",(e=>{"Enter"===e.key&&Do(s.value)})),n.appendChild(s);const a=document.createElement("div");a.className="setting-status",a.textContent=e.baseURL?e.baseURL:`default (${b})`,a.dataset.state=e.baseURL?"configured":"unset",n.appendChild(a);const i=document.createElement("div");i.className="setting-actions";const r=document.createElement("button");r.type="button",r.className="ghost-btn btn-primary btn-sm",r.textContent="Save",r.addEventListener("click",(()=>Do(s.value))),i.appendChild(r);const c=document.createElement("button");return c.type="button",c.className="ghost-btn danger",c.textContent="Reset",c.disabled=!e.baseURL,c.addEventListener("click",(()=>Vo(t))),i.appendChild(c),n.appendChild(i),n}(e))}try{const o=await t.listModels("byok"),s=Array.isArray(o&&o.providers)?o.providers:[];for(const t of s){if(!t||!t.id)continue;if(e.push({id:t.id,label:t.label||t.id}),t.id===k)continue;const o=`byok:${t.id}`,s=n.find((e=>e.provider===o))||{provider:o,baseURL:"",configured:!1,keyMask:null};l.settingsList.appendChild(Fo({provider:o,name:`BYOK: ${t.label||t.id}`,cfg:s,onSave:e=>jo(o,e),onRemove:()=>Vo(o)}))}const a=o&&o.fee;if(a&&!a.disabled&&(Number(a.in_usd_per_1k)>0||Number(a.out_usd_per_1k)>0)){const e=document.createElement("div");e.className="setting-row",e.id="byok-fee-note";const t=document.createElement("div");t.className="setting-name";const n=e=>`${Number(e).toFixed(4)}`;t.textContent=`BYOK handling fee: ${n(a.in_usd_per_1k)} / 1k in, ${n(a.out_usd_per_1k)} / 1k out — billed to your AEGIS account on top of your own provider bill. This is the published rate, not a personal quote — Unlimited subscribers pay no handling fee at all, and neither do users on the free 1-month Unlimited trial.`,e.appendChild(t),l.settingsList.appendChild(e)}}catch{}try{await async function(e){if(!l.settingsList||!t.userModels)return;const n=await t.userModels.get();if(!n)return;const o=n&&n.map||{},s=(e||[]).map((e=>e&&e.id||"")).filter(Boolean),a=document.createElement("div");a.id="user-models-block";const i=document.createElement("div");i.className="setting-name",i.textContent="Your own models (BYOK)",a.appendChild(i);const r=document.createElement("div");r.className="setting-row",r.dataset.provider="byok:__user-model-add";const c=document.createElement("input");if(c.type="text",c.className="setting-input",c.id="user-model-provider",c.placeholder="provider (deepseek)",c.autocomplete="off",c.spellcheck=!1,s.length){const e=document.createElement("datalist");e.id="user-model-providers";for(const t of s){const n=document.createElement("option");n.value=t,e.appendChild(n)}r.appendChild(e),c.setAttribute("list","user-model-providers")}r.appendChild(c);const d=document.createElement("input");d.type="text",d.className="setting-input",d.id="user-model-id",d.placeholder="model id (deepseek-v4.2-preview)",d.autocomplete="off",d.spellcheck=!1,r.appendChild(d);const u=document.createElement("div");u.className="setting-actions";const m=document.createElement("button");m.type="button",m.className="ghost-btn",m.id="user-model-add",m.textContent="Add model",m.addEventListener("click",(async()=>{const e=c.value.trim(),n=d.value.trim();l.settingsHint.textContent="adding…";try{const o=await t.userModels.add(e,n);l.settingsHint.textContent=o&&!1===o.added?`${o.provider}:${o.model} was already declared.`:`added ${o.provider}:${o.model} — /models and the picker now offer it.`,await Po(),await Ro(l.classSelect.value)}catch(e){l.settingsHint.textContent=`${e&&e.message?e.message:e}`}})),u.appendChild(m);const p=document.createElement("button");p.type="button",p.className="ghost-btn",p.id="user-model-discover",p.textContent="List from provider",u.appendChild(p);const f=document.createElement("div");f.className="setting-status",f.id="user-model-discovered",f.hidden=!0,p.addEventListener("click",(async()=>{const e=c.value.trim();if(!e)return void(l.settingsHint.textContent="type a provider id first (the CLI's /byok lists them).");if("function"!=typeof t.userModels.discover)return void(l.settingsHint.textContent="this build cannot ask a provider — type the model id.");let n;l.settingsHint.textContent=`asking ${e}…`,f.hidden=!0,f.textContent="";try{n=await t.userModels.discover(e)}catch(e){return void(l.settingsHint.textContent=`${e&&e.message?e.message:e}`)}if(!n||!n.ok)return void(l.settingsHint.textContent=`${e}: ${n&&n.error||"no answer"}`);l.settingsHint.textContent=`${n.provider} serves ${n.count} chat model id(s) — pick one and Add model, or add them all.`;const o=document.createElement("select");o.className="setting-input",o.id="user-model-discovered-list";for(const e of n.ids){const t=document.createElement("option");t.value=e,t.textContent=n.declared&&n.declared.includes(e)?`${e} — declared`:e,o.appendChild(t)}if(o.addEventListener("change",(()=>{d.value=o.value})),n.ids.length){d.value=n.ids[0],f.appendChild(o);const e=document.createElement("button");e.type="button",e.className="ghost-btn",e.id="user-model-add-all",e.textContent=`Add all ${n.count}`,e.addEventListener("click",(async()=>{l.settingsHint.textContent=`adding ${n.count}…`;try{const e=await t.userModels.addAll(n.provider,n.ids);l.settingsHint.textContent=`added ${e.added} of ${n.ids.length}`+(e.already&&e.already.length?` (${e.already.length} were already declared)`:"")+(e.failed&&e.failed.length?` — ${e.failed.length} refused`:"")+".",await Po(),await Ro(l.classSelect.value)}catch(e){l.settingsHint.textContent=`${e&&e.message?e.message:e}`}})),f.appendChild(e)}else f.textContent="the vendor answered with no chat models — type an id above.";if(n.others&&n.others.length){const e=document.createElement("div");e.textContent=`${n.others.length} non-chat id(s) left out: ${n.others.slice(0,6).join(", ")}`,f.appendChild(e)}f.hidden=!1})),r.appendChild(u),r.appendChild(f);const h=document.createElement("div");h.className="setting-status",h.id="user-model-hint",h.textContent=n.file?`saved in ${n.file} — the CLI reads the same file (/model-add)`:"saved beside your AEGIS config — the CLI reads the same file (/model-add)",r.appendChild(h),a.appendChild(r);const y=Object.keys(o).sort();for(const e of y)for(const n of o[e]){const o=document.createElement("div");o.className="setting-row",o.dataset.provider=`byok:${e}`;const i=document.createElement("div");i.className="setting-name",i.textContent=`${e} — ${n}`,o.appendChild(i);const r=document.createElement("div");r.className="setting-status",r.textContent=s.length&&!s.includes(e)?"no provider row for this id — /byok lists the ones the relay takes":"offered in the picker on this machine",o.appendChild(r);const c=document.createElement("div");c.className="setting-actions";const d=document.createElement("button");d.type="button",d.className="ghost-btn danger",d.textContent="Remove",d.addEventListener("click",(async()=>{l.settingsHint.textContent="removing…";try{const o=await t.userModels.remove(e,n);l.settingsHint.textContent=o&&!1===o.removed?`${e}:${n} was not declared.`:`removed ${e}:${n}.`,await Po(),await Ro(l.classSelect.value)}catch(e){l.settingsHint.textContent=`${e&&e.message?e.message:e}`}})),c.appendChild(d),o.appendChild(c),a.appendChild(o)}const g=n&&n.invalid||[];for(const e of g){const t=document.createElement("div");t.className="setting-row";const n=document.createElement("div");n.className="setting-name",n.textContent=`${e.provider||"models.json"}: ${null==e.model?"":String(e.model)}`.trim(),t.appendChild(n);const o=document.createElement("div");o.className="setting-status",o.textContent=`skipped — ${e.reason}`,t.appendChild(o),a.appendChild(t)}l.settingsList.appendChild(a)}(e)}catch(e){l.settingsHint.textContent=`your own models: ${e&&e.message?e.message:e}`}try{await Uo()}catch(e){l.customStatus&&(l.customStatus.textContent=`custom provider: ${e&&e.message?e.message:e}`)}}async function Uo(){if(!l.customBaseUrl)return;let e=null,n=[];try{const n=await t.settings.get()||[],o=(Array.isArray(n)?n:[]).find((e=>e&&e.provider===`byok:${k}`));o&&(e={baseURL:o.baseURL||"",configured:Boolean(o.configured),keyMask:o.keyMask})}catch{}try{const e=await t.userModels.get(),o=e&&e.map||{};n=Array.isArray(o[k])?o[k]:[]}catch{}!function(e,t){if(!l.customBaseUrl)return;const n=e||{},o=Array.isArray(t)?t:[];if(!l.customBaseUrl.value&&n.baseURL&&(l.customBaseUrl.value=n.baseURL),l.customKey&&(l.customKey.placeholder=n.configured?`key ${n.keyMask||"••••"} (blank = keep)`:"sk-…",l.customKey.value=""),l.customRemove&&(l.customRemove.disabled=!n.configured&&!n.baseURL),!l.customStatus)return;const s=[];n.baseURL?s.push(`endpoint ${n.baseURL}`):s.push("no endpoint saved"),s.push(n.configured?`key ${n.keyMask||"saved"}`:"no key"),s.push(o.length?`model${1===o.length?"":"s"} ${o.join(", ")}`:"no model declared"),l.customStatus.textContent=s.join(" · ")}(e,n)}async function _o(){if(!l.customBaseUrl)return;const e=String(l.customBaseUrl.value||"").trim(),n=l.customKey?String(l.customKey.value||"").trim():"",o=l.customModel?String(l.customModel.value||"").trim():"",s=e=>{l.customStatus&&(l.customStatus.textContent=e)};if(!e)return void s("an address is required — aegis1 dials the endpoint you name, and refuses a custom call that names none.");if(!/^https:\/\//i.test(e))return void s("refused: only an https:// endpoint is dialed — aegis1 rejects a plain-http or scheme-less base URL for this provider.");if(!o)return void s("a model id is required — the `custom` provider pins no default, so nothing would be selectable in the picker.");s("saving…");const a=`byok:${k}`;try{const o={};o.baseURL=e,n&&(o.key=n),await t.settings.set(a,o)}catch(e){return void s(`endpoint not saved: ${e&&e.message?e.message:e}`)}try{await t.userModels.add(k,o)}catch(e){return s(`endpoint saved, model NOT declared: ${e&&e.message?e.message:e}`),await Uo(),void await Ro(l.classSelect.value).catch((()=>{}))}l.customModel&&(l.customModel.value=""),s(`saved ${e} with model ${o} — pick it under provider "byok", then the model.`),await Uo(),await Po(),await Ro(l.classSelect.value).catch((()=>{}))}async function Ko(){if(!l.customBaseUrl)return;const e=e=>{l.customStatus&&(l.customStatus.textContent=e)};e("removing…");let n=0;try{const e=await t.userModels.get(),o=e&&e.map||{},s=Array.isArray(o[k])?o[k]:[];for(const e of s)await t.userModels.remove(k,e),n+=1}catch{}try{await t.settings.remove(`byok:${k}`)}catch(t){return void e(`remove failed: ${t&&t.message?t.message:t}`)}l.customBaseUrl&&(l.customBaseUrl.value=""),e(`removed the custom endpoint${n?` and ${n} declared model(s)`:""}.`),await Uo(),await Po(),await Ro(l.classSelect.value).catch((()=>{}))}async function jo(e,n){l.settingsHint.textContent="saving…";try{const o={};n&&(o.key=n),await t.settings.set(e,o),l.settingsHint.textContent="saved.",await Po(),await Ro(l.classSelect.value)}catch(e){l.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function Vo(e){l.settingsHint.textContent="removing…";try{await t.settings.remove(e),l.settingsHint.textContent="removed.",await Po(),await Ro(l.classSelect.value)}catch(e){l.settingsHint.textContent=`remove failed: ${e&&e.message?e.message:e}`}}const Go=["sessions","memory"];let Qo="sessions";function Wo(e){const t=Go.includes(e)?e:"sessions";Qo=t;for(const e of Go){const n="sessions"===e?l.paneSessions:l.paneMemory,o="sessions"===e?l.tabSessions:l.tabMemory,s=e===t;n&&(n.hidden=!s),o&&(o.setAttribute("aria-selected",s?"true":"false"),o.classList.toggle("is-active",s))}}const zo=new Set,Yo=3;function Jo(e){const t=(Array.isArray(e&&e.messages)?e.messages:[]).find((e=>e&&"user"===e.role&&e.content));return t&&t.content?String(t.content):e&&"string"==typeof e.firstPrompt?e.firstPrompt:""}function Xo(e){const t=Jo(e);return Boolean(t)&&function(e,t){const n=String(null==e?"":e).replace(/\s+/g," ").trim(),o=String(null==t?"":t).replace(/\s+/g," ").trim();if(!n||!o)return!1;const s=o.slice(0,60);return n===s||60===s.length&&n.length>=52&&s.startsWith(n)}(e&&e.title,t)}function Zo(e){if(!e||!e.id||zo.has(e.id))return;if(!0===e.named&&!Xo(e))return;const t=Jo(e);if(!t)return;if(zo.add(e.id),"function"!=typeof n.nameSession)return;const o=l.classSelect?l.classSelect.value:"";n.nameSession({sessionId:e.id,prompt:t,class:o,model:ae()}).then((e=>{e&&os().catch((()=>{}))})).catch((()=>{}))}let es=[],ts=null;const ns="undefined"!=typeof window&&window.aegisLibrary||null;async function os(){l.sessionsHint.textContent="";let e=[];try{const t=await n.listSessions();e=t&&t.sessions||[]}catch(e){return l.sessionsList.innerHTML="",void(l.sessionsHint.textContent=`list failed: ${e&&e.message?e.message:e}`)}es=e;let t=Yo;for(const n of e){if(t<=0)break;!n||!0===n.named&&!Xo(n)||zo.has(n.id)||(t-=1,Zo(n))}ss()}function ss(){if(!l.sessionsList)return;const e=l.sessionsFilter?l.sessionsFilter.value:"",t=es,n=ns?ns.filterSessions(e,t):t;if(l.sessionsCount&&(l.sessionsCount.textContent=ns?ns.countLabel(n.length,t.length):""),l.sessionsList.innerHTML="",!t.length)return void l.sessionsList.appendChild(is("no conversations yet"));if(!n.length)return void l.sessionsList.appendChild(is(`nothing matches “${String(e).trim()}”`));const o=Date.now(),s=ns?ns.groupSessions(n,o):[{key:"all",label:"",sessions:n}],a=n.length>as?as:1/0;let i=0,r=0;for(const e of s)if(i>=a)r+=e.sessions.length;else{if(e.label){const t=document.createElement("li");t.className="library-group",t.setAttribute("role","presentation"),t.textContent=e.label,l.sessionsList.appendChild(t)}for(const t of e.sessions)i>=a?r+=1:(l.sessionsList.appendChild(rs(t,o)),i+=1)}if(r>0){const e=document.createElement("li");e.className="empty library-more",e.textContent=`${r} more — type in the filter to narrow`,l.sessionsList.appendChild(e)}}const as=200;function is(e){const t=document.createElement("li");return t.className="empty",t.textContent=e,t}function rs(t,o){const s=document.createElement("li");if(s.className="session-row",s.tabIndex=0,s.dataset.sessionId=t&&t.id||"",t&&t.id&&t.id===O&&s.classList.add("is-current"),ts&&t&&t.id===ts)return s.classList.add("is-renaming"),s.appendChild(function(e){const t=document.createElement("input");return t.type="text",t.className="session-rename",t.value=e&&e.title||"",t.setAttribute("aria-label","New name for this conversation"),t.addEventListener("click",(e=>e.stopPropagation())),t.addEventListener("keydown",(o=>{o.stopPropagation(),"Enter"===o.key?(o.preventDefault(),async function(e,t){const o=String(null==t?"":t).trim();if(ts=null,!o||o===(e&&e.title||""))return void ss();if("function"!=typeof n.rename)return l.sessionsHint.textContent="rename is unavailable in this build.",void ss();const s=es.find((t=>t&&t.id===e.id));s&&(s.title=o,s.named=!0),ss();try{await n.rename(e.id,o),l.sessionsHint.textContent=`renamed to “${o}”`}catch(e){l.sessionsHint.textContent=`rename failed: ${e&&e.message?e.message:e}`}await os()}(e,t.value)):"Escape"===o.key&&(o.preventDefault(),ts=null,ss())})),t.addEventListener("blur",(()=>{ts===(e&&e.id)&&(ts=null,ss())})),setTimeout((()=>{try{t.focus(),t.select()}catch{}}),0),t}(t)),s;const a=document.createElement("span");a.className="session-title",a.textContent=ns?ns.sessionTitle(t):t&&t.title||t&&t.id||"untitled",s.appendChild(a);const i=document.createElement("span");i.className="session-meta",i.textContent=ns?ns.sessionMeta(t,o):"",s.appendChild(i);const r=document.createElement("span");r.className="session-actions";for(const[o,s,a]of[["Rename","Rename this conversation",()=>function(e){e&&e.id&&(ts=e.id,ss())}(t)],["Export","Save this conversation as Markdown",()=>async function(t){if(t&&t.id)if("function"==typeof e.exportSession)try{const n=await e.exportSession(t.id,"markdown");n&&n.ok?l.sessionsHint.textContent=`exported to ${n.filePath}`:n&&n.canceled?l.sessionsHint.textContent="":l.sessionsHint.textContent=`export failed: ${n&&n.reason||"unknown error"}`}catch(e){l.sessionsHint.textContent=`export failed: ${e&&e.message?e.message:e}`}else l.sessionsHint.textContent="export is unavailable in this build."}(t)],["Delete","Delete this conversation",()=>async function(e){if(!e||!e.id)return;const t=ns?ns.sessionTitle(e):e.title||e.id;if("function"!=typeof confirm||confirm(`Delete “${t}”?\n\nThis removes the conversation from this device. It cannot be undone.`)){try{await n.delete(e.id)}catch(e){return void(l.sessionsHint.textContent=`delete failed: ${e&&e.message?e.message:e}`)}O===e.id&&fs(),l.sessionsHint.textContent=`deleted “${t}”`,await os()}}(t)]]){const e=document.createElement("button");e.type="button",e.className="session-action",e.textContent=o,e.title=s,e.setAttribute("aria-label",`${s}`),e.addEventListener("click",(e=>{e.stopPropagation(),a()})),r.appendChild(e)}return s.appendChild(r),s.addEventListener("click",(()=>ms(t.id))),s.addEventListener("keydown",(e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),ms(t.id))})),s}function cs(e){if(!l.syncStatus)return;if(!e)return void(l.syncStatus.textContent="");const t=[e.cloud?"cloud sync on":"cloud sync off (no key)",`${e.pending} pending`];e.lastSyncAt&&t.push(`last synced ${new Date(e.lastSyncAt).toLocaleTimeString()}`),e.retry&&e.retry.lastError&&t.push(`last sync attempt failed: ${e.retry.lastError}`),l.syncStatus.textContent=t.join(" · ")}async function ls(){try{cs(await n.status())}catch{cs(null)}}function ds(){"function"==typeof n.auto&&n.auto().then((e=>{e&&e.upgrade&&wt(l.sessionsHint,e.upgrade,"queued memory is waiting on the free-plan cap","See what Pro covers →")})).catch((()=>{}))}async function us(){l.syncNow.disabled=!0,l.sessionsHint.textContent="syncing…";try{const e=await n.push(),t=await n.pull();e.upgrade||t.upgrade?wt(l.sessionsHint,e.upgrade||t.upgrade,"queued memory is waiting on the free-plan cap","See what Pro covers →"):e.ok||t.ok?l.sessionsHint.textContent=`synced (pushed ${e.pushed||0}, pulled ${t.merged||0})`:l.sessionsHint.textContent=`sync failed: ${e.reason||t.reason||"unknown error"}`}catch(e){l.sessionsHint.textContent=`sync failed: ${e&&e.message?e.message:e}`}finally{l.syncNow.disabled=!1,await ls(),await os()}}function ms(e,t){n.open(e).then((e=>{if(!e)return void(l.sessionsHint.textContent="session not found");l.messages.innerHTML="",t&&t.fromNav||xn({kind:"session",id:e.id});const n=Array.isArray(e.messages)?e.messages:[];n.length||eo();for(const t of n){const n="assistant"===t.role?"assistant":"system"===t.role?"system":"user";bo(n,t.content||t.text||"",void 0,"assistant"===n?e.id:void 0)}O=e.id,U.set(e.id,rollMessages(n)),K(e.id),F=replayHistory(n),l.sessionsHint.textContent=`opened ${e.id.slice(0,8)}…`})).catch((e=>{l.sessionsHint.textContent=`open failed: ${e&&e.message?e.message:e}`}))}function ps(t){const n=O;n?e.exportSession(n,t).then((e=>{e&&e.ok?l.sessionsHint.textContent=`exported to ${e.filePath}`:e&&e.canceled||(l.sessionsHint.textContent=`export failed: ${e&&e.reason||"unknown error"}`)})).catch((e=>{l.sessionsHint.textContent=`export failed: ${e&&e.message?e.message:e}`})):l.sessionsHint.textContent="no open session to export"}function fs(){z(),hn={query:"",matches:[],index:-1,texts:[]},l.findInput&&(l.findInput.value=""),Mn(),In(),O&&t.clearApprovals(O).catch((()=>{})),eo(),l.sessionsHint.textContent="",R=null,T=null,J=null,X=null,O=null,F=[],Q=0,K(null)}function hs(e){e&&("open"===e.action&&e.sessionId?ms(e.sessionId):"new"===e.action&&(fs(),e.prompt&&(l.prompt.value=e.prompt,l.prompt.focus())))}async function ys(){const e=l.prompt.value.trim(),o=Cs.length?Cs.map((e=>({kind:e.kind,path:e.path,name:e.name,size:e.size,mime:e.mime,dataUrl:e.dataUrl,text:e.text,truncated:e.truncated}))):void 0;if(!e&&!o||l.send.disabled)return;const s=l.classSelect.value,a=ae();l.prompt.value="";const i=(r=Cs,Array.isArray(r)&&r.length?r.map((e=>`📎 ${e.name||e.path}`)).join("\n"):"");var r;const c=i?e?`${e}\n${i}`:i:e;Cs=[],ks=[],xs();const d=++Y;J=d,X=null,bo("user",c);const u=s===g&&oe(),m=ce(),p=budgetFor(a,void 0,m),f=u&&parseInt(l.autonomousWorkers.value,10)||void 0;O||(O=Bo());const h=O;T=h,vo();const y=replayHistory(F);F.push({role:"user",content:o&&!ws()?Ms(e,o):c}),So(!0,{cancellable:!0}),R&&K(h,{prompt:e,reply:"",reasoning:""}),ee({force:!0});try{await n.append(h,{role:"user",content:c})}catch{}let v="",C="",k=0;const b=[];let w=null;const x=(S=()=>{if(!R)return;if(R.classList.remove("pending"),C){const e=function(e){let t=e.querySelector(".reasoning");if(!t){t=document.createElement("div"),t.className="reasoning";const n=e.querySelector(".body");n?e.insertBefore(t,n):e.appendChild(t)}return t}(R);e.textContent!==C&&(e.textContent=C)}const t=R.querySelector(".body");t&&t.textContent!==v&&(t.textContent=v);const n=v.length+C.length+4*k;liveMeterDue(w,n)&&(w=n,K(h,{prompt:e,reply:v,reasoning:C,measuredReasoningTokens:k})),ee()},Z?Z.paint(S):S);var S;const E=e=>{if(e&&"number"==typeof e.thinkingTokens&&e.thinkingTokens>0)return k+=e.thinkingTokens,void x();if(e&&"string"==typeof e.reasoning&&e.reasoning)return C+=e.reasoning,void x();if(e&&"string"==typeof e.note&&e.note){const t=xo();return t.classList.remove("pending"),function(e,t,n){if(!e||!t)return null;const o=document.createElement("div");o.className="turn-note",o.textContent=t;const s=n?e.querySelector(n):null;s?e.insertBefore(o,s):e.appendChild(o)}(t,e.note,".body"),void ee()}if(e&&e.approval){const t=xo();return t.classList.remove("pending"),Ho(t,e.approval,".body"),void ee({force:!0})}if(e&&e.rounds){const n=xo();return n.classList.remove("pending"),function(e,n,o){if(!e||!n||!n.id)return null;const s=Number(n.spent)||0,a=Number(n.size)||s,i=Number(n.extensions)||1,r=Number(n.max)||8,c=document.createElement("div");c.className="approval-card rounds-card",c.dataset.roundsAskId=n.id;const l=document.createElement("div");l.className="approval-title",l.textContent="Round limit reached — keep going?",c.appendChild(l);const d=document.createElement("div");d.className="approval-summary",d.textContent=`This turn has used all ${s} tool rounds allowed for it. ${a} more continue the SAME turn — no restart, no repeated work. Stopping holds everything done so far: your next message resumes it automatically. (${i} of ${r} extensions.)`,c.appendChild(d);const u=document.createElement("div");u.className="approval-actions";const m=(e,o,s)=>{const i=document.createElement("button");return i.type="button",i.className=`approval-btn ${o}`,i.textContent=e,i.addEventListener("click",(()=>(e=>{for(const e of u.querySelectorAll("button"))e.disabled=!0;c.classList.add("resolved");const o=document.createElement("div");o.className="approval-decision",o.textContent=e?`Continuing — ${a} more rounds`:"Stopped — the work is held",c.appendChild(o),t.respondRoundsAsk(n.id,e)})(s))),i};u.appendChild(m(`Keep going (${a} more rounds)`,"allow",!0)),u.appendChild(m("Stop here","deny",!1)),c.appendChild(u);let p=e.querySelector(".approval-slot");if(!p){p=document.createElement("div"),p.className="approval-slot";const t=o?e.querySelector(o):null;t?e.insertBefore(p,t):e.appendChild(p)}p.appendChild(c)}(n,e.rounds,".body"),void ee({force:!0})}if(e&&e.tool){if("run"===e.tool.phase)return void qo(e.tool);b.push(e.tool);const t=xo();return t.classList.remove("pending"),Ao(t,e.tool,"tool-activity",".body"),void ee()}const n=e&&("string"==typeof e.delta?e.delta:e.content);n&&(v+=n,x())};try{const i=await t.chat({class:s,prompt:e,model:a,maxTokens:p,sessionId:h,autonomous:u,effort:m,workers:f,messages:y,attachments:o,roundsAsk:!0},E);if(i&&i.aborted){const e=new Error(i.message||"This operation was aborted");throw e.name="AbortError",e.code="ABORT_ERR",e}const r=i&&i.choices&&i.choices[0]||{},c=r.message&&r.message.content||v||"(empty response)";isPlaceholderContent(c)||F.push({role:"assistant",content:c});const d=[];i&&i.model?d.push(`model: ${i.model}`):a&&d.push(`model: ${a}`),d.push(function(e){const t=D.find((t=>t.class===e));return t?t.label:e}(s)),u?d.push(`autonomous (${m}, ${f||"auto"}w)`):m&&d.push(`effort: ${m}`);const g=turnAccounting(i&&i.usage,a,{costUsd:i&&"number"==typeof i.costUsd?i.costUsd:void 0}),k=displayTokens(g);if(null!=k)d.push(`tokens: ${k}`);else{const t=estimatedBuckets(e,c,c===C?"":C);t&&t.output>0&&d.push(`~${t.output} tokens`)}const w=feeBillable(function(){const e="undefined"!=typeof state?state:null;return e&&e.entitlement?e.entitlement:null}());null!=g.cost&&w&&d.push(fmtCost(g.cost,g.real)),"byok"===s&&null!=g.cost&&w&&d.push("your provider bill (est.) + AEGIS handling fee");const x=_(h,i&&i.usage,{model:a,costUsd:i&&"number"==typeof i.costUsd?i.costUsd:void 0,calls:i&&i.calls,prompt:e,reply:c,reasoning:c===C?"":C}),S=fmtRoll(x,{omitMoney:!w});S&&d.push(`session: ${S}`),i&&i.pooled_notice&&d.push(i.pooled_notice),bo("assistant",c,d.join(" · ")||void 0,h,b);try{await n.append(h,{role:"assistant",content:c,...j(i&&i.usage,a,g,{prompt:e,reply:c,reasoning:c===C?"":C,calls:i&&i.calls})}),await n.save({id:h,title:e.slice(0,60)}),"function"==typeof n.nameSession&&n.nameSession({sessionId:h,prompt:e,class:s,model:a}).then((e=>{e&&os().catch((()=>{}))})).catch((()=>{}))}catch{}ds(),function(){const e=l.exploreToggle;return Boolean(e&&e.checked)}()&&"(empty response)"!==c&&function(e){const t=document.createElement("div");t.className="chatflow";const n=document.createElement("div");n.className="flow-rail";const o=document.createElement("span");o.className="flow-rail-label",o.textContent="discovery lane";const s=document.createElement("span");s.className="flow-rail-hint",s.textContent="alternatives from the AI — scroll →",n.appendChild(o),n.appendChild(s);const a=document.createElement("div");a.className="flow-track";const i=document.createElement("button");i.type="button",i.className="ghost-btn flow-add",i.textContent="+ another path",i.addEventListener("click",(()=>{wo(G[Q%G.length],a,e)})),a.appendChild(i),t.appendChild(n),t.appendChild(a),l.messages.appendChild(t);for(const t of G.slice(0,2))wo(t,a,e)}({prompt:e,cls:s,model:a,maxTokens:p,parentSessionId:h})}catch(t){if(isCancellation(t,{userStopped:X===d})){const t=salvageTurn({streamedText:v,reasoningText:C}),o=t.text,s=t.reasoning,i=replayableContent(t.kind,o);F.push({role:"assistant",content:i});const r=turnAccounting(void 0,a,{}),c=_(h,void 0,{model:a,prompt:e,reply:o,reasoning:s}),l=["stopped by you"];"reasoning-only"===t.kind&&l.push("reasoning only");const d=displayTokens(r);if(null!=d)l.push(`tokens: ${d}`);else{const t=estimatedBuckets(e,o,s);t&&t.output>0&&l.push(`~${t.output} tokens`)}const u=fmtRoll(c);u&&l.push(`session: ${u}`),bo("assistant",o,l.join(" · "),h,b);try{await n.append(h,{role:"assistant",content:i,...j(void 0,a,r,{prompt:e,reply:o,reasoning:s})})}catch{}ds()}else bo("assistant",`Error: ${t&&t.message?t.message:t}`,"request failed")}finally{So(!1),J===d&&(J=null,T=null),os()}}let gs=!1;function vs(){const e=l.messages;e&&(gs=!0,e.scrollTo({top:e.scrollHeight,behavior:"smooth"}),l.scrollBottom&&(l.scrollBottom.hidden=!0))}let Cs=[],ks=[],bs=0;function ws(){return l.classSelect&&"pro"===l.classSelect.value}function xs(){const e=l.attachRow,t=l.attachNote;if(!e)return;e.textContent="";const n=Cs.length+ks.length;if(e.hidden=0===n,t&&(t.hidden=!0,t.textContent=""),n){for(const t of Cs){const n=document.createElement("span");if(n.className="attach-chip",n.title=t.path||"","image"===t.kind&&t.dataUrl){const e=document.createElement("img");e.className="attach-thumb",e.src=t.dataUrl,e.alt="",n.appendChild(e)}const o=document.createElement("span");o.className="attach-kind",o.textContent="image"===t.kind?"img":"text"===t.kind?"txt":t.kind,n.appendChild(o);const s=document.createElement("span");s.className="attach-name",s.textContent=`${t.name||t.path} · ${Es(t.size)}${t.truncated?" (truncated)":""}`,n.appendChild(s),n.appendChild(Ss((()=>{Cs=Cs.filter((e=>e!==t)),xs()}))),e.appendChild(n)}for(const t of ks){const n=document.createElement("span");n.className="attach-chip is-refused",n.title=t.reason||"";const o=document.createElement("span");o.className="attach-name",o.textContent=`${t.name||t.path} — ${t.reason||"not attached"}`,n.appendChild(o),n.appendChild(Ss((()=>{ks=ks.filter((e=>e!==t)),xs()}))),e.appendChild(n)}if(t&&ws()){const e=Cs.filter((e=>"image"===e.kind)).length;e&&(t.hidden=!1,t.textContent=1===e?"This provider runs text-only, so the picture travels as its file path.":`This provider runs text-only, so the ${e} pictures travel as file paths.`)}}}function Ss(e){const t=document.createElement("button");return t.type="button",t.className="attach-remove",t.title="Remove",t.setAttribute("aria-label","Remove attachment"),t.textContent="×",t.addEventListener("click",e),t}function Es(e){const t=Number(e)||0;return t<1024?`${t} B`:t<1048576?`${Math.round(t/1024)} KB`:`${(t/1048576).toFixed(1)} MB`}async function $s(t){const n=(t||"").split(/[\\/]/).pop()||t;if(Cs.length>=8)return ks.push({path:t,name:n,reason:"at most 8 files per message"}),void xs();let o;try{o=await e.attachments.ingest(t)}catch(e){o={ok:!1,reason:e&&e.message||"could not read file"}}if(!o||!0!==o.ok||!o.attachment)return ks.push({path:t,name:n,reason:o&&o.reason||"not attached"}),void xs();Cs.some((e=>e.path===o.attachment.path))||(Cs.push(o.attachment),xs())}const Ls=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function qs(e){if(e&&"string"==typeof e.mime&&e.mime)return e.mime;const t=e&&"string"==typeof e.dataUrl?e.dataUrl:"",n=/^data:([^;,]+)[;,]/.exec(t);return n?n[1].toLowerCase():""}function Ms(e,t){const n=[],o="string"==typeof e?e:"";o.trim()&&n.push({type:"text",text:o});for(const e of t||[]){const t=qs(e);"image"===e.kind&&e.dataUrl&&Ls.has(t)?n.push({type:"image_url",image_url:{url:e.dataUrl}}):"image"===e.kind?n.push({type:"text",text:e.path?`[attached image, not inline (${t||"unknown image type"}): ${e.path}]`:`[attached image, not inline (${t||"unknown image type"})]`}):"text"===e.kind&&"string"==typeof e.text?n.push({type:"text",text:`--- ${e.name} ---\n${e.text}`}):e.path&&n.push({type:"text",text:`[attached file: ${e.path}]`})}return 1===n.length&&"text"===n[0].type?n[0].text:n.length?n:o}const As="aegis.onboardingSeen";async function Ns(){!function(){const t=document.getElementById("onboard-overlay");if(!t)return;let n=!1;try{n="1"===localStorage.getItem(As)}catch{}if(n)return;t.hidden=!1;const o=document.getElementById("onboard-status"),s=document.getElementById("onboard-google"),a=document.getElementById("onboard-apikey"),i=document.getElementById("onboard-skip"),r=(e,t)=>{o&&(o.textContent=e||"",o.classList.toggle("is-err","err"===t),o.classList.toggle("is-ok","ok"===t))},c=()=>{try{localStorage.setItem(As,"1")}catch{}t.classList.add("is-leaving"),setTimeout((()=>{t.hidden=!0}),250)};s&&s.addEventListener("click",(async()=>{s.disabled=!0,a&&(a.disabled=!0),r("Opening a browser to sign in with Google…");try{const t=await e.driveSignIn();if(t&&t.ok)return r(t.username?`Signed in as ${t.username}`:"Signed in","ok"),void setTimeout(c,500);r(t&&t.error||"Sign-in did not complete.","err")}catch(e){r(e&&e.message||"Sign-in failed.","err")}s.disabled=!1,a&&(a.disabled=!1)})),a&&a.addEventListener("click",(()=>{c(),ao();const e=document.getElementById("api-key-input");e&&e.focus()})),i&&i.addEventListener("click",c)}();try{me(await e.status())}catch{me(null)}"on"===localStorage.getItem(m)&&(l.autonomousToggle.checked=!0),l.autonomousToggle.addEventListener("change",(()=>{localStorage.setItem(m,l.autonomousToggle.checked?"on":"off"),se()}));const n=localStorage.getItem(p)||localStorage.getItem("aegis.autonomousEffort"),i=Array.from(l.effortSelect.options).some((e=>e.value===n));n&&i?l.effortSelect.value=n:n&&localStorage.setItem(p,l.effortSelect.value),l.effortSelect.addEventListener("change",(()=>{localStorage.setItem(p,l.effortSelect.value),ie(l.classSelect.value)}));const r=localStorage.getItem(f);r&&(l.autonomousWorkers.value=r),l.autonomousWorkers.addEventListener("change",(()=>{localStorage.setItem(f,l.autonomousWorkers.value)})),se();const c=localStorage.getItem(h);l.exploreToggle.checked="on"===c,l.exploreToggle.addEventListener("change",(()=>{localStorage.setItem(h,l.exploreToggle.checked?"on":"off"),l.exploreToggle.checked||z()})),l.classSelect.addEventListener("change",(()=>{localStorage.setItem(d,l.classSelect.value),ie(l.classSelect.value),Ro(l.classSelect.value)})),l.modelSelect.addEventListener("change",(()=>{const e=P.get(l.modelSelect.value),t=maxTokensCeiling(e),n=l.modelHint.textContent.replace(/ · max output: [\d,]+$/,"");l.modelHint.textContent=t<FLAT_CEILING?`${n} · max output: ${t.toLocaleString()}`:n,ie(l.classSelect.value),"byok"===l.classSelect.value&&e&&e.provider&&!1===e.configured&&function(e){if(!l.settingsList||!e)return;const t=l.settingsList.querySelector(`.setting-row[data-provider="byok:${e}"] input[type="password"]`);if(ao(),lo(l.settingsList),t&&t.focus(),l.modelHint){const t=l.modelHint.textContent.replace(/ — no .* key saved; add it below\.$/,"");l.modelHint.textContent=`${t} — no ${e} key saved; add it below.`}}(e.provider)})),l.modelFree.addEventListener("input",(()=>{ie(l.classSelect.value)})),l.newChat.addEventListener("click",fs),l.railAutomations&&l.railAutomations.addEventListener("click",(async()=>{await Promise.all([Ze().catch((()=>{})),je().catch((()=>{}))]),io()})),l.automationsBack&&l.automationsBack.addEventListener("click",ro),l.railSettings&&l.railSettings.addEventListener("click",ao),l.settingsBack&&l.settingsBack.addEventListener("click",ro),l.settingsJump&&l.settingsJump.addEventListener("click",(e=>{const t=e.target.closest(".settings-jump-link");if(!t)return;const n=document.getElementById(t.dataset.jump);n&&oo(n)})),l.importSessionBtn&&l.importSessionBtn.addEventListener("click",Qt),l.openCliFace&&l.openCliFace.addEventListener("click",(async()=>{if(e.openCliFace)try{const t=await e.openCliFace();t&&t.ok?le(!0,`opened ${t.emulator||"a terminal"}`):le(!1,t&&t.reason||"could not open a terminal")}catch(e){le(!1,`terminal face failed: ${e&&e.message||e}`)}else le(!1,"terminal face unavailable in this build")})),l.importClose&&l.importClose.addEventListener("click",Vt),l.importBackdrop&&l.importBackdrop.addEventListener("click",Vt),l.importSessionsBtn&&l.importSessionsBtn.addEventListener("click",Wt),l.importMemoryBtn&&l.importMemoryBtn.addEventListener("click",(()=>async function(t){if(!e.memoryImport)return;const n=t&&t.hint||l.memoryHint;l.importMemoryBtn&&(l.importMemoryBtn.disabled=!0),n.textContent="scanning for other AI tool memory…";try{const t=await e.memoryImport({confirm:!1});if(!t||!t.totals||!t.totals.entries)return void(n.textContent=t&&t.summary?t.summary:"nothing found.");const o=(t.sources||[]).filter((e=>e.present&&e.count>0)).map((e=>`${e.label}: ${e.count}`)).join(" · ");n.textContent=`importing ${t.totals.entries} entries — ${o}`;const s=await e.memoryImport({confirm:!0,limit:1e3});if(s&&s.upgrade)return wt(n,s.upgrade,`import stopped after ${s.saved||0} entries`),void await _n();const a=s&&s.queued?` (${s.queued} queued offline)`:"";n.textContent=s&&s.ok?`imported ${s.saved} entries${a}.`:`import stopped: ${s&&s.reason||"unknown error"}`,await _n()}catch(e){n.textContent=`import failed: ${e&&e.message?e.message:e}`}finally{l.importMemoryBtn&&(l.importMemoryBtn.disabled=!1)}}({hint:l.importHint}))),e.onMenuNewChat&&e.onMenuNewChat(fs),e.onMenuSearch&&e.onMenuSearch((()=>Pt(""))),e.onMenuSearchMemory&&e.onMenuSearchMemory(Ut),
5
+ function zt(){return!!l.creditsOverlay&&!l.creditsOverlay.hidden}function Yt(e,t){const n=document.createElement("section");n.className="credits-section";const o=document.createElement("h3");o.textContent=e,n.appendChild(o);const s=document.createElement("ul");s.className="credits-rows";for(const e of t){const t=document.createElement("li");t.className="credits-row";const n=document.createElement("span");n.className="credits-name",n.textContent=e.name||"",t.appendChild(n);const o=document.createElement("span");if(o.className="credits-meta",o.textContent=[e.version,e.licence,e.copyright].filter(Boolean).join(" · "),t.appendChild(o),e.url){const n=document.createElement("a");n.href=e.url,n.textContent=e.url.replace(/^https?:\/\//,""),n.target="_blank",n.rel="noopener noreferrer",t.appendChild(n)}s.appendChild(t)}return n.appendChild(s),n}function Jt(e){if(!l.creditsBody)return;l.creditsBody.innerHTML="";const t=e&&"object"==typeof e?e:{},n=t.program||{};l.creditsLicenceTag&&(l.creditsLicenceTag.textContent=n.licence||"");const o=document.createElement("section");o.className="credits-section";const s=document.createElement("h3");s.textContent="This program",o.appendChild(s);const a=document.createElement("p");if(a.className="credits-line",a.textContent=`${n.name||"AGPL"} — ${n.licence||""}`,o.appendChild(a),n.copyright){const e=document.createElement("p");e.className="credits-line",e.textContent=n.copyright,o.appendChild(e)}if(n.url){const e=document.createElement("p");e.className="credits-line";const t=document.createElement("a");t.href=n.url,t.textContent="Full licence text",t.target="_blank",t.rel="noopener noreferrer",e.appendChild(t),o.appendChild(e)}if(n.source){const e=document.createElement("p");e.className="credits-line";const t=document.createElement("a");t.href=n.source,t.textContent="Corresponding source",t.target="_blank",t.rel="noopener noreferrer",e.appendChild(t),o.appendChild(e)}if(n.notice){const e=document.createElement("pre");e.className="credits-notice",e.textContent=n.notice,o.appendChild(e)}if(l.creditsBody.appendChild(o),Array.isArray(t.code)&&t.code.length&&l.creditsBody.appendChild(Yt("Vendored third-party code",t.code)),Array.isArray(t.fonts)&&t.fonts.length&&l.creditsBody.appendChild(Yt("Vendored webfonts",t.fonts)),Array.isArray(t.missing)&&t.missing.length){const e=document.createElement("p");e.className="hint",e.textContent=`Could not read: ${t.missing.join(", ")} — the in-app attribution list may be incomplete.`,l.creditsBody.appendChild(e)}}function Xt(){l.creditsOverlay&&(xn({kind:"credits"}),l.creditsOverlay.hidden=!1,document.body.classList.add("memory-open"),async function(){if(!l.creditsBody)return;if(l.creditsStatus&&(l.creditsStatus.textContent="loading…"),!e||"function"!=typeof e.credits)return Jt(null),void(l.creditsStatus&&(l.creditsStatus.textContent=""));let t=null;try{t=await e.credits()}catch(e){return void(l.creditsStatus&&(l.creditsStatus.textContent=`could not read the licence files: ${e&&e.message||e}`))}l.creditsStatus&&(l.creditsStatus.textContent=""),Jt(t)}())}function Zt(){l.creditsOverlay&&(l.creditsOverlay.hidden=!0,document.body.classList.remove("memory-open"))}function en(){return!!l.shortcutsOverlay&&!l.shortcutsOverlay.hidden}function tn(){l.shortcutsOverlay&&(xn({kind:"shortcuts"}),function(){if(!l.shortcutsBody)return;const e=window.aegisShortcuts,t=window.aegis&&window.aegis.platform||navigator.platform||"";if(l.shortcutsBody.textContent="",!e||!Array.isArray(e.SHORTCUTS)){const e=document.createElement("p");return e.className="hint",e.textContent="The shortcut table failed to load (renderer/shortcuts.js).",void l.shortcutsBody.appendChild(e)}let n=0;for(const o of e.groups()){const s=e.rowsFor(o),a=document.createElement("section");a.className="shortcuts-section";const i=document.createElement("h3");i.className="shortcuts-group",i.textContent=o,a.appendChild(i);const r=document.createElement("div");r.className="keys-rows";for(const o of s){n+=1;const s=document.createElement("div");s.className="keys-row";const a=document.createElement("span");a.className="keys-state shortcuts-chord",a.textContent=e.platformize(o.chord,t);const i=document.createElement("div");i.className="keys-body";const c=document.createElement("b");c.textContent=o.label,i.appendChild(c);const l=o.note||o.where;if(l&&i.appendChild(document.createTextNode(` — ${l}`)),o.hidden){const e=document.createElement("span");e.className="hint shortcuts-hidden-note",e.textContent=" Not in the menu; the chord still works.",i.appendChild(e)}s.appendChild(a),s.appendChild(i),r.appendChild(s)}a.appendChild(r),l.shortcutsBody.appendChild(a)}l.shortcutsCount&&(l.shortcutsCount.textContent=`${n} chord${1===n?"":"s"}`)}(),l.shortcutsOverlay.hidden=!1,document.body.classList.add("memory-open"))}function nn(){l.shortcutsOverlay&&(l.shortcutsOverlay.hidden=!0,document.body.classList.remove("memory-open"))}let on=[],sn=-1;function an(){return{cliFace:void 0!==e&&e&&"function"==typeof e.openCliFace}}function rn(){return globalThis.AegisPaletteFilter||null}function cn(){return!!l.paletteOverlay&&!l.paletteOverlay.hidden}function ln(e){if(!l.paletteList)return;const t=rn(),n=function(){const e=globalThis.AegisCommands;return e&&Array.isArray(e.COMMANDS)?e.availableCommands(e.COMMANDS,an()):[]}();on=t?t.filterCommands(n,e):n.slice(),sn=t?t.initialIndex(on):on.length?0:-1,l.paletteList.replaceChildren();for(let e=0;e<on.length;e+=1){const t=on[e],n=document.createElement("li");n.className="palette-row"+(e===sn?" is-active":""),n.id=`palette-row-${e}`,n.setAttribute("role","option"),n.setAttribute("aria-selected",e===sn?"true":"false"),n.dataset.index=String(e);const o=document.createElement("span");if(o.className="palette-row-label",o.textContent=t.label,n.appendChild(o),t.hint){const e=document.createElement("span");e.className="palette-row-hint",e.textContent=t.hint,n.appendChild(e)}n.addEventListener("mousedown",(n=>{n.preventDefault(),sn=e,Pn(t.action)})),l.paletteList.appendChild(n)}l.paletteEmpty&&(l.paletteEmpty.hidden=on.length>0),dn()}function dn(){if(!l.paletteList)return;const e=l.paletteList.children;for(let t=0;t<e.length;t+=1){const n=t===sn;e[t].classList.toggle("is-active",n),e[t].setAttribute("aria-selected",n?"true":"false")}l.paletteInput&&(sn>=0?l.paletteInput.setAttribute("aria-activedescendant",`palette-row-${sn}`):l.paletteInput.removeAttribute("aria-activedescendant"));const t=e[sn];t&&"function"==typeof t.scrollIntoView&&t.scrollIntoView({block:"nearest"})}function un(e){const t=rn();t&&(sn=t.moveIndex(sn,on.length,e),dn())}function mn(){l.paletteOverlay&&(l.paletteOverlay.hidden=!1,document.body.classList.add("memory-open"),l.paletteInput&&(l.paletteInput.value="",l.paletteInput.focus()),ln(""))}function pn(){l.paletteOverlay&&(l.paletteOverlay.hidden=!0,document.body.classList.remove("memory-open"),on=[],sn=-1)}function fn(){if(!l.side)return;const e=l.side.classList.toggle("is-collapsed");l.side.setAttribute("aria-hidden",e?"true":"false")}let hn={query:"",matches:[],index:-1,texts:[]},yn=AegisNavHistory.createHistory(),gn=!1;function vn(){return globalThis.AegisFindInConversation||null}function Cn(){const e="undefined"!=typeof CSS&&CSS.highlights?CSS.highlights:null;if(!e)return;e.delete("find-match"),e.delete("find-match-current");const t=[],n=[];for(let e=0;e<hn.matches.length;e+=1){const o=hn.matches[e],s=hn.texts[o.textIndex];if(!s)continue;const a=document.createRange();a.setStart(s,o.start),a.setEnd(s,o.end),t.push(a),e===hn.index&&n.push(a)}t.length&&e.set("find-match",new Highlight(...t)),n.length&&e.set("find-match-current",new Highlight(...n))}function kn(e){const t=vn();if(!t)return;hn.texts=function(){const e=l.messages;if(!e||"function"!=typeof document.createTreeWalker)return[];const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null),n=[];let o=t.nextNode();for(;o;)o.nodeValue&&o.nodeValue.trim()&&n.push(o),o=t.nextNode();return n}();const n=hn.texts.map((e=>e.nodeValue||""));hn.matches=t.findMatches(n,hn.query,{caseSensitive:!1}),hn.index=hn.matches.length?0:-1,Cn(),l.findCount&&(l.findCount.textContent=t.matchLabel(hn.index,hn.matches.length)),e&&bn()}function bn(){const e=hn.matches[hn.index];if(!e)return;const t=hn.texts[e.textIndex];if(!t)return;const n=t.parentElement;n&&"function"==typeof n.scrollIntoView&&n.scrollIntoView({block:"center",behavior:"smooth"})}function wn(){return!!l.findBar&&!l.findBar.hidden}function xn(e){gn||(yn=AegisNavHistory.pushEntry(yn,e),Sn())}function Sn(){e.setNavState&&e.setNavState({back:AegisNavHistory.canGoBack(yn),forward:AegisNavHistory.canGoForward(yn)}).catch((()=>{}))}function En(e){if(e){gn=!0;try{!function(){for(const e of[l.memoryOverlay,l.creditsOverlay,l.shortcutsOverlay,l.keysOverlay])e&&(e.hidden=!0);document.body.classList.remove("memory-open","keys-open")}(),"settings"===e.kind?ao():"automations"===e.kind?io():"session"===e.kind&&e.id?ms(e.id,{fromNav:!0}):"memory"===e.kind?Nt():"credits"===e.kind?Xt():"shortcuts"===e.kind?tn():"keys"===e.kind?go():ro()}finally{gn=!1}}}function $n(){const e=AegisNavHistory.back(yn);e?(yn=e.state,En(e.entry),Sn()):l.sessionsHint.textContent="already at the start of the history"}function Ln(){const e=AegisNavHistory.forward(yn);e?(yn=e.state,En(e.entry),Sn()):l.sessionsHint.textContent="already at the newest place"}function qn(){l.findBar&&(l.findBar.hidden=!1,l.findInput&&(l.findInput.focus(),"function"==typeof l.findInput.select&&l.findInput.select()),hn.query&&kn(!0))}function Mn(){l.findBar&&(l.findBar.hidden=!0,"undefined"!=typeof CSS&&CSS.highlights&&(CSS.highlights.delete("find-match"),CSS.highlights.delete("find-match-current")),l.prompt&&"function"==typeof l.prompt.focus&&l.prompt.focus())}let An={kind:"",rows:[],index:-1,span:null,query:""};function Nn(){return globalThis.AegisComposerTriggers||null}function Hn(){return!!l.composerMenu&&!l.composerMenu.hidden}const Bn=new Set(["exportJson","toggleSidebar","keys","credits","find"]);function In(){An={kind:"",rows:[],index:-1,span:null,query:""},l.composerMenu&&(l.composerMenu.hidden=!0),l.composerMenuHint&&(l.composerMenuHint.hidden=!0),l.composerMenuList&&l.composerMenuList.replaceChildren()}function Rn(){if(!l.composerMenuList)return;l.composerMenuList.replaceChildren();const e=An.rows;for(let t=0;t<e.length;t+=1){const n=e[t],o=document.createElement("li");o.className="composer-menu-row"+(t===An.index?" is-active":""),o.id=`composer-row-${t}`,o.setAttribute("role","option"),o.setAttribute("aria-selected",t===An.index?"true":"false"),o.dataset.index=String(t);const s=document.createElement("span");if(s.className="composer-menu-label",s.textContent=n.label,o.appendChild(s),n.hint){const e=document.createElement("span");e.className="composer-menu-hint-text",e.textContent=n.hint,o.appendChild(e)}o.addEventListener("mousedown",(e=>{e.preventDefault(),An.index=t,On()})),l.composerMenuList.appendChild(o)}const t=l.composerMenuList.children[An.index];if(t&&"function"==typeof t.scrollIntoView&&t.scrollIntoView({block:"nearest"}),l.composerMenu&&(l.composerMenu.hidden=0===e.length),l.composerMenuHint){const t=0===e.length;l.composerMenuHint.hidden=!t,t&&(l.composerMenuHint.textContent="mention"===An.kind?An.query?`nothing matches “${An.query}”`:"no sessions or memories to mention yet":"no command matches")}e.length&&function(){if(!l.composerMenu)return;const e=l.composer||l.prompt&&l.prompt.parentElement;if(!e)return;const t=e.getBoundingClientRect(),n=l.composerMenu.offsetHeight||0;l.composerMenu.style.left=`${Math.round(t.left)}px`,l.composerMenu.style.width=`${Math.round(t.width)}px`,l.composerMenu.style.top=`${Math.round(t.top-n-6)}px`}()}async function Tn(){const e=Nn(),t=l.prompt;if(!e||!t)return;const o=e.activeTrigger(t.value,t.selectionStart);if(!o)return void(Hn()&&In());const s={start:o.start,end:o.end};let a;if(An.kind=o.kind,An.span=s,An.query=o.query,"slash"===o.kind)a=e.rankRows(function(){const e=globalThis.AegisCommands;return e&&Array.isArray(e.COMMANDS)?e.availableCommands(e.COMMANDS,an()).filter((e=>!Bn.has(e.action))).map((e=>({label:`/${e.label}`,hint:e.hint||"",keywords:e.keywords||"",action:e.action,row:"command"}))):[]}(),o.query);else{a=e.rankRows(await async function(e){if(!n||"function"!=typeof n.searchSessions)return[];let t=null;try{t=await n.searchSessions(e,8)}catch(e){return[]}const o=[],s=Array.isArray(t&&t.memory)?t.memory:[];for(const e of s){const t=String(e&&e.content||"").replace(/\s+/g," ").trim();t&&o.push({label:t.length>72?`${t.slice(0,71)}…`:t,hint:e.scope?`memory · ${e.scope}`:"memory",keywords:Array.isArray(e.tags)?e.tags.join(" "):"",action:"stageMemory",row:"memory",memory:e})}const a=Array.isArray(t&&t.sessions)?t.sessions:[];for(const e of a){const t=String(e&&e.title||"").trim()||"(untitled)";o.push({label:t,hint:"session · open",keywords:"",action:"openSessionRow",row:"session",session:e})}return o}(o.query),o.query);const i=e.activeTrigger(t.value,t.selectionStart);if(!i||"mention"!==i.kind||i.start!==s.start)return}An.rows=a,An.index=a.length?0:-1,Rn()}async function On(){const e=An.rows[An.index],t=l.prompt;if(!e||!t)return void In();const n=An.span,o=An.kind,s=t.value,a=Math.max(0,Math.min(n?n.start:s.length,s.length)),i=Math.max(a,Math.min(n?n.end:s.length,s.length)),r=s.slice(i);if("slash"===o)return t.value=(s.slice(0,a)+r).replace(/\s{2,}/g," ").trimStart(),In(),void Pn(e.action);if(In(),"openSessionRow"===e.action&&e.session)return t.value=(s.slice(0,a)+r).replace(/\s{2,}/g," ").trimStart(),void ms(e.session.id);if("stageMemory"===e.action&&e.memory){const n=e.memory,o=String(n.content||"");Cs.some((e=>"text"===e.kind&&e.text===o))||(Cs.push({kind:"text",name:n.scope?`memory: ${n.scope}`:"memory",path:"",size:o.length,mime:"text/plain",text:o,truncated:!1}),xs());const i=n.scope?`@${n.scope}`:"@memory";t.value=s.slice(0,a)+i+r;const c=a+i.length;t.setSelectionRange(c,c),t.focus()}}function Fn(e){const t=Nn();t&&An.rows.length&&(An.index=t.stepRow(An.rows.length,An.index,e),Rn())}function Dn(e){const t=vn();t&&hn.matches.length&&(hn.index=t.stepMatch(hn.index,hn.matches.length,e),Cn(),l.findCount&&(l.findCount.textContent=t.matchLabel(hn.index,hn.matches.length)),bn())}function Pn(e){switch(pn(),e){case"newChat":return void fs();case"go-back":return void $n();case"go-forward":return void Ln();case"search":return void Pt("");case"find":return void qn();case"settings":return void ao();case"customizations":return ao(),void oo(l.confirmMode);case"automations":return void Promise.all([Ze().catch((()=>{})),je().catch((()=>{}))]).then((()=>io()));case"cli":return void(l.openCliFace&&l.openCliFace.click());case"import":return void(l.importSessionBtn&&l.importSessionBtn.click());case"exportMarkdown":return void ps("markdown");case"exportJson":return void ps("json");case"memory":return void Nt();case"fingerprint":return void(dt&&"function"==typeof dt.open&&dt.open());case"shortcuts":return void tn();case"keys":return void go();case"credits":return void Xt();case"toggleSidebar":return void fn();default:throw new Error(`palette: unknown action ${e}`)}}async function Un(){const t=ct()&&l.memoryOverlayEntry?l.memoryOverlayEntry:l.memoryEntry;if(!t)return;const n=t.value.trim();if(n){l.memorySaveBtn.disabled=!0,l.memoryOverlaySave&&(l.memoryOverlaySave.disabled=!0),l.memoryHint.textContent="saving…";try{const o=await e.memorySave({text:n,source:"aegis-desktop"});if(o&&o.upgrade)return xt(o.upgrade,"free plan limit reached"),void await _n();t.value="",l.memoryHint.textContent=o&&o.queued?"saved offline — syncs when AEGIS is reachable.":"saved.",await _n()}catch(e){l.memoryHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{l.memorySaveBtn.disabled=!1,l.memoryOverlaySave&&(l.memoryOverlaySave.disabled=!1)}}}async function _n(){const e=l.memoryQuery?l.memoryQuery.value.trim():"";await St(e),ct()&&await At(it.query)}function Kn(){const e=yt();return void 0===e.keyConfigured&&delete e.keyConfigured,e}function jn(){const e=document.getElementById("welcome-personal");if(!e)return;const t=function(e){const t=window.aegisCompanion;if(!t||"function"!=typeof t.pickMessage)return null;const n=t.pickMessage(Kn(),new Date);return n&&n.text?{text:n.text,kind:n.kind||"tip"}:null}();if(!t)return e.textContent="",void(e.hidden=!0);e.textContent=t.text,e.dataset.kind=t.kind,e.hidden=!1}const Vn="aegis.welcomeRowsDismissed";function Gn(){const e=window.aegisWelcomeRows;if(!e)return[];try{return e.parseDismissed(localStorage.getItem(Vn))}catch{return[]}}function Qn(e){const t=document.createElement("div");t.className="welcome-row",t.dataset.rowId=e.id;const n=document.createElement("button");n.type="button",n.className="welcome-row-go";const o=document.createElement("span");if(o.className="welcome-row-label",o.textContent=e.label,n.appendChild(o),e.hint){const t=document.createElement("span");t.className="welcome-row-hint",t.textContent=e.hint,n.appendChild(t)}n.addEventListener("click",(()=>function(e){switch(e){case"update":l.updateRestartBtn&&l.updateRestartBtn.click();break;case"sessions":Pt("");break;case"memory":Nt();break;case"cli":l.openCliFace&&l.openCliFace.click()}}(e.action))),t.appendChild(n);const s=document.createElement("button");return s.type="button",s.className="welcome-row-x",s.setAttribute("aria-label",`Dismiss: ${e.label}`),s.textContent="✕",s.addEventListener("click",(()=>function(e){const t=window.aegisWelcomeRows;if(t){try{localStorage.setItem(Vn,t.withDismissed(Gn(),e))}catch{}Wn()}}(e.id))),t.appendChild(s),t}function Wn(){const t=document.getElementById("welcome-rows"),n=window.aegisWelcomeRows;if(!t||!n)return;const o=n.pickRows(function(){const t=Kn();return es.length&&(t.sessionCount=es.length),void 0!==e&&e&&"function"==typeof e.openCliFace&&(t.cliAvailable=!0),t}(),Gn());if(t.innerHTML="",o.length){for(const e of o)t.appendChild(Qn(e));t.hidden=!1}else t.hidden=!0}const zn="aegis.welcomeAiLine",Yn=120,Jn=200;function Xn(e){const t=e instanceof Date?e:new Date(null==e?Date.now():e);if(Number.isNaN(t.getTime()))return"";const n=e=>String(e).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}`}function Zn(e){const t=(new Date).getHours(),n=t>=5&&t<12?"morning":t>=12&&t<17?"afternoon":t>=17&&t<22?"evening":"late night",o=[];return"number"==typeof e.memoryCount&&o.push(`${e.memoryCount} entries saved in the user's memory`),"number"==typeof e.modelCount&&o.push(`${e.modelCount} models available`),"string"==typeof e.updatePending&&o.push(`update ${e.updatePending} is downloaded and installs on quit`),!0===e.keyConfigured&&o.push("the account key is connected"),!1===e.keyConfigured&&o.push("no account key is connected yet"),["Write the one sentence shown at the top of a coding assistant's empty",`chat panel. It is ${n} for the person reading it.`,o.length?`What you know about their setup: ${o.join("; ")}.`:"","Rules: one sentence, at most 25 words, second person, no greeting cliché",'like "Welcome back", no exclamation marks, no quotes, no preamble, no',"markdown. Say something specific and useful about their work right now, or","ask one short question that helps them start. Reply with the sentence only."].filter(Boolean).join(" ")}function eo(){const e=document.getElementById("welcome-template");if(!e)return;l.messages.innerHTML="",l.messages.appendChild(e.content.cloneNode(!0)),function(){const e=document.getElementById("chat-greeting");if(!e)return;const t=(new Date).getHours();e.textContent=t>=5&&t<12?"Good morning":t>=12&&t<17?"Good afternoon":t>=17&&t<22?"Good evening":"Working late?"}(),jn(),async function(){const e=document.getElementById("welcome-personal");if(!e)return;if(void 0===t||!t||"function"!=typeof t.chat)return;if(!(!0===de||l.modelSelect&&l.modelSelect.options&&l.modelSelect.options.length>1))return;const n=new Date,o=function(e){let t=null;try{t=JSON.parse(localStorage.getItem(zn)||"null")}catch{t=null}return t&&"string"==typeof t.text&&t.text?t.day!==Xn(e)?null:t.text:null}(n);if(o)return e.textContent=o,e.dataset.kind="ai",void(e.hidden=!1);const s=Kn(),a=l.classSelect&&l.classSelect.value?l.classSelect.value:"aegis",i=l.modelSelect&&l.modelSelect.value?l.modelSelect.value:"",r={class:a,prompt:Zn(s),maxTokens:Yn,tools:!1,singlePass:!0,effort:"low",bestEffort:!0};i&&(r.model=i);let c=null;try{c=await t.chat(r)}catch{return}const d=c&&c.choices&&c.choices[0]||{},u=function(e){let t,n=String(null==e?"":e).trim();if(!n)return"";n=n.replace(/^(assistant|greeting|response)\s*:\s*/i,"");do{t=n,n=n.replace(/^(?:sure|certainly|of course|absolutely|okay|ok|got it|no problem|here(?:'s| is)\b[^.!?:]*)\s*[.!?:,—–-]\s*/i,"")}while(n!==t&&n);const o=n.match(/^["'“”'']([\s\S]+)["'“”'']$/);o&&(n=o[1].trim()),n=n.replace(/\s+/g," ");const s=n.match(/^[\s\S]*?[.!?](?=\s|$)/);if(s&&(n=s[0].trim()),n.length>Jn){const e=n.slice(0,Jn),t=Math.max(e.lastIndexOf(". "),e.lastIndexOf("! "),e.lastIndexOf("? "));n=t>40?e.slice(0,t+1):`${e.replace(/[,;:\s]+$/,"")}…`}return n.length>=12?n:""}(d.message&&d.message.content||"");if(!u)return;const m=document.getElementById("welcome-personal");if(m){m.textContent=u,m.dataset.kind="ai",m.hidden=!1;try{localStorage.setItem(zn,JSON.stringify({day:Xn(n),text:u}))}catch{}}}();const n=document.getElementById("welcome-byok");n&&n.addEventListener("click",uo);const o=document.getElementById("welcome-cloud");o&&o.addEventListener("click",mo);const s=document.getElementById("welcome-dismiss");s&&s.addEventListener("click",fo),to(),Wn()}function to(){const e=document.getElementById("welcome-connect");if(!e)return;let t=!1;try{t="on"===localStorage.getItem(y)}catch{}const n=!0!==de,o=!0!==ue;e.hidden=t||!n&&!o,no("welcome-cloud",!n),no("welcome-cloud-note",!n),no("welcome-byok",!o),no("welcome-byok-note",!o)}function no(e,t){const n=document.getElementById(e);n&&(n.hidden=t)}function oo(e){if(!e)return;const t=e.closest("label")||e;let n=t.parentElement;for(;n;){const e=getComputedStyle(n).overflowY;if("auto"===e||"scroll"===e)break;n=n.parentElement}if(n){const e=n.querySelector(":scope > .settings-view-header"),o=e?e.offsetHeight:0,s=()=>t.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-o,a=()=>n.scrollTo({top:Math.max(0,s()),behavior:"smooth"});a();const i=Date.now()+3e3;let r=s();const c=()=>{const e=s();Math.abs(e-r)>=1&&(r=e,a()),Date.now()<i&&requestAnimationFrame(c)};requestAnimationFrame(c)}else try{t.scrollIntoView({block:"start",behavior:"smooth"})}catch{t.scrollIntoView()}t.classList.add("flash"),setTimeout((()=>t.classList.remove("flash")),1200)}let so=!1;function ao(){l.settingsView&&(l.settingsView.hidden=!1,l.settingsView.scrollTop=0),l.automationsView&&(l.automationsView.hidden=!0),l.chatCanvas&&(l.chatCanvas.hidden=!0),co(l.railSettings),xn({kind:"settings"}),function(){if(so)return;const t=l.avatarPaneMount;if(!t)return;const n="undefined"!=typeof window?window.AegisAvatarPane:null;if(!n||"function"!=typeof n.buildPane)return void(t.textContent="companion pane unavailable in this build");const o="function"==typeof e.personaRead?e.personaRead:null,s="function"==typeof e.personaPatch?e.personaPatch:null;if(!o||!s)return void(t.textContent="companion pane unavailable in this build");let a;try{a=o()}catch(e){return void(t.textContent=`could not read the persona: ${e&&e.message||e}`)}Promise.resolve(a).then((e=>{const o=e&&!1!==e.ok?e:null;let a;try{a=n.buildPane({doc:document,persona:o&&o.persona,capabilities:o&&o.capabilities,onPatch:e=>s(e)})}catch(e){return void(t.textContent=`could not build the pane: ${e&&e.message||e}`)}t.appendChild(a.root),so=!0,o&&Array.isArray(o.warnings)&&o.warnings.length?a.setStatus(`repaired — ${o.warnings.join("; ")}`):o||a.setStatus(e&&e.reason||"could not read the persona")}),(e=>{t.textContent=`could not read the persona: ${e&&e.message||e}`}))}()}function io(){l.automationsView&&(l.automationsView.hidden=!1,l.automationsView.scrollTop=0),l.settingsView&&(l.settingsView.hidden=!0),l.chatCanvas&&(l.chatCanvas.hidden=!0),co(l.railAutomations),xn({kind:"automations"})}function ro(){l.settingsView&&(l.settingsView.hidden=!0),l.automationsView&&(l.automationsView.hidden=!0),l.chatCanvas&&(l.chatCanvas.hidden=!1),co(null),xn({kind:"conversations"})}function co(e){for(const t of[l.railAutomations,l.railSettings]){if(!t)continue;const n=t===e;t.classList.toggle("is-active",n),n?t.setAttribute("aria-current","true"):t.removeAttribute("aria-current")}}function lo(e){if(!e)return;const t=e.closest("section.card")||e;try{t.scrollIntoView({block:"center",behavior:"smooth"})}catch{t.scrollIntoView()}t.classList.add("flash"),setTimeout((()=>t.classList.remove("flash")),1200)}async function uo(){if(po("byok"),Array.from(l.classSelect.options).some((e=>"byok"===e.value))&&"byok"!==l.classSelect.value&&(l.classSelect.value="byok",l.classSelect.dispatchEvent(new Event("change"))),ao(),lo(l.settingsList),!1===de&&l.apiKeyHint&&(l.apiKeyHint.textContent="BYOK needs an AEGIS key too — the handling fee is billed to it. Paste one above, then add your provider key below."),!1===de&&l.apiKeyInput)return l.apiKeyInput.focus(),void lo(l.apiKeyInput);const e=l.settingsList?l.settingsList.querySelector('.setting-row input[type="password"]'):null;e&&e.focus()}function mo(){po("cloud"),ao(),lo(l.apiKeyInput),l.apiKeyInput&&l.apiKeyInput.focus()}function po(e){const t=l.apiKeyHint;if(!t)return;t.textContent="","byok"===e?t.appendChild(document.createTextNode("Bring your own key: everything on this machine stays free, and a local model server needs no account at all. A key relayed through AEGIS is a cloud turn, so it bills a small handling fee — paste the AEGIS key here, then add the provider key in Provider settings. No key yet? ")):t.appendChild(document.createTextNode(`Connect AEGIS Cloud: ${x} Paste your AEGIS key, then Save. Free key at `));const n=document.createElement("a");n.href=w,n.target="_blank",n.rel="noreferrer noopener",n.textContent="aegiscloud.org",t.appendChild(n),t.appendChild(document.createTextNode("."))}function fo(){try{localStorage.setItem(y,"on")}catch{}const e=document.getElementById("welcome-connect");e&&(e.hidden=!0)}const ho="aegis.keysPopupDismissed";function yo(){const e=!0===de,t=!0===ue;l.keysAegisState&&(l.keysAegisState.textContent=e?"set":"not set"),l.keysByokState&&(l.keysByokState.textContent=t?"set":"not set"),l.keysRowAegis&&l.keysRowAegis.classList.toggle("set",e),l.keysRowByok&&l.keysRowByok.classList.toggle("set",t),l.keysCount&&(l.keysCount.textContent=(e?1:0)+(t?1:0)+" / 2"),l.keysAccount&&(l.keysAccount.hidden=!ye,l.keysAccount.textContent=ye?`The AEGIS account key could not be set up: ${ye}.`:""),l.keysAccountRetry&&(l.keysAccountRetry.hidden=!ye),l.keysHint&&(l.keysHint.textContent=e&&t?"Both keys are on this machine — both surfaces run.":`Missing: ${[e?null:"the AEGIS key",t?null:"your provider (BYOK) key"].filter(Boolean).join(" and ")}. Add it above, then both aegis one and the aegiscode CLI run.`)}function go(){l.keysOverlay&&(yo(),l.keysOverlay.hidden&&(xn({kind:"keys"}),l.keysOverlay.hidden=!1,document.body.classList.add("keys-open")))}function vo(){l.keysOverlay&&(l.keysOverlay.hidden=!0,document.body.classList.remove("keys-open"))}function Co(){try{localStorage.setItem(ho,"on")}catch{}vo()}function ko(e,t,n){"assistant"===t&&window.AegisMarkdown?(e.classList.add("md-body"),window.AegisMarkdown.renderInto(e,n)):(e.classList.remove("md-body"),e.textContent=n)}function bo(e,t,n,o,s){!function(){const e=document.getElementById("chat-welcome");e&&e.remove()}();const a=document.createElement("div");a.className=`msg ${e}`;const i=document.createElement("div");if(i.className="body",ko(i,e,t),Array.isArray(s)&&s.length){const e=document.createElement("div");e.className="tool-activity";for(const t of s){const n=document.createElement("div");n.textContent=Mo(t),e.appendChild(n)}a.appendChild(e)}if(a.appendChild(i),n){const e=document.createElement("div");e.className="meta",e.textContent=n,a.appendChild(e)}if("assistant"===e&&o){const e=document.createElement("button");e.type="button",e.className="copy-btn",e.textContent="copy",e.addEventListener("click",(()=>async function(e,t){try{await navigator.clipboard.writeText(e),t&&(t.textContent="copied!")}catch(e){t&&(t.textContent="copy failed")}finally{t&&setTimeout((()=>{t.textContent="copy"}),1500)}}(t,e))),a.appendChild(e)}return l.messages.appendChild(a),ee(),a}function wo(e,n,o){const s=document.createElement("article");s.className="flow-card pending",s.dataset.path=e.key;const a=document.createElement("div");a.className="flow-head";const i=document.createElement("span");i.className="flow-badge",i.textContent=e.badge;const r=document.createElement("span");r.className="flow-title",r.textContent=e.title;const c=document.createElement("span");c.className="flow-state",c.textContent="queued",a.appendChild(i),a.appendChild(r),a.appendChild(c);const l=document.createElement("div");l.className="flow-body",l.textContent="…";const d=document.createElement("div");d.className="flow-meta";const u=document.createElement("button");u.type="button",u.className="ghost-btn flow-abort",u.textContent="stop",u.addEventListener("click",(()=>{s.dataset.session&&t.cancel(s.dataset.session),c.textContent="stopped",s.classList.remove("pending"),s.classList.add("stopped"),u.remove()})),s.appendChild(a),s.appendChild(l),s.appendChild(d),s.appendChild(u);const m=n.querySelector(".flow-add");return m?n.insertBefore(s,m):n.appendChild(s),async function(e,n){const o=`${n.parentSessionId}::flow${++Q}`;e.dataset.session=o,W.add(o);const s=e.querySelector(".flow-body"),a=e.querySelector(".flow-state"),i=e.querySelector(".flow-meta");let r="";const c=t=>{if(t&&t.approval)return e.classList.contains("pending")&&(e.classList.remove("pending"),a.textContent="needs approval"),void Ho(e,t.approval,".flow-body");if(t&&t.tool)return e.classList.contains("pending")&&(e.classList.remove("pending"),a.textContent="streaming…"),"run"===t.tool.phase?void qo(t.tool):void Ao(e,t.tool,"flow-tools",".flow-body");const n=t&&("string"==typeof t.delta?t.delta:t.content);n&&(e.classList.contains("pending")&&(e.classList.remove("pending"),a.textContent="streaming…"),r+=n,s.textContent=r,function(e){return e.parentElement}(e)&&function(e){const t=e.nextElementSibling;return!t||t.classList.contains("flow-add")}(e)&&e.scrollIntoView({block:"nearest",inline:"end"}))};try{const l=await t.chat({class:n.cls,system:`${V}\n\n${n.path.hint}`,prompt:`Original request:\n${n.prompt}\n\n${n.path.hint}`,model:n.model,maxTokens:Math.min(n.maxTokens||1024,1024),tools:!1,singlePass:!0,sessionId:o,bestEffort:!0},c),d=l&&l.choices&&l.choices[0]||{};if(l&&l.bestEffortFailed)throw new Error(l.message||"the provider did not answer");if(l&&l.aborted){const e=new Error(l.message||"This operation was aborted");throw e.name="AbortError",e.code="ABORT_ERR",e}const u=d.message&&d.message.content||r||"(no path found)";ko(s,"assistant",u),e.classList.remove("pending"),e.classList.add("done"),a.textContent="done";const m=[n.path.title];l&&l.model?m.push(l.model):n.model&&m.push(n.model);const p=turnAccounting(l&&l.usage,n.model,{costUsd:l&&"number"==typeof l.costUsd?l.costUsd:void 0}),f=displayTokens(p);null!=f&&m.push(`${f} tokens`),null!=p.cost&&m.push(fmtCost(p.cost,p.real));const h=_(n.parentSessionId,l&&l.usage,{model:n.model,costUsd:l&&"number"==typeof l.costUsd?l.costUsd:void 0,calls:l&&l.calls,turns:0,prompt:`Original request:\n${n.prompt}\n\n${n.path.hint}`,reply:u}),y=fmtRoll(h);y&&m.push(`session: ${y}`),i.textContent=m.join(" · ")}catch(t){const o=t&&t.message?t.message:String(t);e.classList.remove("pending"),e.classList.add("stopped"),a.textContent="stopped",s.textContent=r||`Path unavailable: ${o}`,i.textContent=n.path.title}finally{W.delete(o);const t=e.querySelector(".flow-abort");t&&t.remove()}}(s,{...o,path:e}),s}function xo(){return R||(R=bo("assistant",""),R.classList.remove("pending"),R)}function So(e,{cancellable:t}={}){if(l.send.disabled=e,l.prompt.disabled=e,e){R=bo("assistant",""),R.classList.add("pending");const e=document.createElement("span");e.className="typing-dots";for(let t=0;t<3;t++)e.appendChild(document.createElement("span"));R.querySelector(".body").appendChild(e);const n=document.createElement("span");if(n.className="typing-tokens",n.hidden=!0,R.appendChild(n),t){const e=document.createElement("button");e.type="button",e.className="cancel-btn",e.textContent="cancel",e.addEventListener("click",(()=>ne())),R.appendChild(e)}}else R&&(R.remove(),R=null)}const Eo=72,$o=new Set(["editFile","writeFile","Edit","Write","MultiEdit"]),Lo=new Map;function qo(e){if(!e||!$o.has(e.name)||null==e.id)return;const t=e.cwd,n=editPreview(e.name,e.args,{cwd:t,readFile:e=>function(e,t){try{const n="undefined"!=typeof window?window.aegis:null;if(n&&"function"==typeof n.readTextFile)return n.readTextFile(e,t)}catch{}}(e,t)});n&&Lo.set(e.id,n)}function Mo(e){const{name:t,args:n}=e||{},o=toolMark(e),s=n||{};if("task"===t){const e=s.subagent_type&&"general"!==s.subagent_type?s.subagent_type:"general";return`→ task ▸ ${s.description||"subagent"} (${e}) ${o}`}const a=s.file_path||s.path||s.command||s.pattern||s.query||s.description||"",i=String(a).replace(/\s+/g," ").trim(),r=i.length>Eo?`${i.slice(0,Eo-1)}…`:i;return`→ ${t}${r?` ${r}`:""} ${o}`}function Ao(t,n,o,s){if(!t)return;let a=t.querySelector(`.${o}`);if(!a){a=document.createElement("div"),a.className=o;const e=s?t.querySelector(s):null;e?t.insertBefore(a,e):t.appendChild(a)}const i=n&&null!=n.id?Lo.get(n.id):null;if(i){Lo.delete(n.id);const t=renderDiffBlock(i,document);if(t)return a.appendChild(t),function(t,n){if(!t||!n||null==n.id||!1===n.ok)return;if("writeFile"!==n.name&&"editFile"!==n.name)return;if(!e||"function"!=typeof e.undoMutation)return;const o=document.createElement("div");o.className="diff-undo-row";const s=document.createElement("span");s.className="diff-undo-link",s.textContent="⎿ undo this edit",s.setAttribute("role","button"),s.tabIndex=0;const a=async()=>{s.removeEventListener("click",a),s.tabIndex=-1,s.textContent="⎿ undoing…";try{const t=await e.undoMutation(O,n.id);s.textContent=t&&t.ok?"⎿ "+("deleted"===t.restored?"undone — file deleted (it was new)":"undone — content restored"):`⎿ undo failed — ${t&&t.error||"unknown error"}`,s.className=t&&t.ok?"diff-undo-link diff-undo-done":"diff-undo-link diff-undo-failed"}catch(e){s.textContent=`⎿ undo failed — ${e&&e.message||e}`,s.className="diff-undo-link diff-undo-failed"}};s.addEventListener("click",a),s.addEventListener("keydown",(e=>{!e||"Enter"!==e.key&&" "!==e.key||("function"==typeof e.preventDefault&&e.preventDefault(),a())})),o.appendChild(s),t.appendChild(o)}(a,n),a}const r=document.createElement("div");return r.textContent=Mo(n),a.appendChild(r),a}function No(e){return e.startsWith("@@")?"diff-hunk":e.startsWith("+++")||e.startsWith("---")?"diff-file":e.startsWith("+")?"diff-add":e.startsWith("-")?"diff-del":"diff-ctx"}function Ho(e,n,o){if(!e||!n)return;const s=document.createElement("div");s.className="approval-card",s.dataset.approvalId=n.id;const a=document.createElement("div");a.className="approval-title",a.textContent=`${n.tool} wants to run — review before it executes`,s.appendChild(a);const i=function(e,t){const n=t||{};return"exec"===e?n.description?`${n.command} — ${n.description}`:n.command||"":n.file_path||""}(n.tool,n.args);if(i){const e=document.createElement("div");e.className="approval-summary",e.textContent=i,s.appendChild(e)}if(n.diff){const e=document.createElement("pre");e.className="approval-diff";for(const t of n.diff.split("\n")){const n=document.createElement("div");n.className=No(t),n.textContent=t,e.appendChild(n)}s.appendChild(e)}const r=document.createElement("div");r.className="approval-actions";const c=(e,o,a)=>{const i=document.createElement("button");return i.type="button",i.className=`approval-btn ${o}`,i.textContent=e,i.addEventListener("click",(()=>(e=>{for(const e of r.querySelectorAll("button"))e.disabled=!0;s.classList.add("resolved");const o=document.createElement("div");o.className="approval-decision",o.textContent="deny"===e?"Denied":"session"===e?"Allowed for this session":"always"===e?"Always allowed":"Allowed once",s.appendChild(o),t.respondApproval(n.id,e)})(a))),i};if(r.appendChild(c("Allow once","allow","once")),r.appendChild(c("Allow for this session","allow-session","session")),n.canPersist){const e=c("Always allow this command","allow-always","always");e.title="Stores a rule in ~/.aegiscode/permissions.json, shared with the terminal face",r.appendChild(e)}r.appendChild(c("Deny","deny","deny")),s.appendChild(r);let l=e.querySelector(".approval-slot");if(!l){l=document.createElement("div"),l.className="approval-slot";const t=o?e.querySelector(o):null;t?e.insertBefore(l,t):e.appendChild(l)}return l.appendChild(s),s}function Bo(){try{if(globalThis.crypto&&"function"==typeof globalThis.crypto.randomUUID)return globalThis.crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}async function Io(){try{D=await t.listClasses()||[]}catch(e){D=[],l.modelHint.textContent=`listClasses failed: ${e&&e.message?e.message:e}`}l.classSelect.innerHTML="";for(const e of D){const t=document.createElement("option");t.value=e.class,t.textContent=e.configured?e.label:`${e.label} (not configured)`,l.classSelect.appendChild(t)}const e=localStorage.getItem(d);e&&D.some((t=>t.class===e))&&(l.classSelect.value=e),await Ro(l.classSelect.value)}async function Ro(e){if(l.autonomousToggleWrap&&(l.autonomousToggleWrap.hidden=e!==g),se(),ie(e),l.modelSelect.hidden=!1,l.modelSelect.disabled=!1,l.modelFree.hidden=!0,l.modelFree.value="",l.modelHint.textContent="",l.modelSelect.innerHTML="",P=new Map,"aegis"===e){const e=document.createElement("option");e.value=i,e.textContent=r,l.modelSelect.appendChild(e)}try{const n=await t.listModels(e),o=Array.isArray(n&&n.models)?n.models:[],s=Boolean(n&&n.needsKey),a=Boolean(n&&n.needsDaemon),i=!(n&&!1===n.listed),r=Boolean(n&&n.providersFailed),c=Array.isArray(n&&n.unmatchedProviders)?n.unmatchedProviders:[];l.modelFree.hidden=!("local"===e&&(a||!i));for(const e of o){P.set(e.id,e);const t=document.createElement("option");t.value=e.id,t.textContent=e.label||e.id,l.modelSelect.appendChild(t)}let d;if(re(),s)d=null;else if(a)d=`No local model server at ${n&&n.baseURL||"the configured address"} — start Ollama, or set Base URL below to llama.cpp / LM Studio, then Refresh.`;else if("local"!==e||i)if("byok"===e&&r)d="Provider catalog unreachable — your saved keys and declared models are unaffected. Refresh to try again."+(n&&n.providersError?` (${n.providersError})`:"");else if(o.length)if("byok"===e&&n&&n.needsAegisKey){const e=n&&n.fee||null;d=`${o.length} model${1===o.length?"":"s"} available — `+(e&&e.require_balance?"an AEGIS account key and a funded balance are required: the BYOK handling fee is billed there.":"an AEGIS account key is required: the BYOK handling fee is billed there.")}else d="byok"===e&&n&&n.needsProviderKey?`${o.length} model${1===o.length?"":"s"} available — add a provider key in Provider settings below to use one.`:`${o.length} model${1===o.length?"":"s"} available.`;else d="local"===e?"No models on this server yet — pull one first (ollama pull llama3.2).":"aegis"===e?"No models to pin — this class runs the pooled route on the server's own default. Use Bring your own key for a per-provider model.":"No models listed.";else d="That address answered but listed no models — not Ollama? Type the model tag in the box above and send.";"byok"===e&&!r&&c.length&&(d=`${d} Not shown: ${c.join(", ")} — declared in models.json, but not in the provider catalog. Check the provider name in Settings.`);const u=maxTokensCeiling(P.get(ae()));if(s){l.modelHint.textContent="Connect Aegis Cloud to load its models: paste your AEGIS API key in the Status card above (";const e=document.createElement("a");return e.href=w,e.target="_blank",e.rel="noreferrer noopener",e.textContent="free key at aegiscloud.org",l.modelHint.appendChild(e),void l.modelHint.appendChild(document.createTextNode("), then Save."))}l.modelHint.textContent=u<FLAT_CEILING?`${d} · max output: ${u.toLocaleString()}`:d}catch(e){P=new Map,l.modelHint.textContent=`listModels failed: ${e&&e.message?e.message:e}`,re()}}function To(){if(l.queueModelInput&&!l.queueModelInput.hidden){const e=l.queueModelInput.value.trim();if(e)return e}return l.queueModelSelect?l.queueModelSelect.value:""}async function Oo(e){if(l.queueModelSelect){if(function(e){const t=l.queueFanout&&l.queueFanout.closest("label");t&&(t.hidden="aegis"!==e)}(e),l.queueModelSelect.hidden=!1,l.queueModelSelect.disabled=!1,l.queueModelInput&&(l.queueModelInput.hidden=!0,l.queueModelInput.value=""),l.queueModelField&&(l.queueModelField.hidden=!0),l.queueModelHint&&(l.queueModelHint.textContent=""),l.queueModelSelect.innerHTML="","aegis"===e){const e=document.createElement("option");e.value="",e.textContent="server default (auto)",l.queueModelSelect.appendChild(e)}try{const n=await t.listModels(e),o=Array.isArray(n&&n.models)?n.models:[],s=Boolean(n&&n.needsKey),a=Boolean(n&&n.needsDaemon),i=!(n&&!1===n.listed);l.queueModelInput&&(l.queueModelInput.hidden=!("local"===e&&(a||!i))),l.queueModelField&&(l.queueModelField.hidden=!("local"===e&&(a||!i)));for(const e of o){const t=document.createElement("option");t.value=e.id,t.textContent=e.label||e.id,l.queueModelSelect.appendChild(t)}if(!l.queueModelHint)return;s?l.queueModelHint.textContent="Connect this class in the Model card above (API key / provider key), then Refresh.":a?l.queueModelHint.textContent=`No local model server at ${n&&n.baseURL||"the configured address"} — start it, then reopen this picker.`:"local"!==e||i?o.length?"byok"===e&&n&&n.needsProviderKey&&(l.queueModelHint.textContent="A provider key is required before a queued task on this model can run — add one in the Model card above."):l.queueModelHint.textContent="local"===e?"No models on this server yet — pull one first (ollama pull llama3.2).":"aegis"===e?"No models to pin — this runs the pooled route on the server's own default.":"No models listed.":l.queueModelHint.textContent="That address answered but listed no models — type the model tag above."}catch(e){l.queueModelHint&&(l.queueModelHint.textContent=`listModels failed: ${e&&e.message?e.message:e}`)}}}function Fo({provider:e,name:t,cfg:n,onSave:o,onRemove:s}){const a=document.createElement("div");a.className="setting-row",a.dataset.provider=e;const i=document.createElement("div");i.className="setting-name",i.textContent=t,a.appendChild(i);const r=document.createElement("input");r.type="password",r.className="setting-input",r.placeholder=n.configured?`key ${n.keyMask} (blank = keep)`:"API key",a.appendChild(r);const c=document.createElement("div");c.className="setting-status",c.textContent=n.configured?`configured (${n.keyMask})`:"no key",c.dataset.state=n.configured?"configured":"unset",a.appendChild(c);const l=document.createElement("div");l.className="setting-actions";const d=document.createElement("button");d.type="button",d.className="ghost-btn btn-primary btn-sm",d.textContent="Save",d.addEventListener("click",(()=>o(r.value))),l.appendChild(d);const u=document.createElement("button");return u.type="button",u.className="ghost-btn danger",u.textContent="Remove",u.disabled=!n.configured,u.addEventListener("click",s),l.appendChild(u),a.appendChild(l),a}async function Do(e){l.settingsHint.textContent="saving…";try{const n=String(null==e?"":e).trim()||b,o=await t.settings.set(C,{baseURL:n}),s=o&&o.baseURL||n;l.settingsHint.textContent=`saved: local model server at ${s}`,await Po(),await Ro(l.classSelect.value)}catch(e){l.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function Po(){l.settingsList.innerHTML="";const e=[];let n=[];try{n=await t.settings.get()||[]}catch{}Array.isArray(n)&&(n=n.filter((e=>e&&!v.has(e.provider))));{const e=n.find((e=>e&&e.provider===C))||{provider:C,baseURL:"",configured:!1,keyMask:null};l.settingsList.appendChild(function(e){const t=C,n=document.createElement("div");n.className="setting-row",n.dataset.provider=t;const o=document.createElement("div");o.className="setting-name",o.textContent="Local model server",n.appendChild(o);const s=document.createElement("input");s.type="text",s.className="setting-input",s.id="local-base-url",s.autocomplete="off",s.spellcheck=!1,s.placeholder=b,s.value=e.baseURL||"",s.addEventListener("keydown",(e=>{"Enter"===e.key&&Do(s.value)})),n.appendChild(s);const a=document.createElement("div");a.className="setting-status",a.textContent=e.baseURL?e.baseURL:`default (${b})`,a.dataset.state=e.baseURL?"configured":"unset",n.appendChild(a);const i=document.createElement("div");i.className="setting-actions";const r=document.createElement("button");r.type="button",r.className="ghost-btn btn-primary btn-sm",r.textContent="Save",r.addEventListener("click",(()=>Do(s.value))),i.appendChild(r);const c=document.createElement("button");return c.type="button",c.className="ghost-btn danger",c.textContent="Reset",c.disabled=!e.baseURL,c.addEventListener("click",(()=>Vo(t))),i.appendChild(c),n.appendChild(i),n}(e))}try{const o=await t.listModels("byok"),s=Array.isArray(o&&o.providers)?o.providers:[];for(const t of s){if(!t||!t.id)continue;if(e.push({id:t.id,label:t.label||t.id}),t.id===k)continue;const o=`byok:${t.id}`,s=n.find((e=>e.provider===o))||{provider:o,baseURL:"",configured:!1,keyMask:null};l.settingsList.appendChild(Fo({provider:o,name:`BYOK: ${t.label||t.id}`,cfg:s,onSave:e=>jo(o,e),onRemove:()=>Vo(o)}))}const a=o&&o.fee;if(a&&!a.disabled&&(Number(a.in_usd_per_1k)>0||Number(a.out_usd_per_1k)>0)){const e=document.createElement("div");e.className="setting-row",e.id="byok-fee-note";const t=document.createElement("div");t.className="setting-name";const n=e=>`${Number(e).toFixed(4)}`;t.textContent=`BYOK handling fee: ${n(a.in_usd_per_1k)} / 1k in, ${n(a.out_usd_per_1k)} / 1k out — billed to your AEGIS account on top of your own provider bill. This is the published rate, not a personal quote — Unlimited subscribers pay no handling fee at all, and neither do users on the free 1-month Unlimited trial.`,e.appendChild(t),l.settingsList.appendChild(e)}}catch{}try{await async function(e){if(!l.settingsList||!t.userModels)return;const n=await t.userModels.get();if(!n)return;const o=n&&n.map||{},s=(e||[]).map((e=>e&&e.id||"")).filter(Boolean),a=document.createElement("div");a.id="user-models-block";const i=document.createElement("div");i.className="setting-name",i.textContent="Your own models (BYOK)",a.appendChild(i);const r=document.createElement("div");r.className="setting-row",r.dataset.provider="byok:__user-model-add";const c=document.createElement("input");if(c.type="text",c.className="setting-input",c.id="user-model-provider",c.placeholder="provider (deepseek)",c.autocomplete="off",c.spellcheck=!1,s.length){const e=document.createElement("datalist");e.id="user-model-providers";for(const t of s){const n=document.createElement("option");n.value=t,e.appendChild(n)}r.appendChild(e),c.setAttribute("list","user-model-providers")}r.appendChild(c);const d=document.createElement("input");d.type="text",d.className="setting-input",d.id="user-model-id",d.placeholder="model id (deepseek-v4.2-preview)",d.autocomplete="off",d.spellcheck=!1,r.appendChild(d);const u=document.createElement("div");u.className="setting-actions";const m=document.createElement("button");m.type="button",m.className="ghost-btn",m.id="user-model-add",m.textContent="Add model",m.addEventListener("click",(async()=>{const e=c.value.trim(),n=d.value.trim();l.settingsHint.textContent="adding…";try{const o=await t.userModels.add(e,n);l.settingsHint.textContent=o&&!1===o.added?`${o.provider}:${o.model} was already declared.`:`added ${o.provider}:${o.model} — /models and the picker now offer it.`,await Po(),await Ro(l.classSelect.value)}catch(e){l.settingsHint.textContent=`${e&&e.message?e.message:e}`}})),u.appendChild(m);const p=document.createElement("button");p.type="button",p.className="ghost-btn",p.id="user-model-discover",p.textContent="List from provider",u.appendChild(p);const f=document.createElement("div");f.className="setting-status",f.id="user-model-discovered",f.hidden=!0,p.addEventListener("click",(async()=>{const e=c.value.trim();if(!e)return void(l.settingsHint.textContent="type a provider id first (the CLI's /byok lists them).");if("function"!=typeof t.userModels.discover)return void(l.settingsHint.textContent="this build cannot ask a provider — type the model id.");let n;l.settingsHint.textContent=`asking ${e}…`,f.hidden=!0,f.textContent="";try{n=await t.userModels.discover(e)}catch(e){return void(l.settingsHint.textContent=`${e&&e.message?e.message:e}`)}if(!n||!n.ok)return void(l.settingsHint.textContent=`${e}: ${n&&n.error||"no answer"}`);l.settingsHint.textContent=`${n.provider} serves ${n.count} chat model id(s) — pick one and Add model, or add them all.`;const o=document.createElement("select");o.className="setting-input",o.id="user-model-discovered-list";for(const e of n.ids){const t=document.createElement("option");t.value=e,t.textContent=n.declared&&n.declared.includes(e)?`${e} — declared`:e,o.appendChild(t)}if(o.addEventListener("change",(()=>{d.value=o.value})),n.ids.length){d.value=n.ids[0],f.appendChild(o);const e=document.createElement("button");e.type="button",e.className="ghost-btn",e.id="user-model-add-all",e.textContent=`Add all ${n.count}`,e.addEventListener("click",(async()=>{l.settingsHint.textContent=`adding ${n.count}…`;try{const e=await t.userModels.addAll(n.provider,n.ids);l.settingsHint.textContent=`added ${e.added} of ${n.ids.length}`+(e.already&&e.already.length?` (${e.already.length} were already declared)`:"")+(e.failed&&e.failed.length?` — ${e.failed.length} refused`:"")+".",await Po(),await Ro(l.classSelect.value)}catch(e){l.settingsHint.textContent=`${e&&e.message?e.message:e}`}})),f.appendChild(e)}else f.textContent="the vendor answered with no chat models — type an id above.";if(n.others&&n.others.length){const e=document.createElement("div");e.textContent=`${n.others.length} non-chat id(s) left out: ${n.others.slice(0,6).join(", ")}`,f.appendChild(e)}f.hidden=!1})),r.appendChild(u),r.appendChild(f);const h=document.createElement("div");h.className="setting-status",h.id="user-model-hint",h.textContent=n.file?`saved in ${n.file} — the CLI reads the same file (/model-add)`:"saved beside your AEGIS config — the CLI reads the same file (/model-add)",r.appendChild(h),a.appendChild(r);const y=Object.keys(o).sort();for(const e of y)for(const n of o[e]){const o=document.createElement("div");o.className="setting-row",o.dataset.provider=`byok:${e}`;const i=document.createElement("div");i.className="setting-name",i.textContent=`${e} — ${n}`,o.appendChild(i);const r=document.createElement("div");r.className="setting-status",r.textContent=s.length&&!s.includes(e)?"no provider row for this id — /byok lists the ones the relay takes":"offered in the picker on this machine",o.appendChild(r);const c=document.createElement("div");c.className="setting-actions";const d=document.createElement("button");d.type="button",d.className="ghost-btn danger",d.textContent="Remove",d.addEventListener("click",(async()=>{l.settingsHint.textContent="removing…";try{const o=await t.userModels.remove(e,n);l.settingsHint.textContent=o&&!1===o.removed?`${e}:${n} was not declared.`:`removed ${e}:${n}.`,await Po(),await Ro(l.classSelect.value)}catch(e){l.settingsHint.textContent=`${e&&e.message?e.message:e}`}})),c.appendChild(d),o.appendChild(c),a.appendChild(o)}const g=n&&n.invalid||[];for(const e of g){const t=document.createElement("div");t.className="setting-row";const n=document.createElement("div");n.className="setting-name",n.textContent=`${e.provider||"models.json"}: ${null==e.model?"":String(e.model)}`.trim(),t.appendChild(n);const o=document.createElement("div");o.className="setting-status",o.textContent=`skipped — ${e.reason}`,t.appendChild(o),a.appendChild(t)}l.settingsList.appendChild(a)}(e)}catch(e){l.settingsHint.textContent=`your own models: ${e&&e.message?e.message:e}`}try{await Uo()}catch(e){l.customStatus&&(l.customStatus.textContent=`custom provider: ${e&&e.message?e.message:e}`)}}async function Uo(){if(!l.customBaseUrl)return;let e=null,n=[];try{const n=await t.settings.get()||[],o=(Array.isArray(n)?n:[]).find((e=>e&&e.provider===`byok:${k}`));o&&(e={baseURL:o.baseURL||"",configured:Boolean(o.configured),keyMask:o.keyMask})}catch{}try{const e=await t.userModels.get(),o=e&&e.map||{};n=Array.isArray(o[k])?o[k]:[]}catch{}!function(e,t){if(!l.customBaseUrl)return;const n=e||{},o=Array.isArray(t)?t:[];if(!l.customBaseUrl.value&&n.baseURL&&(l.customBaseUrl.value=n.baseURL),l.customKey&&(l.customKey.placeholder=n.configured?`key ${n.keyMask||"••••"} (blank = keep)`:"sk-…",l.customKey.value=""),l.customRemove&&(l.customRemove.disabled=!n.configured&&!n.baseURL),!l.customStatus)return;const s=[];n.baseURL?s.push(`endpoint ${n.baseURL}`):s.push("no endpoint saved"),s.push(n.configured?`key ${n.keyMask||"saved"}`:"no key"),s.push(o.length?`model${1===o.length?"":"s"} ${o.join(", ")}`:"no model declared"),l.customStatus.textContent=s.join(" · ")}(e,n)}async function _o(){if(!l.customBaseUrl)return;const e=String(l.customBaseUrl.value||"").trim(),n=l.customKey?String(l.customKey.value||"").trim():"",o=l.customModel?String(l.customModel.value||"").trim():"",s=e=>{l.customStatus&&(l.customStatus.textContent=e)};if(!e)return void s("an address is required — aegis1 dials the endpoint you name, and refuses a custom call that names none.");if(!/^https:\/\//i.test(e))return void s("refused: only an https:// endpoint is dialed — aegis1 rejects a plain-http or scheme-less base URL for this provider.");if(!o)return void s("a model id is required — the `custom` provider pins no default, so nothing would be selectable in the picker.");s("saving…");const a=`byok:${k}`;try{const o={};o.baseURL=e,n&&(o.key=n),await t.settings.set(a,o)}catch(e){return void s(`endpoint not saved: ${e&&e.message?e.message:e}`)}try{await t.userModels.add(k,o)}catch(e){return s(`endpoint saved, model NOT declared: ${e&&e.message?e.message:e}`),await Uo(),void await Ro(l.classSelect.value).catch((()=>{}))}l.customModel&&(l.customModel.value=""),s(`saved ${e} with model ${o} — pick it under provider "byok", then the model.`),await Uo(),await Po(),await Ro(l.classSelect.value).catch((()=>{}))}async function Ko(){if(!l.customBaseUrl)return;const e=e=>{l.customStatus&&(l.customStatus.textContent=e)};e("removing…");let n=0;try{const e=await t.userModels.get(),o=e&&e.map||{},s=Array.isArray(o[k])?o[k]:[];for(const e of s)await t.userModels.remove(k,e),n+=1}catch{}try{await t.settings.remove(`byok:${k}`)}catch(t){return void e(`remove failed: ${t&&t.message?t.message:t}`)}l.customBaseUrl&&(l.customBaseUrl.value=""),e(`removed the custom endpoint${n?` and ${n} declared model(s)`:""}.`),await Uo(),await Po(),await Ro(l.classSelect.value).catch((()=>{}))}async function jo(e,n){l.settingsHint.textContent="saving…";try{const o={};n&&(o.key=n),await t.settings.set(e,o),l.settingsHint.textContent="saved.",await Po(),await Ro(l.classSelect.value)}catch(e){l.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function Vo(e){l.settingsHint.textContent="removing…";try{await t.settings.remove(e),l.settingsHint.textContent="removed.",await Po(),await Ro(l.classSelect.value)}catch(e){l.settingsHint.textContent=`remove failed: ${e&&e.message?e.message:e}`}}const Go=["sessions","memory"];let Qo="sessions";function Wo(e){const t=Go.includes(e)?e:"sessions";Qo=t;for(const e of Go){const n="sessions"===e?l.paneSessions:l.paneMemory,o="sessions"===e?l.tabSessions:l.tabMemory,s=e===t;n&&(n.hidden=!s),o&&(o.setAttribute("aria-selected",s?"true":"false"),o.classList.toggle("is-active",s))}}const zo=new Set,Yo=3;function Jo(e){const t=(Array.isArray(e&&e.messages)?e.messages:[]).find((e=>e&&"user"===e.role&&e.content));return t&&t.content?String(t.content):e&&"string"==typeof e.firstPrompt?e.firstPrompt:""}function Xo(e){const t=Jo(e);return Boolean(t)&&function(e,t){const n=String(null==e?"":e).replace(/\s+/g," ").trim(),o=String(null==t?"":t).replace(/\s+/g," ").trim();if(!n||!o)return!1;const s=o.slice(0,60);return n===s||60===s.length&&n.length>=52&&s.startsWith(n)}(e&&e.title,t)}function Zo(e){if(!e||!e.id||zo.has(e.id))return;if(!0===e.named&&!Xo(e))return;const t=Jo(e);if(!t)return;if(zo.add(e.id),"function"!=typeof n.nameSession)return;const o=l.classSelect?l.classSelect.value:"";n.nameSession({sessionId:e.id,prompt:t,class:o,model:ae()}).then((t=>{t&&(e.title=t,e.named=!0,ss())})).catch((()=>{}))}let es=[],ts=null;const ns="undefined"!=typeof window&&window.aegisLibrary||null;async function os(){l.sessionsHint.textContent="";let e=[];try{const t=await n.listSessions();e=t&&t.sessions||[]}catch(e){return l.sessionsList.innerHTML="",void(l.sessionsHint.textContent=`list failed: ${e&&e.message?e.message:e}`)}es=e;let t=Yo;for(const n of e){if(t<=0)break;!n||!0===n.named&&!Xo(n)||zo.has(n.id)||(t-=1,Zo(n))}ss()}function ss(){if(!l.sessionsList)return;const e=l.sessionsFilter?l.sessionsFilter.value:"",t=es,n=ns?ns.filterSessions(e,t):t;if(l.sessionsCount&&(l.sessionsCount.textContent=ns?ns.countLabel(n.length,t.length):""),l.sessionsList.innerHTML="",!t.length)return void l.sessionsList.appendChild(is("no conversations yet"));if(!n.length)return void l.sessionsList.appendChild(is(`nothing matches “${String(e).trim()}”`));const o=Date.now(),s=ns?ns.groupSessions(n,o):[{key:"all",label:"",sessions:n}],a=n.length>as?as:1/0;let i=0,r=0;for(const e of s)if(i>=a)r+=e.sessions.length;else{if(e.label){const t=document.createElement("li");t.className="library-group",t.setAttribute("role","presentation"),t.textContent=e.label,l.sessionsList.appendChild(t)}for(const t of e.sessions)i>=a?r+=1:(l.sessionsList.appendChild(rs(t,o)),i+=1)}if(r>0){const e=document.createElement("li");e.className="empty library-more",e.textContent=`${r} more — type in the filter to narrow`,l.sessionsList.appendChild(e)}}const as=200;function is(e){const t=document.createElement("li");return t.className="empty",t.textContent=e,t}function rs(t,o){const s=document.createElement("li");if(s.className="session-row",s.tabIndex=0,s.dataset.sessionId=t&&t.id||"",t&&t.id&&t.id===O&&s.classList.add("is-current"),ts&&t&&t.id===ts)return s.classList.add("is-renaming"),s.appendChild(function(e){const t=document.createElement("input");return t.type="text",t.className="session-rename",t.value=e&&e.title||"",t.setAttribute("aria-label","New name for this conversation"),t.addEventListener("click",(e=>e.stopPropagation())),t.addEventListener("keydown",(o=>{o.stopPropagation(),"Enter"===o.key?(o.preventDefault(),async function(e,t){const o=String(null==t?"":t).trim();if(ts=null,!o||o===(e&&e.title||""))return void ss();if("function"!=typeof n.rename)return l.sessionsHint.textContent="rename is unavailable in this build.",void ss();const s=es.find((t=>t&&t.id===e.id));s&&(s.title=o,s.named=!0),ss();try{await n.rename(e.id,o),l.sessionsHint.textContent=`renamed to “${o}”`}catch(e){l.sessionsHint.textContent=`rename failed: ${e&&e.message?e.message:e}`}await os()}(e,t.value)):"Escape"===o.key&&(o.preventDefault(),ts=null,ss())})),t.addEventListener("blur",(()=>{ts===(e&&e.id)&&(ts=null,ss())})),setTimeout((()=>{try{t.focus(),t.select()}catch{}}),0),t}(t)),s;const a=document.createElement("span");a.className="session-title",a.textContent=ns?ns.sessionTitle(t):t&&t.title||t&&t.id||"untitled",s.appendChild(a);const i=document.createElement("span");i.className="session-meta",i.textContent=ns?ns.sessionMeta(t,o):"",s.appendChild(i);const r=document.createElement("span");r.className="session-actions";for(const[o,s,a]of[["Rename","Rename this conversation",()=>function(e){e&&e.id&&(ts=e.id,ss())}(t)],["Export","Save this conversation as Markdown",()=>async function(t){if(t&&t.id)if("function"==typeof e.exportSession)try{const n=await e.exportSession(t.id,"markdown");n&&n.ok?l.sessionsHint.textContent=`exported to ${n.filePath}`:n&&n.canceled?l.sessionsHint.textContent="":l.sessionsHint.textContent=`export failed: ${n&&n.reason||"unknown error"}`}catch(e){l.sessionsHint.textContent=`export failed: ${e&&e.message?e.message:e}`}else l.sessionsHint.textContent="export is unavailable in this build."}(t)],["Delete","Delete this conversation",()=>async function(e){if(!e||!e.id)return;const t=ns?ns.sessionTitle(e):e.title||e.id;if("function"!=typeof confirm||confirm(`Delete “${t}”?\n\nThis removes the conversation from this device. It cannot be undone.`)){try{await n.delete(e.id)}catch(e){return void(l.sessionsHint.textContent=`delete failed: ${e&&e.message?e.message:e}`)}O===e.id&&fs(),l.sessionsHint.textContent=`deleted “${t}”`,await os()}}(t)]]){const e=document.createElement("button");e.type="button",e.className="session-action",e.textContent=o,e.title=s,e.setAttribute("aria-label",`${s}`),e.addEventListener("click",(e=>{e.stopPropagation(),a()})),r.appendChild(e)}return s.appendChild(r),s.addEventListener("click",(()=>ms(t.id))),s.addEventListener("keydown",(e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),ms(t.id))})),s}function cs(e){if(!l.syncStatus)return;if(!e)return void(l.syncStatus.textContent="");const t=[e.cloud?"cloud sync on":"cloud sync off (no key)",`${e.pending} pending`];e.lastSyncAt&&t.push(`last synced ${new Date(e.lastSyncAt).toLocaleTimeString()}`),e.retry&&e.retry.lastError&&t.push(`last sync attempt failed: ${e.retry.lastError}`),l.syncStatus.textContent=t.join(" · ")}async function ls(){try{cs(await n.status())}catch{cs(null)}}function ds(){"function"==typeof n.auto&&n.auto().then((e=>{e&&e.upgrade&&wt(l.sessionsHint,e.upgrade,"queued memory is waiting on the free-plan cap","See what Pro covers →"),e&&e.memoryFlushed&&_n().catch((()=>{}))})).catch((()=>{}))}async function us(){l.syncNow.disabled=!0,l.sessionsHint.textContent="syncing…";try{const e=await n.push(),t=await n.pull();e.upgrade||t.upgrade?wt(l.sessionsHint,e.upgrade||t.upgrade,"queued memory is waiting on the free-plan cap","See what Pro covers →"):e.ok||t.ok?l.sessionsHint.textContent=`synced (pushed ${e.pushed||0}, pulled ${t.merged||0})`:l.sessionsHint.textContent=`sync failed: ${e.reason||t.reason||"unknown error"}`}catch(e){l.sessionsHint.textContent=`sync failed: ${e&&e.message?e.message:e}`}finally{l.syncNow.disabled=!1,await ls(),await os()}}function ms(e,t){n.open(e).then((e=>{if(!e)return void(l.sessionsHint.textContent="session not found");l.messages.innerHTML="",t&&t.fromNav||xn({kind:"session",id:e.id});const n=Array.isArray(e.messages)?e.messages:[];n.length||eo();for(const t of n){const n="assistant"===t.role?"assistant":"system"===t.role?"system":"user";bo(n,t.content||t.text||"",void 0,"assistant"===n?e.id:void 0)}O=e.id,U.set(e.id,rollMessages(n)),K(e.id),F=replayHistory(n),l.sessionsHint.textContent=`opened ${e.id.slice(0,8)}…`})).catch((e=>{l.sessionsHint.textContent=`open failed: ${e&&e.message?e.message:e}`}))}function ps(t){const n=O;n?e.exportSession(n,t).then((e=>{e&&e.ok?l.sessionsHint.textContent=`exported to ${e.filePath}`:e&&e.canceled||(l.sessionsHint.textContent=`export failed: ${e&&e.reason||"unknown error"}`)})).catch((e=>{l.sessionsHint.textContent=`export failed: ${e&&e.message?e.message:e}`})):l.sessionsHint.textContent="no open session to export"}function fs(){z(),hn={query:"",matches:[],index:-1,texts:[]},l.findInput&&(l.findInput.value=""),Mn(),In(),O&&t.clearApprovals(O).catch((()=>{})),eo(),l.sessionsHint.textContent="",R=null,T=null,J=null,X=null,O=null,F=[],Q=0,K(null)}function hs(e){e&&("open"===e.action&&e.sessionId?ms(e.sessionId):"new"===e.action&&(fs(),e.prompt&&(l.prompt.value=e.prompt,l.prompt.focus())))}async function ys(){const e=l.prompt.value.trim(),o=Cs.length?Cs.map((e=>({kind:e.kind,path:e.path,name:e.name,size:e.size,mime:e.mime,dataUrl:e.dataUrl,text:e.text,truncated:e.truncated}))):void 0;if(!e&&!o||l.send.disabled)return;const s=l.classSelect.value,a=ae();l.prompt.value="";const i=(r=Cs,Array.isArray(r)&&r.length?r.map((e=>`📎 ${e.name||e.path}`)).join("\n"):"");var r;const c=i?e?`${e}\n${i}`:i:e;Cs=[],ks=[],xs();const d=++Y;J=d,X=null,bo("user",c);const u=s===g&&oe(),m=ce(),p=budgetFor(a,void 0,m),f=u&&parseInt(l.autonomousWorkers.value,10)||void 0;O||(O=Bo());const h=O;T=h,vo();const y=replayHistory(F);F.push({role:"user",content:o&&!ws()?Ms(e,o):c}),So(!0,{cancellable:!0}),R&&K(h,{prompt:e,reply:"",reasoning:""}),ee({force:!0});try{await n.append(h,{role:"user",content:c})}catch{}let v="",C="",k=0;const b=[];let w=null;const x=(S=()=>{if(!R)return;if(R.classList.remove("pending"),C){const e=function(e){let t=e.querySelector(".reasoning");if(!t){t=document.createElement("div"),t.className="reasoning";const n=e.querySelector(".body");n?e.insertBefore(t,n):e.appendChild(t)}return t}(R);e.textContent!==C&&(e.textContent=C)}const t=R.querySelector(".body");t&&t.textContent!==v&&(t.textContent=v);const n=v.length+C.length+4*k;liveMeterDue(w,n)&&(w=n,K(h,{prompt:e,reply:v,reasoning:C,measuredReasoningTokens:k})),ee()},Z?Z.paint(S):S);var S;const E=e=>{if(e&&"number"==typeof e.thinkingTokens&&e.thinkingTokens>0)return k+=e.thinkingTokens,void x();if(e&&"string"==typeof e.reasoning&&e.reasoning)return C+=e.reasoning,void x();if(e&&"string"==typeof e.note&&e.note){const t=xo();return t.classList.remove("pending"),function(e,t,n){if(!e||!t)return null;const o=document.createElement("div");o.className="turn-note",o.textContent=t;const s=n?e.querySelector(n):null;s?e.insertBefore(o,s):e.appendChild(o)}(t,e.note,".body"),void ee()}if(e&&e.approval){const t=xo();return t.classList.remove("pending"),Ho(t,e.approval,".body"),void ee({force:!0})}if(e&&e.rounds){const n=xo();return n.classList.remove("pending"),function(e,n,o){if(!e||!n||!n.id)return null;const s=Number(n.spent)||0,a=Number(n.size)||s,i=Number(n.extensions)||1,r=Number(n.max)||8,c=document.createElement("div");c.className="approval-card rounds-card",c.dataset.roundsAskId=n.id;const l=document.createElement("div");l.className="approval-title",l.textContent="Round limit reached — keep going?",c.appendChild(l);const d=document.createElement("div");d.className="approval-summary",d.textContent=`This turn has used all ${s} tool rounds allowed for it. ${a} more continue the SAME turn — no restart, no repeated work. Stopping holds everything done so far: your next message resumes it automatically. (${i} of ${r} extensions.)`,c.appendChild(d);const u=document.createElement("div");u.className="approval-actions";const m=(e,o,s)=>{const i=document.createElement("button");return i.type="button",i.className=`approval-btn ${o}`,i.textContent=e,i.addEventListener("click",(()=>(e=>{for(const e of u.querySelectorAll("button"))e.disabled=!0;c.classList.add("resolved");const o=document.createElement("div");o.className="approval-decision",o.textContent=e?`Continuing — ${a} more rounds`:"Stopped — the work is held",c.appendChild(o),t.respondRoundsAsk(n.id,e)})(s))),i};u.appendChild(m(`Keep going (${a} more rounds)`,"allow",!0)),u.appendChild(m("Stop here","deny",!1)),c.appendChild(u);let p=e.querySelector(".approval-slot");if(!p){p=document.createElement("div"),p.className="approval-slot";const t=o?e.querySelector(o):null;t?e.insertBefore(p,t):e.appendChild(p)}p.appendChild(c)}(n,e.rounds,".body"),void ee({force:!0})}if(e&&e.tool){if("run"===e.tool.phase)return void qo(e.tool);b.push(e.tool);const t=xo();return t.classList.remove("pending"),Ao(t,e.tool,"tool-activity",".body"),void ee()}const n=e&&("string"==typeof e.delta?e.delta:e.content);n&&(v+=n,x())};try{const i=await t.chat({class:s,prompt:e,model:a,maxTokens:p,sessionId:h,autonomous:u,effort:m,workers:f,messages:y,attachments:o,roundsAsk:!0},E);if(i&&i.aborted){const e=new Error(i.message||"This operation was aborted");throw e.name="AbortError",e.code="ABORT_ERR",e}const r=i&&i.choices&&i.choices[0]||{},c=r.message&&r.message.content||v||"(empty response)";isPlaceholderContent(c)||F.push({role:"assistant",content:c});const d=[];i&&i.model?d.push(`model: ${i.model}`):a&&d.push(`model: ${a}`),d.push(function(e){const t=D.find((t=>t.class===e));return t?t.label:e}(s)),u?d.push(`autonomous (${m}, ${f||"auto"}w)`):m&&d.push(`effort: ${m}`);const g=turnAccounting(i&&i.usage,a,{costUsd:i&&"number"==typeof i.costUsd?i.costUsd:void 0}),k=displayTokens(g);if(null!=k)d.push(`tokens: ${k}`);else{const t=estimatedBuckets(e,c,c===C?"":C);t&&t.output>0&&d.push(`~${t.output} tokens`)}const w=feeBillable(function(){const e="undefined"!=typeof state?state:null;return e&&e.entitlement?e.entitlement:null}());null!=g.cost&&w&&d.push(fmtCost(g.cost,g.real)),"byok"===s&&null!=g.cost&&w&&d.push("your provider bill (est.) + AEGIS handling fee");const x=_(h,i&&i.usage,{model:a,costUsd:i&&"number"==typeof i.costUsd?i.costUsd:void 0,calls:i&&i.calls,prompt:e,reply:c,reasoning:c===C?"":C}),S=fmtRoll(x,{omitMoney:!w});S&&d.push(`session: ${S}`),i&&i.pooled_notice&&d.push(i.pooled_notice),bo("assistant",c,d.join(" · ")||void 0,h,b);try{await n.append(h,{role:"assistant",content:c,...j(i&&i.usage,a,g,{prompt:e,reply:c,reasoning:c===C?"":C,calls:i&&i.calls})}),await n.save({id:h,title:e.slice(0,60)}),"function"==typeof n.nameSession&&n.nameSession({sessionId:h,prompt:e,class:s,model:a}).then((e=>{e&&os().catch((()=>{}))})).catch((()=>{}))}catch{}ds(),function(){const e=l.exploreToggle;return Boolean(e&&e.checked)}()&&"(empty response)"!==c&&function(e){const t=document.createElement("div");t.className="chatflow";const n=document.createElement("div");n.className="flow-rail";const o=document.createElement("span");o.className="flow-rail-label",o.textContent="discovery lane";const s=document.createElement("span");s.className="flow-rail-hint",s.textContent="alternatives from the AI — scroll →",n.appendChild(o),n.appendChild(s);const a=document.createElement("div");a.className="flow-track";const i=document.createElement("button");i.type="button",i.className="ghost-btn flow-add",i.textContent="+ another path",i.addEventListener("click",(()=>{wo(G[Q%G.length],a,e)})),a.appendChild(i),t.appendChild(n),t.appendChild(a),l.messages.appendChild(t);for(const t of G.slice(0,2))wo(t,a,e)}({prompt:e,cls:s,model:a,maxTokens:p,parentSessionId:h})}catch(t){if(isCancellation(t,{userStopped:X===d})){const t=salvageTurn({streamedText:v,reasoningText:C}),o=t.text,s=t.reasoning,i=replayableContent(t.kind,o);F.push({role:"assistant",content:i});const r=turnAccounting(void 0,a,{}),c=_(h,void 0,{model:a,prompt:e,reply:o,reasoning:s}),l=["stopped by you"];"reasoning-only"===t.kind&&l.push("reasoning only");const d=displayTokens(r);if(null!=d)l.push(`tokens: ${d}`);else{const t=estimatedBuckets(e,o,s);t&&t.output>0&&l.push(`~${t.output} tokens`)}const u=fmtRoll(c);u&&l.push(`session: ${u}`),bo("assistant",o,l.join(" · "),h,b);try{await n.append(h,{role:"assistant",content:i,...j(void 0,a,r,{prompt:e,reply:o,reasoning:s})})}catch{}ds()}else bo("assistant",`Error: ${t&&t.message?t.message:t}`,"request failed")}finally{So(!1),J===d&&(J=null,T=null),os()}}let gs=!1;function vs(){const e=l.messages;e&&(gs=!0,e.scrollTo({top:e.scrollHeight,behavior:"smooth"}),l.scrollBottom&&(l.scrollBottom.hidden=!0))}let Cs=[],ks=[],bs=0;function ws(){return l.classSelect&&"pro"===l.classSelect.value}function xs(){const e=l.attachRow,t=l.attachNote;if(!e)return;e.textContent="";const n=Cs.length+ks.length;if(e.hidden=0===n,t&&(t.hidden=!0,t.textContent=""),n){for(const t of Cs){const n=document.createElement("span");if(n.className="attach-chip",n.title=t.path||"","image"===t.kind&&t.dataUrl){const e=document.createElement("img");e.className="attach-thumb",e.src=t.dataUrl,e.alt="",n.appendChild(e)}const o=document.createElement("span");o.className="attach-kind",o.textContent="image"===t.kind?"img":"text"===t.kind?"txt":t.kind,n.appendChild(o);const s=document.createElement("span");s.className="attach-name",s.textContent=`${t.name||t.path} · ${Es(t.size)}${t.truncated?" (truncated)":""}`,n.appendChild(s),n.appendChild(Ss((()=>{Cs=Cs.filter((e=>e!==t)),xs()}))),e.appendChild(n)}for(const t of ks){const n=document.createElement("span");n.className="attach-chip is-refused",n.title=t.reason||"";const o=document.createElement("span");o.className="attach-name",o.textContent=`${t.name||t.path} — ${t.reason||"not attached"}`,n.appendChild(o),n.appendChild(Ss((()=>{ks=ks.filter((e=>e!==t)),xs()}))),e.appendChild(n)}if(t&&ws()){const e=Cs.filter((e=>"image"===e.kind)).length;e&&(t.hidden=!1,t.textContent=1===e?"This provider runs text-only, so the picture travels as its file path.":`This provider runs text-only, so the ${e} pictures travel as file paths.`)}}}function Ss(e){const t=document.createElement("button");return t.type="button",t.className="attach-remove",t.title="Remove",t.setAttribute("aria-label","Remove attachment"),t.textContent="×",t.addEventListener("click",e),t}function Es(e){const t=Number(e)||0;return t<1024?`${t} B`:t<1048576?`${Math.round(t/1024)} KB`:`${(t/1048576).toFixed(1)} MB`}async function $s(t){const n=(t||"").split(/[\\/]/).pop()||t;if(Cs.length>=8)return ks.push({path:t,name:n,reason:"at most 8 files per message"}),void xs();let o;try{o=await e.attachments.ingest(t)}catch(e){o={ok:!1,reason:e&&e.message||"could not read file"}}if(!o||!0!==o.ok||!o.attachment)return ks.push({path:t,name:n,reason:o&&o.reason||"not attached"}),void xs();Cs.some((e=>e.path===o.attachment.path))||(Cs.push(o.attachment),xs())}const Ls=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function qs(e){if(e&&"string"==typeof e.mime&&e.mime)return e.mime;const t=e&&"string"==typeof e.dataUrl?e.dataUrl:"",n=/^data:([^;,]+)[;,]/.exec(t);return n?n[1].toLowerCase():""}function Ms(e,t){const n=[],o="string"==typeof e?e:"";o.trim()&&n.push({type:"text",text:o});for(const e of t||[]){const t=qs(e);"image"===e.kind&&e.dataUrl&&Ls.has(t)?n.push({type:"image_url",image_url:{url:e.dataUrl}}):"image"===e.kind?n.push({type:"text",text:e.path?`[attached image, not inline (${t||"unknown image type"}): ${e.path}]`:`[attached image, not inline (${t||"unknown image type"})]`}):"text"===e.kind&&"string"==typeof e.text?n.push({type:"text",text:`--- ${e.name} ---\n${e.text}`}):e.path&&n.push({type:"text",text:`[attached file: ${e.path}]`})}return 1===n.length&&"text"===n[0].type?n[0].text:n.length?n:o}const As="aegis.onboardingSeen";async function Ns(){!function(){const t=document.getElementById("onboard-overlay");if(!t)return;let n=!1;try{n="1"===localStorage.getItem(As)}catch{}if(n)return;t.hidden=!1;const o=document.getElementById("onboard-status"),s=document.getElementById("onboard-google"),a=document.getElementById("onboard-apikey"),i=document.getElementById("onboard-skip"),r=(e,t)=>{o&&(o.textContent=e||"",o.classList.toggle("is-err","err"===t),o.classList.toggle("is-ok","ok"===t))},c=()=>{try{localStorage.setItem(As,"1")}catch{}t.classList.add("is-leaving"),setTimeout((()=>{t.hidden=!0}),250)};s&&s.addEventListener("click",(async()=>{s.disabled=!0,a&&(a.disabled=!0),r("Opening a browser to sign in with Google…");try{const t=await e.driveSignIn();if(t&&t.ok)return r(t.username?`Signed in as ${t.username}`:"Signed in","ok"),void setTimeout(c,500);r(t&&t.error||"Sign-in did not complete.","err")}catch(e){r(e&&e.message||"Sign-in failed.","err")}s.disabled=!1,a&&(a.disabled=!1)})),a&&a.addEventListener("click",(()=>{c(),ao();const e=document.getElementById("api-key-input");e&&e.focus()})),i&&i.addEventListener("click",c)}();try{me(await e.status())}catch{me(null)}"on"===localStorage.getItem(m)&&(l.autonomousToggle.checked=!0),l.autonomousToggle.addEventListener("change",(()=>{localStorage.setItem(m,l.autonomousToggle.checked?"on":"off"),se()}));const n=localStorage.getItem(p)||localStorage.getItem("aegis.autonomousEffort"),i=Array.from(l.effortSelect.options).some((e=>e.value===n));n&&i?l.effortSelect.value=n:n&&localStorage.setItem(p,l.effortSelect.value),l.effortSelect.addEventListener("change",(()=>{localStorage.setItem(p,l.effortSelect.value),ie(l.classSelect.value)}));const r=localStorage.getItem(f);r&&(l.autonomousWorkers.value=r),l.autonomousWorkers.addEventListener("change",(()=>{localStorage.setItem(f,l.autonomousWorkers.value)})),se();const c=localStorage.getItem(h);l.exploreToggle.checked="on"===c,l.exploreToggle.addEventListener("change",(()=>{localStorage.setItem(h,l.exploreToggle.checked?"on":"off"),l.exploreToggle.checked||z()})),l.classSelect.addEventListener("change",(()=>{localStorage.setItem(d,l.classSelect.value),ie(l.classSelect.value),Ro(l.classSelect.value)})),l.modelSelect.addEventListener("change",(()=>{const e=P.get(l.modelSelect.value),t=maxTokensCeiling(e),n=l.modelHint.textContent.replace(/ · max output: [\d,]+$/,"");l.modelHint.textContent=t<FLAT_CEILING?`${n} · max output: ${t.toLocaleString()}`:n,ie(l.classSelect.value),"byok"===l.classSelect.value&&e&&e.provider&&!1===e.configured&&function(e){if(!l.settingsList||!e)return;const t=l.settingsList.querySelector(`.setting-row[data-provider="byok:${e}"] input[type="password"]`);if(ao(),lo(l.settingsList),t&&t.focus(),l.modelHint){const t=l.modelHint.textContent.replace(/ — no .* key saved; add it below\.$/,"");l.modelHint.textContent=`${t} — no ${e} key saved; add it below.`}}(e.provider)})),l.modelFree.addEventListener("input",(()=>{ie(l.classSelect.value)})),l.newChat.addEventListener("click",fs),l.railAutomations&&l.railAutomations.addEventListener("click",(async()=>{await Promise.all([Ze().catch((()=>{})),je().catch((()=>{}))]),io()})),l.automationsBack&&l.automationsBack.addEventListener("click",ro),l.railSettings&&l.railSettings.addEventListener("click",ao),l.settingsBack&&l.settingsBack.addEventListener("click",ro),l.settingsJump&&l.settingsJump.addEventListener("click",(e=>{const t=e.target.closest(".settings-jump-link");if(!t)return;const n=document.getElementById(t.dataset.jump);n&&oo(n)})),l.importSessionBtn&&l.importSessionBtn.addEventListener("click",Qt),l.openCliFace&&l.openCliFace.addEventListener("click",(async()=>{if(e.openCliFace)try{const t=await e.openCliFace();t&&t.ok?le(!0,`opened ${t.emulator||"a terminal"}`):le(!1,t&&t.reason||"could not open a terminal")}catch(e){le(!1,`terminal face failed: ${e&&e.message||e}`)}else le(!1,"terminal face unavailable in this build")})),l.importClose&&l.importClose.addEventListener("click",Vt),l.importBackdrop&&l.importBackdrop.addEventListener("click",Vt),l.importSessionsBtn&&l.importSessionsBtn.addEventListener("click",Wt),l.importMemoryBtn&&l.importMemoryBtn.addEventListener("click",(()=>async function(t){if(!e.memoryImport)return;const n=t&&t.hint||l.memoryHint;l.importMemoryBtn&&(l.importMemoryBtn.disabled=!0),n.textContent="scanning for other AI tool memory…";try{const t=await e.memoryImport({confirm:!1});if(!t||!t.totals||!t.totals.entries)return void(n.textContent=t&&t.summary?t.summary:"nothing found.");const o=(t.sources||[]).filter((e=>e.present&&e.count>0)).map((e=>`${e.label}: ${e.count}`)).join(" · ");n.textContent=`importing ${t.totals.entries} entries — ${o}`;const s=await e.memoryImport({confirm:!0,limit:1e3});if(s&&s.upgrade)return wt(n,s.upgrade,`import stopped after ${s.saved||0} entries`),void await _n();const a=s&&s.queued?` (${s.queued} queued offline)`:"";n.textContent=s&&s.ok?`imported ${s.saved} entries${a}.`:`import stopped: ${s&&s.reason||"unknown error"}`,await _n()}catch(e){n.textContent=`import failed: ${e&&e.message?e.message:e}`}finally{l.importMemoryBtn&&(l.importMemoryBtn.disabled=!1)}}({hint:l.importHint}))),e.onMenuNewChat&&e.onMenuNewChat(fs),e.onMenuSearch&&e.onMenuSearch((()=>Pt(""))),e.onMenuSearchMemory&&e.onMenuSearchMemory(Ut),
6
6
  // Help > Credits & licence… — the AGPL, the program notice and every vendored
7
7
  e.onMenuCredits&&e.onMenuCredits(Xt),e.onMenuPalette&&e.onMenuPalette(mn),e.onMenuToggleSidebar&&e.onMenuToggleSidebar(fn),e.onMenuFind&&e.onMenuFind(qn),e.onMenuGoBack&&e.onMenuGoBack($n),e.onMenuGoForward&&e.onMenuGoForward(Ln),l.findInput&&(l.findInput.addEventListener("input",(()=>{hn.query=l.findInput.value,kn(!0)})),l.findInput.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),Dn(e.shiftKey?-1:1))}))),l.findNext&&l.findNext.addEventListener("click",(()=>Dn(1))),l.findPrev&&l.findPrev.addEventListener("click",(()=>Dn(-1))),l.findClose&&l.findClose.addEventListener("click",Mn),l.paletteInput&&(l.paletteInput.addEventListener("input",(()=>ln(l.paletteInput.value))),l.paletteInput.addEventListener("keydown",(e=>{if("ArrowDown"===e.key)return e.preventDefault(),void un(1);if("ArrowUp"===e.key)return e.preventDefault(),void un(-1);if("Enter"===e.key){const t=on[sn];if(!t)return;e.preventDefault(),Pn(t.action)}}))),l.paletteBackdrop&&l.paletteBackdrop.addEventListener("click",pn),e.onMenuFingerprint&&e.onMenuFingerprint((()=>{dt&&"function"==typeof dt.open&&dt.open()})),e.onMenuGoogleDrive&&e.onMenuGoogleDrive((()=>{dt&&"function"==typeof dt.open&&dt.open({focus:"drive"})})),e.onMenuExportMarkdown&&e.onMenuExportMarkdown((()=>ps("markdown"))),e.onMenuExportJson&&e.onMenuExportJson((()=>ps("json"))),e.onDeepLink&&e.onDeepLink(hs),e.onQuickLauncherPush&&e.onQuickLauncherPush(nt),l.sessionsRefresh.addEventListener("click",os),l.sessionsFilter&&(l.sessionsFilter.addEventListener("input",(()=>ss())),l.sessionsFilter.addEventListener("keydown",(e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),l.sessionsFilter.value="",ss())}))),l.syncNow.addEventListener("click",us),l.sessionsExport.addEventListener("click",(()=>ps("markdown"))),l.apiKeySave.addEventListener("click",we),l.apiKeyVerify.addEventListener("click",xe),l.apiKeyInput.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),we())})),l.customSave&&l.customSave.addEventListener("click",_o),l.customRemove&&l.customRemove.addEventListener("click",Ko);for(const e of[l.customBaseUrl,l.customKey,l.customModel])e&&e.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),_o())}));l.upgradePlan.addEventListener("click",(()=>ke("upgrade"))),l.topupBtn.addEventListener("click",(()=>ke("topup"))),attachScrollLift({panes:document.querySelectorAll(".messages, .side, .memory-scroll"),target:document.body,requestFrame:e=>window.requestAnimationFrame(e),onSync:({panes:e})=>function(e){const t=l.scrollBottom;if(!t)return;const n=e.find((e=>e&&e.classList&&e.classList.contains("messages")));if(!n)return;const o=n.scrollHeight-n.scrollTop-n.clientHeight;if(gs){if(!(o<=24))return void(t.hidden=!0);gs=!1}t.hidden=o<=24}(e)}),l.scrollBottom&&l.scrollBottom.addEventListener("click",vs),async function(){if(e.getFontScale)try{const t=await e.getFontScale();qe(t&&"number"==typeof t.scale?t.scale:1)}catch{qe(1)}}(),async function(){if(e.getAccent)try{const t=await e.getAccent();Me(t&&t.name?t.name:"default")}catch{Me("default")}}(),l.quickLauncherSave.addEventListener("click",Ee),l.quickLauncherShortcut.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),Ee())})),l.fontScale&&l.fontScale.addEventListener("change",(()=>async function(t){if(e.getFontScale)try{const n=await e.setFontScale(t);qe(n&&"number"==typeof n.scale?n.scale:t)}catch(e){l.fontScaleHint&&(l.fontScaleHint.textContent=`save failed: ${e&&e.message?e.message:e}`)}}(Number(l.fontScale.value)))),l.accentSelect&&l.accentSelect.addEventListener("change",(()=>async function(t){if(e.setAccent)try{const n=await e.setAccent(t);Me(n&&n.name?n.name:t)}catch(e){l.accentHint&&(l.accentHint.textContent=`save failed: ${e&&e.message?e.message:e}`)}}(l.accentSelect.value))),l.confirmMode&&l.confirmMode.addEventListener("change",(()=>Ae(l.confirmMode.checked))),l.planMode&&l.planMode.addEventListener("change",(()=>async function(t){if(l.planMode){l.planMode.disabled=!0;try{Ne(await e.setPermissionMode(t))}catch(e){l.planMode.checked=!t,l.planModeHint&&(l.planModeHint.textContent=`save failed: ${e&&e.message?e.message:e}`)}finally{l.planMode.disabled=!1}}}(l.planMode.checked))),l.permRulesForm&&l.permRulesForm.addEventListener("submit",(t=>{t.preventDefault(),async function(t,n){if(!e.permRulesAdd)return;const o=String(null==n?"":n).trim();if(o){l.permRulesAdd&&(l.permRulesAdd.disabled=!0);try{const n=await e.permRulesAdd(t,o);if(n&&!0===n.ok){Be(n),l.permRulesInput&&(l.permRulesInput.value="");const e=!1===n.added?"already stored":"stored";l.permRulesStatus&&(l.permRulesStatus.textContent=n.warning?`${e}: ${o} — ${n.warning}`:`${e}: ${o}`)}else l.permRulesStatus&&(l.permRulesStatus.textContent=`not stored: ${n&&n.reason||"the store refused it"}`)}catch(e){l.permRulesStatus&&(l.permRulesStatus.textContent=`add failed: ${e&&e.message?e.message:e}`)}finally{l.permRulesAdd&&(l.permRulesAdd.disabled=!1)}}else l.permRulesStatus&&(l.permRulesStatus.textContent="type a rule first")}(l.permRulesListSelect?l.permRulesListSelect.value:"allow",l.permRulesInput&&l.permRulesInput.value)})),l.sandboxMode&&l.sandboxMode.addEventListener("change",(()=>{const e=l.sandboxNetwork&&l.sandboxNetwork.checked?"open":"restricted";Fe(l.sandboxMode.value,e)})),l.sandboxNetwork&&l.sandboxNetwork.addEventListener("change",(()=>{Fe(l.sandboxMode?l.sandboxMode.value:"workspace-write",l.sandboxNetwork.checked?"open":"restricted")})),l.autoMode&&l.autoMode.addEventListener("click",(()=>{l.confirmMode&&Ae(!l.confirmMode.checked)})),l.composer.addEventListener("submit",(e=>{e.preventDefault(),ys()})),l.prompt&&(window.addEventListener("dragenter",(e=>{if(!e.dataTransfer)return;const t=Array.from(e.dataTransfer.types||[]);(t.includes("Files")||t.includes("text/plain")||t.includes("text/uri-list"))&&(bs+=1,document.body.classList.add("is-dropping"))})),window.addEventListener("dragleave",(()=>{bs=Math.max(0,bs-1),0===bs&&document.body.classList.remove("is-dropping")})),window.addEventListener("dragover",(e=>{e.dataTransfer&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")})),window.addEventListener("drop",(t=>{bs=0,document.body.classList.remove("is-dropping"),async function(t){const n=t.dataTransfer;if(!n)return;const o=Array.from(n.files||[]);if(o.length){t.preventDefault();for(const t of o){const n=e.attachments.pathFor(t);n?await $s(n):(ks.push({name:t.name||"file",reason:"no path available"}),xs())}return}const s=(n.getData("text/uri-list")||n.getData("text/plain")||"").split(/\r?\n/).map((e=>{const t=e.trim();if(!t)return"";const n=t.replace(/^file:\/\//,"");if(n===t)return t;try{return decodeURIComponent(n).trim()}catch{return n.trim()}})).filter(Boolean).join("\n");s&&(t.preventDefault(),function(e){const t=l.prompt;if(!t)return;const n="number"==typeof t.selectionStart?t.selectionStart:t.value.length,o="number"==typeof t.selectionEnd?t.selectionEnd:t.value.length,s=t.value.slice(0,n),a=t.value.slice(o),i=s&&!/\s$/.test(s)?" ":"";t.value=`${s}${i}${e}${a}`;const r=(s+i+e).length;try{t.setSelectionRange(r,r)}catch{}t.focus()}(s))}(t).catch((()=>{}))})),document.addEventListener("dragover",(e=>e.preventDefault())),document.addEventListener("drop",(e=>e.preventDefault())),l.classSelect&&l.classSelect.addEventListener("change",xs),xs()),l.prompt.addEventListener("keydown",(e=>{if(Hn()){if("ArrowDown"===e.key)return e.preventDefault(),void Fn(1);if("ArrowUp"===e.key)return e.preventDefault(),void Fn(-1);if(("Enter"===e.key||"Tab"===e.key)&&An.rows.length)return e.preventDefault(),void On()}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),l.composer.requestSubmit())})),l.prompt.addEventListener("input",(()=>{Tn().catch((()=>{}))})),l.prompt.addEventListener("click",(()=>{Hn()&&Tn().catch((()=>{}))})),l.tabSessions&&l.tabSessions.addEventListener("click",(()=>Wo("sessions"))),l.tabMemory&&l.tabMemory.addEventListener("click",(()=>Wo("memory"))),l.memorySearchForm.addEventListener("submit",(e=>{e.preventDefault(),St(l.memoryQuery.value.trim())})),l.memorySaveBtn.addEventListener("click",Un),l.sessionClose&&l.sessionClose.addEventListener("click",_t),l.sessionBackdrop&&l.sessionBackdrop.addEventListener("click",_t),l.sessionClear&&l.sessionClear.addEventListener("click",(()=>{l.sessionQuery&&(l.sessionQuery.value=""),It="",l.sessionHint&&(l.sessionHint.textContent=""),Dt(""),l.sessionQuery&&l.sessionQuery.focus()})),l.sessionFilters&&l.sessionFilters.addEventListener("submit",(e=>{e.preventDefault(),Dt(l.sessionQuery?l.sessionQuery.value:"")})),l.sessionQuery&&l.sessionQuery.addEventListener("input",(()=>{Dt(l.sessionQuery.value)})),l.creditsClose&&l.creditsClose.addEventListener("click",Zt),l.creditsBackdrop&&l.creditsBackdrop.addEventListener("click",Zt),l.shortcutsClose&&l.shortcutsClose.addEventListener("click",nn),l.shortcutsBackdrop&&l.shortcutsBackdrop.addEventListener("click",nn),l.memoryOpen&&l.memoryOpen.addEventListener("click",Nt),l.memoryClose&&l.memoryClose.addEventListener("click",Ht),l.memoryBackdrop&&l.memoryBackdrop.addEventListener("click",Ht),l.memoryOverlaySave&&l.memoryOverlaySave.addEventListener("click",Un),l.memoryFilters&&l.memoryFilters.addEventListener("submit",(e=>{e.preventDefault(),it.query=l.memoryOverlayQuery.value.trim(),At(it.query)})),l.memoryFiltersClear&&l.memoryFiltersClear.addEventListener("click",(()=>{l.memoryOverlayQuery.value="",it.query="",it.source="",it.role="",Mt()})),l.keysClose&&l.keysClose.addEventListener("click",vo),l.keysBackdrop&&l.keysBackdrop.addEventListener("click",vo),l.keysDismiss&&l.keysDismiss.addEventListener("click",Co),l.keysGotoAegis&&l.keysGotoAegis.addEventListener("click",(()=>{vo(),ao(),lo(l.apiKeyInput),l.apiKeyInput&&l.apiKeyInput.focus(),l.apiKeyHint&&(l.apiKeyHint.textContent=`Missing: ${function(){const e=[];return!0!==de&&e.push("the AEGIS key"),!0!==ue&&e.push("your provider (BYOK) key"),e.join(" and ")}()}. This is the AEGIS account key — the same one the CLI reads from ~/.aegiscode/.env, so pasting it here configures both.`)})),l.keysGotoByok&&l.keysGotoByok.addEventListener("click",(()=>{vo(),uo()})),s&&(l.queueEnqueue&&l.queueEnqueue.addEventListener("click",We),l.queueDrain&&l.queueDrain.addEventListener("click",(()=>ze("one"))),l.queueProceed&&l.queueProceed.addEventListener("click",(()=>ze("all"))),l.queueStop&&l.queueStop.addEventListener("click",Ye),"function"==typeof s.onProgress&&s.onProgress(tt),"function"==typeof s.onChanged&&s.onChanged((()=>{!function(){if(s)if(Ge){if(null!=Ve)return;Ve=setTimeout(Qe,60)}else null!=Ve&&clearTimeout(Ve),Ve=setTimeout(Qe,60)}()})),l.queueClassSelect&&l.queueClassSelect.addEventListener("change",(()=>{localStorage.setItem(u,l.queueClassSelect.value),Oo(l.queueClassSelect.value)})),await je(),await async function(){if(!l.queueClassSelect)return;let e=[];try{e=await t.listClasses()||[]}catch(t){e=[],l.queueModelHint&&(l.queueModelHint.textContent=`listClasses failed: ${t&&t.message?t.message:t}`)}l.queueClassSelect.innerHTML="";for(const t of e){const e=document.createElement("option");e.value=t.class,e.textContent=t.configured?t.label:`${t.label} (not configured)`,l.queueClassSelect.appendChild(e)}const n=localStorage.getItem(u);n&&e.some((e=>e.class===n))&&(l.queueClassSelect.value=n),await Oo(l.queueClassSelect.value)}()),a&&(l.queueAuto&&l.queueAuto.addEventListener("change",(()=>et(l.queueAuto.checked))),l.queueAutoInterval&&l.queueAutoInterval.addEventListener("change",(()=>{l.queueAuto&&l.queueAuto.checked&&et(!0)})),await Ze()),Z=createTranscriptView({messages:l.messages,requestFrame:e=>requestAnimationFrame(e)}),Z.attachScrollVeto();let y=null;window.__aegisSmoke=Object.freeze({isScrolledUp:()=>Z.isScrolledUp(),metrics:()=>Z.metrics(),escapeDecision:()=>y&&"function"==typeof y.lastDecision?y.lastDecision():null,stopOutcome:()=>te}),y=bindEscapeInterrupt({doc:document,isOverlayOpen:rt,onOverlayEscape:()=>{if(Rt())_t();else if(jt())Vt();else if(zt())Zt();else if(en())nn();else if(cn())pn();else if(wn())Mn();else if(Hn())In();else if(lt())vo();else{if(dt&&"function"==typeof dt.close)try{return void dt.close()}catch(e){}Ht()}},hasPendingTurn:()=>!!T,stopTurn:ne}),l.accountBanner&&e.onAccountStatus&&(e.onAccountStatus(ge),e.accountStatus().then(ge).catch((e=>console.warn("account status unavailable",e))),l.accountRetryBtn.addEventListener("click",(()=>ve(l.accountRetryBtn))),l.keysAccountRetry&&l.keysAccountRetry.addEventListener("click",(()=>ve(l.keysAccountRetry)))),l.updateBanner&&e.onUpdateStatus&&(e.onUpdateStatus(he),e.updateStatus().then(he).catch((()=>{})),l.updateDownloadBtn.addEventListener("click",(()=>{l.updateDownloadBtn.disabled=!0,Promise.resolve(e.downloadUpdate()).then((e=>{e&&e.status&&he(e)})).catch((()=>{})).finally((()=>{l.updateDownloadBtn.disabled=!1}))})),l.updateRestartBtn.addEventListener("click",(()=>{e.quitAndInstallUpdate()})),l.updateRetryBtn&&e.checkForUpdates&&l.updateRetryBtn.addEventListener("click",(()=>{l.updateRetryBtn.disabled=!0,Promise.resolve(e.checkForUpdates()).then(he).catch((()=>{})).finally((()=>{l.updateRetryBtn.disabled=!1}))})),l.updateLaterBtn.addEventListener("click",(()=>{fe=pe&&pe.status,l.updateBanner.hidden=!0}))),l.messages.querySelector(".msg, .chatflow")||eo(),xn({kind:"conversations"}),await Io(),await Po(),await async function(){if(o)try{Se(await o.status())}catch(e){l.quickLauncherHint.textContent=`status failed: ${e&&e.message?e.message:e}`}}(),await async function(){if(l.confirmMode&&e.getConfirmMode)try{$e(await e.getConfirmMode())}catch(e){l.confirmModeHint.textContent=`status failed: ${e&&e.message?e.message:e}`}}(),await async function(){if(l.planMode&&e.getPermissionMode)try{Ne(await e.getPermissionMode())}catch(e){l.planModeHint&&(l.planModeHint.textContent=`status failed: ${e&&e.message?e.message:e}`)}}(),await async function(){if(l.permRulesList&&e.permRulesList)try{Be(await e.permRulesList())}catch(e){Be({ok:!1,reason:e&&e.message||String(e)})}}(),await Oe(),await os(),await ls(),Ce(),Wo("sessions"),l.memoryQuietFloor&&(l.memoryQuietFloor.textContent=String(st)),St("");try{!function(){if(window.aegisProviderToolbar&&l.ptList)if(ut=window.aegisProviderToolbar.mount({list:l.ptList,count:l.ptCount,search:l.ptSearch,hint:l.ptHint,onSelect:ft}),l.ptRefresh&&l.ptRefresh.addEventListener("click",(()=>{pt(!0)})),"function"==typeof IntersectionObserver&&l.ptList.closest("section")){const e=new IntersectionObserver((t=>{t.some((e=>e.isIntersecting))&&(e.disconnect(),pt(!1))}));e.observe(l.ptList.closest("section"))}else pt(!1)}()}catch(e){l.ptHint&&(l.ptHint.textContent=`provider list unavailable: ${e&&e.message||e}`)}if(l.companionDismiss&&l.companionDismiss.addEventListener("click",(()=>{localStorage.setItem(ht,JSON.stringify({day:window.aegisCompanion?window.aegisCompanion.dayKey(new Date):"",id:l.companionCard.dataset.messageId||""})),l.companionCard.hidden=!0})),gt(),window.aegisFingerprint)try{dt=window.aegisFingerprint.mount({api:e,getSessionId:()=>O}),dt.refresh().catch((()=>{}))}catch(e){const t=l.fpCardStatus;t&&(t.textContent=`authorship panel unavailable: ${e&&e.message||e}`)}}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",Ns):Ns()}();
@@ -1,29 +1,40 @@
1
- # aegiscode — the terminal host
1
+ # aegiscode — the assistant in your terminal
2
2
 
3
- `aegiscode` in your shell — the command-line version of AEGIS One. The same
4
- tool surface the Claude Code plugin exposes over MCP, plus a terminal instead of
5
- an editor — built on the same two shared pieces and no others:
3
+ `aegiscode` is the command-line version of AEGIS One. You type what you want in
4
+ plain English — *"why does the build fail?"*, *"rename this function
5
+ throughout"*, *"summarise what changed this week"* — and it reads your files,
6
+ runs commands, edits code and answers. It is the same assistant, in a terminal
7
+ window instead of a window with buttons.
6
8
 
7
- | Shared piece | What it is |
8
- |---|---|
9
- | `client/aegis.js` | The thin transport. Holds the API key, speaks HTTP/SSE. No brain logic. |
10
- | `mcp/tools.js` | The tool registry — names, JSON schemas, result formatting. |
11
- | `desktop/renderer/usage.js` | The token-usage → number mapping, shared with the GUI so the two can never disagree. |
12
- | `desktop/lib/local/` | The agent-loop engine — persistent-shell exec, read/write/edit/glob/grep, Task subagents. The CLI runs the same loop the GUI does, scoped to the AEGIS class. |
9
+ There is nothing to configure before you start and no project to set up.
13
10
 
14
- Routing, model tiers, memory and billing all stay behind aegiscloud.org.
11
+ **You need two things:**
12
+
13
+ 1. **[Node.js 22 or newer](https://nodejs.org/en/download)** — the runtime that
14
+ runs the app. On macOS or Windows the installer is a double-click; on Linux
15
+ use your package manager. Check yours with `node -v`.
16
+ 2. **A free AEGIS key** from <https://aegiscloud.org> — this is what lets it
17
+ think. You paste it once, in step 2 below.
18
+
19
+ If you have never used a terminal before: it is the plain window where you type
20
+ commands and press Enter. On macOS it is called **Terminal**; on Windows,
21
+ **PowerShell**. Open it and type the grey boxes below exactly as written.
15
22
 
16
23
  ## Quick start
17
24
 
18
25
  Four steps, in order. Everything past this section is the fuller reference for
19
26
  each one.
20
27
 
21
- **1. Install** — requires Node 22+.
28
+ **1. Install** — needs Node 22+ (see above if you are not sure).
22
29
 
23
30
  ```bash
24
31
  npm install -g aegiscode
25
32
  ```
26
33
 
34
+ `npm` comes with Node.js. `-g` means *"install this so I can run it from any
35
+ folder"*. This one line downloads the app and puts the `aegiscode` command on
36
+ your machine.
37
+
27
38
  **2. Log in** — get a key at <https://aegiscloud.org> if you don't have one.
28
39
 
29
40
  ```bash
@@ -56,7 +67,7 @@ product, so they are one name now:
56
67
 
57
68
  | Name | Status |
58
69
  |---|---|
59
- | `aegiscode` | **this host**, v6.0.0. Installs a single binary, `aegiscode`. |
70
+ | `aegiscode` | **this host**. Installs a single command, `aegiscode`. Run `aegiscode version` for the version you have. |
60
71
  | `aegis-terminal` | deprecated — the 0.1.x spelling of this package, folded into `aegiscode`. |
61
72
  | `aegiscode-cli` | 4.0.3, an earlier name of this CLI's predecessor line. Untouched. |
62
73
  | `aegis-cli` | 0.4.8 (unrelated). |
@@ -249,22 +260,28 @@ launch, and an explicit flag (`-m`, `--light`) always outranks the stored value.
249
260
 
250
261
  In a session, plain text is a prompt. `/help` lists commands, grouped by
251
262
  category, the way the reference does. The registry is that client's, ported
252
- command for command — 87 entries across nine categories:
263
+ command for command — 96 entries across eight categories:
253
264
 
254
265
  | Category | Commands |
255
266
  |---|---|
256
- | Session & context | `/schedule` `/clear` `/compact` `/context` `/todos` `/config` `/exit` `/recap` `/resume` `/rewind` `/agents` `/status` `/teleport` `/version` `/new` `/skills` `/multiyolo` `/multi` `/research` `/debate` |
257
- | Workspace | `/run` `/build` `/cd` `/init` `/clone` |
258
- | Model & behavior | `/ping` `/effort` `/model` `/models` `/model-add` `/model-rm` `/theme` `/terminal` `/vim` `/permissions` `/hooks` `/credentials` `/install-github-app` `/thinking` `/mcp` `/memory` `/memory-deep` `/confirm` `/automode` *(alias `/yolo`)* `/router` `/class` |
259
- | Data | `/copy` `/cost` `/export` `/tokens` `/sync` |
260
- | Auth | `/login` `/logout` `/key` `/byok` `/byok-set` `/byok-rm` `/byok-key` `/byok-rm-key` |
261
- | Support | `/help` `/doctor` `/upgrade` `/troubleshooting` `/feedback` `/bug` `/issue` `/onboarding` `/shell-completion` `/terminal-setup` `/pr-comments` `/prs` `/review` `/benchmark` `/billing` `/topup` `/cloud` `/gmail` `/release-notes` |
267
+ | Session & context | `/schedule` `/clear` `/undo` `/compact` `/context` `/todos` `/config` `/exit` `/recap` `/resume` `/rewind` `/agents` `/status` `/teleport` `/version` `/new` `/skills` `/multiyolo` `/multi` `/research` `/debate` |
268
+ | Workspace | `/run` `/build` `/cd` `/sandbox` `/init` `/clone` |
269
+ | Model & behavior | `/ping` `/effort` `/model` `/theme` `/terminal` `/vim` `/permissions` `/hooks` `/credentials` `/install-github-app` `/thinking` `/mcp` `/memory` `/memory-deep` `/confirm` `/automode` *(alias `/yolo`)* `/router` `/class` `/models` `/model-add` `/model-discover` `/model-rm` |
270
+ | Data | `/copy` `/cost` `/export` `/tokens` `/sync` `/drive` |
271
+ | Auth | `/login` `/logout` `/key` `/byok` `/byok-set` `/byok-rm` `/byok-list` `/byok-key` `/byok-rm-key` |
272
+ | Support | `/help` `/license` `/credits` `/doctor` `/upgrade` `/troubleshooting` `/feedback` `/bug` `/issue` `/onboarding` `/shell-completion` `/terminal-setup` `/pr-comments` `/prs` `/review` `/benchmark` `/billing` `/topup` `/cloud` `/gmail` `/release-notes` |
262
273
  | Fun | `/radio` `/waifu` |
263
274
  | Aegis plugin | `/aegis-status` `/aegis-ask` `/aegis-recall` `/aegis-remember` `/aegis-council` `/aegis-print` `/aegis-multi` `/tool` `/aegis-import` |
264
275
 
276
+ There are 96 commands in eight categories; the ninth category in the registry,
277
+ `Custom`, holds none by default. `/yolo` is an **alias** of `/automode`, not a
278
+ command of its own — it never appears as its own row.
279
+
265
280
  The table above is generated from `cli/src/commands.js` (`COMMANDS` +
266
- `CATEGORIES`), which is the only authority on what exists — a hand-kept copy is
267
- how it came to claim 75 entries while the code held 84 before this port.
281
+ `CATEGORIES`), which is the only authority on what exists, and
282
+ `test/readme-claims.test.mjs` asserts that every name here matches the registry
283
+ exactly. A hand-kept copy is how it came to claim 75 entries while the code held
284
+ 84 before this port.
268
285
 
269
286
  `/help` shows the live list with hints; aliases are searchable in the `/`
270
287
  palette exactly as they are there (`/ask` → `/aegis-ask`, `?` → `/help`,
@@ -647,7 +664,7 @@ alternate-screen frame of header rule, transcript viewport, spinner/effort line,
647
664
  input line and status line, driven by a raw key stream.
648
665
 
649
666
  ```
650
- ╭───────────────────────────── AEGIS Code v6.3.0 ─────────────────────────────╮
667
+ ╭────────────────────────── AEGIS Code v<version> ────────────────────────────╮
651
668
  ❯ summarise what changed in the token accounting
652
669
  ● Three things changed, and one of them was costing you money:
653
670
 
@@ -717,6 +734,18 @@ node cli/scripts/demo.mjs # from a source checkout
717
734
 
718
735
  ## Design notes
719
736
 
737
+ **Four shared pieces, and no others.** The CLI is not a second implementation;
738
+ it is the same parts the other faces use:
739
+
740
+ | Shared piece | What it is |
741
+ |---|---|
742
+ | `client/aegis.js` | The thin transport. Holds the API key, speaks HTTP/SSE. No brain logic. |
743
+ | `mcp/tools.js` | The tool registry — names, JSON schemas, result formatting. |
744
+ | `desktop/renderer/usage.js` | The token-usage → number mapping, shared with the GUI so the two can never disagree. |
745
+ | `desktop/lib/local/` | The agent-loop engine — persistent-shell exec, read/write/edit/glob/grep, Task subagents. The CLI runs the same loop the GUI does, scoped to the AEGIS class. |
746
+
747
+ Routing, model tiers, memory and billing all stay behind aegiscloud.org.
748
+
720
749
  **It looks like the reference on purpose.** The gold/coral/lavender palette,
721
750
  the `✦`-studded welcome mark (mascot, crescent moon and diving whale), the `❯`
722
751
  prompt, the `⎿` hook rows and the `✻` spinner line are the reference's
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "7.0.42",
4
+ "version": "7.0.44",
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,4 +1,4 @@
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
- import{readdirSync as s}from"node:fs";import{spawnSync as t}from"node:child_process";import{dirname as e,join as o,resolve as r}from"node:path";import{fileURLToPath as n}from"node:url";const i=r(e(n(import.meta.url)),"..","..","test"),a=s(i).filter((s=>/^cli-.*\.test\.mjs$/.test(s))).sort();0===a.length&&(process.stderr.write(`no cli-*.test.mjs found in ${i}\n`),process.exit(1));const c=[],p=[];for(const s of a){const e=o(i,s);process.stdout.write(`\n── ${s} ${"─".repeat(Math.max(0,60-s.length))}\n`);const r=t(process.execPath,[e],{stdio:"inherit"});0===r.status?p.push(s):c.push({f:s,status:r.status,signal:r.signal})}if(process.stdout.write(`\n${"═".repeat(64)}\n`),process.stdout.write(`cli suite: ${p.length}/${a.length} files passed\n`),c.length){process.stdout.write(`\nFAILED (${c.length}):\n`);for(const{f:s,status:t,signal:e}of c)process.stdout.write(` ✗ ${s}${e?` (signal ${e})`:` (exit ${t})`}\n`);process.exit(1)}
4
+ import{readdirSync as s}from"node:fs";import{spawnSync as t}from"node:child_process";import{dirname as e,join as o,resolve as r}from"node:path";import{fileURLToPath as n}from"node:url";const i=r(e(n(import.meta.url)),"..","..","test"),a=s(i).filter((s=>/^cli-.*\.test\.mjs$/.test(s))).sort();0===a.length&&(process.stderr.write(`no cli-*.test.mjs found in ${i}\n`),process.exit(1));const c=[],p=[],l=["AEGIS_REDUCED_MODE","AEGIS_SKIP_PERMISSIONS","AEGISONE_SKIP_PERMISSIONS","AEGIS_NO_PROVENANCE_CHECK","AEGIS_SKIP_PROVENANCE","AEGIS_NO_INTERLOCK"],E={...process.env};for(const s of l)delete E[s];for(const s of a){const e=o(i,s);process.stdout.write(`\n── ${s} ${"─".repeat(Math.max(0,60-s.length))}\n`);const r=t(process.execPath,[e],{stdio:"inherit",env:E});0===r.status?p.push(s):c.push({f:s,status:r.status,signal:r.signal})}if(process.stdout.write(`\n${"═".repeat(64)}\n`),process.stdout.write(`cli suite: ${p.length}/${a.length} files passed\n`),c.length){process.stdout.write(`\nFAILED (${c.length}):\n`);for(const{f:s,status:t,signal:e}of c)process.stdout.write(` ✗ ${s}${e?` (signal ${e})`:` (exit ${t})`}\n`);process.exit(1)}