aegisone 1.0.45 → 1.0.47
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 +1 -1
- package/bin/aegis.js +1 -1
- package/package.json +1 -1
- package/src/doctor.js +1 -1
- package/src/producthelp.js +3 -0
- package/vendor/cli/README.md +1 -1
- package/vendor/cli/package.json +1 -1
- package/vendor/desktop/README.md +5 -2
- package/vendor/desktop/package.json +2 -2
- package/vendor/desktop/renderer/app.js +3 -3
- package/vendor/desktop/renderer/index.html +0 -6
- package/vendor/desktop/renderer/style.css +1 -8
- package/vendor/desktop/vendor/faces/cli/README.md +1 -1
- package/vendor/desktop/vendor/faces/cli/package.json +1 -1
package/README.md
CHANGED
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"),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}const c=(o.argv||[]).indexOf("doctor");if(-1!==c&&!(o.argv||[]).slice(0,c).some((e=>!e.startsWith("-")))){const e=
|
|
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}))}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aegisone",
|
|
3
3
|
"productName": "AEGISONE",
|
|
4
|
-
"version": "1.0.
|
|
4
|
+
"version": "1.0.47",
|
|
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",
|
package/src/doctor.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const path=require("node:path"),fs=require("node:fs"),crypto=require("node:crypto"),EXIT=Object.freeze({OK:0,WARN:1,BROKEN:2}),FACE_PACKAGES=Object.freeze([Object.freeze({dir:"cli",package:"aegiscode"}),Object.freeze({dir:"desktop",package:"aegis-desktop"})]),BUNDLE_FACES=Object.freeze([Object.freeze({face:"cli",root:"cli",staged:"one/vendor/cli"}),Object.freeze({face:"desktop",root:"desktop",staged:"one/vendor/desktop"})]);function oneDir(){return path.resolve(__dirname,"..")}function repoDir(){return path.resolve(__dirname,"..","..")}function homeHint(e){const t=e||{};return t.AEGISCODE_HOME||t.AEGIS_HOME||null}function defaultFs(){return{exists:e=>{try{return fs.existsSync(e)}catch{return!1}},readFile:e=>{try{return fs.readFileSync(e,"utf8")}catch(e){if(e&&("ENOENT"===e.code||"EISDIR"===e.code))return null;throw e}},hashFile:e=>crypto.createHash("sha256").update(fs.readFileSync(e)).digest("hex"),listFiles:(e,t)=>listFiles(e,void 0===t?e:t)}}function listFiles(e,t){const n=[],r=e=>{let s;try{s=fs.readdirSync(e,{withFileTypes:!0})}catch{return}for(const o of s){if("node_modules"===o.name||".git"===o.name)continue;const s=path.join(e,o.name);o.isDirectory()?r(s):n.push(path.relative(t,s).split(path.sep).join("/"))}};return r(e),n.sort()}function defaultElectronPaths(e,t){const n=t||{},r=homeHint(e)||path.join(e&&e.HOME?e.HOME:"",".aegiscode");return{electron:void 0!==n.electron?n.electron:null,desktopMain:void 0!==n.desktopMain?n.desktopMain:null,userData:void 0!==n.userData?n.userData:r,keychain:void 0!==n.keychain?n.keychain:path.join(r,"settings.json")}}function defaultRegistry(){let e=null;const t=()=>{if(e)return e;const t=[path.join(repoDir(),"client","update.js"),path.join(oneDir(),"vendor","cli","vendor","client","update.js")];for(const n of t)try{e=require(n);break}catch{}return e};return{check(e){const n=t();return n&&"function"==typeof n.updateNotice?n.updateNotice(e||{}):{latest:null,behind:!1,reason:"unavailable"}},plan(e){const n=t();return n&&"function"==typeof n.updatePlan?n.updatePlan(e||{}):null}}}function defaultStorePath(e){try{const t=require(path.join(repoDir(),"client","prefs.js"));if("function"==typeof t.prefsFile)return t.prefsFile(e)}catch{}const t=homeHint(e)||path.join(e&&e.HOME||"",".aegiscode");return path.join(t,"preferences.json")}function defaultCredentials(){let e=null;return{resolve(t){if(!e)try{e=require(path.join(repoDir(),"client","credentials.js"))}catch{e=null}if(!e||"function"!=typeof e.resolveApiKey)return{key:"",source:"none",from:""};try{return e.resolveApiKey(t||{})}catch{return{key:"",source:"none",from:""}}}}}function vendorPairs(e){const{exists:t}=e,n=[];for(const{face:r,root:s,staged:o}of BUNDLE_FACES){const a=path.join(e.root,o),i=e.listFiles(a,a);for(const a of i){const i=[];if(a.startsWith("vendor/")){const e=a.slice(7);if(i.push(e),i.push(path.join(s,e)),"selfhost.js"===e&&i.push(path.join("one","src","selfhost.js")),"desktop"===r){const t=path.basename(e);for(const e of["client","mcp","covenant","commands","skills","tools","hosts"])i.push(path.join(e,t));i.push(t)}}else i.push(path.join(s,a)),i.push(a);const c=i.find((n=>t(path.join(e.root,n))))||null;n.push({face:r,staged:path.join(o,a),source:c,candidates:i})}}return n}function checkVendor(e,t){const n=t||vendorPairs(e),r=[],s=[];let o=0,a=0;for(const t of n){if(!e.exists(path.join(e.root,t.staged)))continue;if(a+=1,!t.source){r.push(t.staged);continue}let n,i;try{n=e.hashFile(path.join(e.root,t.source)),i=e.hashFile(path.join(e.root,t.staged))}catch(e){s.push({staged:t.staged,source:t.source,error:String(e&&e.message||e)});continue}n===i?o+=1:s.push({staged:t.staged,source:t.source})}return{staged:a,matched:o,mismatch:s,missingSource:r,stale:n.length>0&&0===a,checked:n.length}}function readJson(e,t){const n=path.join(e.root,t);if(!e.exists(n))return{ok:!1,missing:!0,value:null,path:t};let r;try{r=e.readFile(n)}catch(e){return{ok:!1,unreadable:!0,value:null,path:t,error:String(e&&e.message||e)}}if(null==r)return{ok:!1,missing:!0,value:null,path:t};try{return{ok:!0,value:JSON.parse(r),path:t}}catch(e){return{ok:!1,unreadable:!0,value:null,path:t,error:String(e&&e.message||e)}}}function resolveSeams(e){const t=e||{},n=t.env||{},r=defaultFs(),s=t||{};return{root:t.root||repoDir(),platform:t.platform||"linux",env:n,exists:s.exists||r.exists,readFile:s.readFile||r.readFile,hashFile:s.hashFile||r.hashFile,listFiles:s.listFiles||r.listFiles,credentials:t.credentials||defaultCredentials(),storePath:t.storePath||defaultStorePath(n),registry:t.registry||defaultRegistry(),electronPaths:t.electronPaths||defaultElectronPaths(n,t),updateCache:t.updateCache,saveUpdateCache:t.saveUpdateCache,now:"number"==typeof t.now?t.now:0,guiRequested:Boolean(t.guiRequested),guiImplied:t.guiImplied,vendorPairs:t.vendorPairs}}function diagnose(e){const t=resolveSeams(e),n=[],r=(e,t)=>n.push({level:"broken",code:e,detail:t}),s=(e,t)=>n.push({level:"warn",code:e,detail:t}),o=readJson(t,"one/package.json"),a=o.ok?{name:o.value.name||"aegisone",version:String(o.value.version||"")}:{name:"aegisone",version:""};o.ok||r("product-unreadable","one/package.json "+(o.unreadable?"is unreadable":"is missing"));let i=null;try{i=require("./release.js").deriveFaceVersions(a.version)}catch(e){i=null,o.ok&&r("product-version-invalid",`${a.version}: ${String(e&&e.message||e)}`)}const c={};for(const{dir:e,package:n}of FACE_PACKAGES){const s=readJson(t,`${e}/package.json`),o=s.ok?String(s.value.version||""):"",l=i&&i[n]?i[n].version:null;s.ok?l&&o!==l&&r("version-mismatch",`${n} is ${o}, product ${a.version} derives ${l}`):r("face-unreadable",`${e}/package.json ${s.unreadable?"is unreadable":"is missing"}`),c[n]={dir:e,version:o,expected:l,ok:Boolean(l&&o===l)}}let l={key:"",source:"none",from:""};try{l=t.credentials.resolve({env:t.env})||l}catch{l={key:"",source:"none",from:""}}const u=t.electronPaths||{};let d=l.key?"env"===l.source?"env":(l.source,"env-file"):"none";if(!l.key&&u.keychain&&t.exists(u.keychain)){const e=(()=>{try{return t.readFile(u.keychain)}catch{return null}})();e&&/encrypt|safeStorage/i.test(e)&&(d="keychain")}"none"===d&&s("no-credential","no credential found (env, credentials.json, or the OS keychain)");const h={path:t.storePath,exists:!1,readable:null,legacy:null};try{h.exists=t.exists(t.storePath)}catch{h.exists=!1}let p,f=h.path;if(h.exists){let e=null;try{e=t.readFile(h.path)}catch(e){h.readable=!1,r("store-unreadable",`${h.path}: ${String(e&&e.message||e)}`)}if(null===h.readable)if(null==e)h.readable=!1,r("store-unreadable",`${h.path} exists but could not be read`);else try{const t=JSON.parse(e);h.readable=!0,h.legacy=t&&t.version||null}catch(e){h.readable=!1,r("store-unreadable",`${h.path} is not valid JSON: ${String(e&&e.message||e)}`)}f=path.basename(h.path)}h.display=f;try{p=checkVendor(t,t.vendorPairs)}catch(e){p={staged:0,matched:0,mismatch:[],missingSource:[],stale:!1,checked:0,error:String(e&&e.message||e)},r("vendor-unreadable",p.error)}for(const e of p.mismatch)r("vendor-hash-mismatch",`${e.staged} differs from ${e.source||"its source"}`);for(const e of p.missingSource)r("vendor-source-missing",`${e} has no source to be re-derived from`);p.stale&&s("vendor-stale","the ONE bundle has never been staged (one/vendor is empty) — run `npm run predist`");const g={channel:"npm",current:a.version,latest:null,behind:!1,reason:null,checkedAt:null,cached:!0,action:"none",applier:"npm",instruction:null};try{const e=t.registry.check({current:a.version,cache:t.updateCache,save:t.saveUpdateCache,now:t.now})||{};g.latest=e.latest||null,g.behind=Boolean(e.behind),g.reason=e.reason||null}catch(e){g.reason="unavailable",g.error=String(e&&e.message||e)}try{const e=t.registry.plan({current:a.version,latest:g.latest,behind:g.behind});e&&(g.action=e.action,g.applier=e.applier,g.instruction=e.instruction)}catch{}g.behind&&s("update-available",`${g.current} → ${g.latest} (${g.instruction||"run the channel updater"})`);const v=u&&u.electron||null;t.guiRequested&&!v&&r("gui-without-electron","--gui was requested but Electron is not installed — use --tui");const m=n.filter((e=>"broken"===e.level)).length,y=n.filter((e=>"warn"===e.level)).length,b=m?EXIT.BROKEN:y?EXIT.WARN:EXIT.OK;return{report:{aegis:"one",status:m?"broken":y?"warn":"healthy",exitCode:b,product:a,faces:c,credential:{source:d,found:Boolean(l.key),from:l.key?l.from:""},store:{path:h.path,exists:h.exists,readable:h.exists?!0===h.readable:null},vendor:{staged:p.staged,matched:p.matched,mismatched:p.mismatch.length,missingSource:p.missingSource.length,stale:p.stale},update:g,gui:{requested:Boolean(t.guiRequested),electron:v||null,usable:Boolean(v)&&(!t.guiImplied||t.guiImplied)},problems:n},code:b}}function render(e){const t=[];t.push(`aegis doctor — ${e.status} (exit ${e.exitCode})`),t.push(` product ${e.product.name} ${e.product.version}`);for(const[r,s]of Object.entries(e.faces)){const e=s.ok?"":` (expected ${s.expected||"unknown"})`;t.push(` ${n=r,14,String(n)+" ".repeat(Math.max(0,14-String(n).length))} ${s.version||"unknown"}${e}`)}var n;t.push(` credential ${e.credential.source}`),t.push(` shared store ${e.store.path} ${e.store.exists?e.store.readable?"(readable)":"(unreadable)":"(absent)"}`),t.push(` vendor ${e.vendor.staged} staged, ${e.vendor.matched} matching, ${e.vendor.mismatched} mismatched, ${e.vendor.missingSource} without a source`+(e.vendor.stale?" (never staged)":""));const r=e.update;if(t.push(" update "+(r.behind?`${r.current} → ${r.latest}`:`${r.current} is current`)+` (next: ${r.action}${r.instruction?` — ${r.instruction}`:""})`),t.push(" window face "+(e.gui.electron?`Electron at ${e.gui.electron}`:"not installed")),e.problems.length){t.push(" problems:");for(const n of e.problems)t.push(` ${"broken"===n.level?"✗":"!"} ${n.code}: ${n.detail}`)}return t.join("\n")+"\n"}function wantsGui(e,t){return!!(Array.isArray(e)?e:[]).includes("--gui")||"gui"===(t||{}).AEGISONE_FACE}function main(e,t){const n=t||{},r=Array.isArray(e)?e:[],s=n.stdout||process.stdout,o=n.env||process.env||{},a=Object.assign({},n,{env:o,guiRequested:wantsGui(r,o)}),{report:i,code:c}=diagnose(a),l=r.includes("--json")?JSON.stringify(i)+"\n":render(i);try{s.write(l)}catch{}return c}module.exports={EXIT:EXIT,FACE_PACKAGES:FACE_PACKAGES,wantsGui:wantsGui,diagnose:diagnose,render:render,main:main,vendorPairs:vendorPairs,resolveSeams:resolveSeams},require.main===module&&(process.exitCode=main(process.argv.slice(2)));
|
|
3
|
+
"use strict";const path=require("node:path"),fs=require("node:fs"),crypto=require("node:crypto"),EXIT=Object.freeze({OK:0,WARN:1,BROKEN:2}),FACE_PACKAGES=Object.freeze([Object.freeze({dir:"cli",package:"aegiscode"}),Object.freeze({dir:"desktop",package:"aegis-desktop"})]),BUNDLE_FACES=Object.freeze([Object.freeze({face:"cli",root:"cli",staged:"one/vendor/cli"}),Object.freeze({face:"desktop",root:"desktop",staged:"one/vendor/desktop"})]);function oneDir(){return path.resolve(__dirname,"..")}function repoDir(){return path.resolve(__dirname,"..","..")}function layoutOf(e,t){const n=t=>{try{return Boolean(e.exists(t))}catch{return!1}};if(t){const e=!n(path.join(t,"one","package.json"));return{root:t,installed:e,facePrefix:e?["vendor"]:[]}}const r=repoDir(),o=!n(path.join(r,"one","package.json"));return{root:o?oneDir():r,installed:o,facePrefix:o?["vendor"]:[]}}function inLayout(e,t){if(!e.installed)return t;const n=t.split("/");if("one"===n[0]){const e=n.slice(1).join("/");return"src/selfhost.js"===e?"vendor/desktop/vendor/selfhost.js":("vendor/cli"===e||e.startsWith("vendor/"),e)}return"cli"===n[0]||"desktop"===n[0]?path.posix.join("vendor",t).split(path.sep).join("/"):path.posix.join("vendor","cli","vendor",t).split(path.sep).join("/")}function homeHint(e){const t=e||{};return t.AEGISCODE_HOME||t.AEGIS_HOME||null}function defaultFs(){return{exists:e=>{try{return fs.existsSync(e)}catch{return!1}},readFile:e=>{try{return fs.readFileSync(e,"utf8")}catch(e){if(e&&("ENOENT"===e.code||"EISDIR"===e.code))return null;throw e}},hashFile:e=>crypto.createHash("sha256").update(fs.readFileSync(e)).digest("hex"),listFiles:(e,t)=>listFiles(e,void 0===t?e:t)}}function listFiles(e,t){const n=[],r=e=>{let o;try{o=fs.readdirSync(e,{withFileTypes:!0})}catch{return}for(const s of o){if("node_modules"===s.name||".git"===s.name)continue;const o=path.join(e,s.name);s.isDirectory()?r(o):n.push(path.relative(t,o).split(path.sep).join("/"))}};return r(e),n.sort()}function defaultElectronPaths(e,t){const n=t||{},r=homeHint(e)||path.join(e&&e.HOME?e.HOME:"",".aegiscode");return{electron:void 0!==n.electron?n.electron:null,desktopMain:void 0!==n.desktopMain?n.desktopMain:null,userData:void 0!==n.userData?n.userData:r,keychain:void 0!==n.keychain?n.keychain:path.join(r,"settings.json")}}function defaultRegistry(e){let t=null;const n=()=>{if(t)return t;const n=e&&e.layout?e.layout:{root:repoDir(),installed:!1},r=[path.join(n.root,"client","update.js"),path.join(n.root,"vendor","cli","vendor","client","update.js")];for(const e of r)try{t=require(e);break}catch{}return t};return{check(e){const t=n();return t&&"function"==typeof t.updateNotice?t.updateNotice(e||{}):{latest:null,behind:!1,reason:"unavailable"}},plan(e){const t=n();return t&&"function"==typeof t.updatePlan?t.updatePlan(e||{}):null}}}function defaultStorePath(e,t){try{const n=t&&t.layout?t.layout:{root:repoDir(),installed:!1},r=require(path.join(n.root,"client","prefs.js"));if("function"==typeof r.prefsFile)return r.prefsFile(e)}catch{}const n=homeHint(e)||path.join(e&&e.HOME||"",".aegiscode");return path.join(n,"preferences.json")}function defaultCredentials(e){let t=null;return{resolve(n){if(!t)try{const n=e&&e.layout?e.layout:{root:repoDir(),installed:!1};t=require(path.join(n.root,"client","credentials.js"))}catch{t=null}if(!t||"function"!=typeof t.resolveApiKey)return{key:"",source:"none",from:""};try{return t.resolveApiKey(n||{})}catch{return{key:"",source:"none",from:""}}}}}function vendorPairs(e){const{exists:t}=e,n=[];if((e.layout||{installed:!1,facePrefix:[]}).installed)return n;for(const{face:r,root:o,staged:s}of BUNDLE_FACES){const a=path.join(e.root,s),i=e.listFiles(a,a);for(const a of i){const i=[];if(a.startsWith("vendor/")){const e=a.slice(7);if(i.push(e),i.push(path.join(o,e)),"selfhost.js"===e&&i.push(path.join("one","src","selfhost.js")),"desktop"===r){const t=path.basename(e);for(const e of["client","mcp","covenant","commands","skills","tools","hosts"])i.push(path.join(e,t));i.push(t)}}else i.push(path.join(o,a)),i.push(a);const l=i.find((n=>t(path.join(e.root,n))))||null;n.push({face:r,staged:path.join(s,a),source:l,candidates:i})}}return n}function layoutsInstalled(e){return Boolean(e&&e.installed)}function checkVendor(e,t){const n=t||vendorPairs(e),r=[],o=[];let s=0,a=0;const i=e.layout||{installed:!1,facePrefix:[]};if(layoutsInstalled(i)){for(const t of BUNDLE_FACES){const n=path.join(e.root,inLayout(i,t.staged));e.exists(n)&&(a+=e.listFiles(n,n).length)}return{staged:a,matched:0,mismatch:o,missingSource:r,stale:0===a,checked:0}}for(const t of n){if(!e.exists(path.join(e.root,t.staged)))continue;if(a+=1,!t.source){r.push(t.staged);continue}let n,i;try{n=e.hashFile(path.join(e.root,t.source)),i=e.hashFile(path.join(e.root,t.staged))}catch(e){o.push({staged:t.staged,source:t.source,error:String(e&&e.message||e)});continue}n===i?s+=1:o.push({staged:t.staged,source:t.source})}return{staged:a,matched:s,mismatch:o,missingSource:r,stale:n.length>0&&0===a,checked:n.length}}function readJson(e,t){const n=path.join(e.root,t);if(!e.exists(n))return{ok:!1,missing:!0,value:null,path:t};let r;try{r=e.readFile(n)}catch(e){return{ok:!1,unreadable:!0,value:null,path:t,error:String(e&&e.message||e)}}if(null==r)return{ok:!1,missing:!0,value:null,path:t};try{return{ok:!0,value:JSON.parse(r),path:t}}catch(e){return{ok:!1,unreadable:!0,value:null,path:t,error:String(e&&e.message||e)}}}function resolveSeams(e){const t=e||{},n=t.env||{},r=defaultFs(),o=t||{},s=o.exists||r.exists,a=t.layout||layoutOf({exists:s,root:t.root},t.root),i=t.root||a.root,l={root:i,layout:Object.assign({},a,{root:i}),platform:t.platform||"linux",env:n,exists:s,readFile:o.readFile||r.readFile,hashFile:o.hashFile||r.hashFile,listFiles:o.listFiles||r.listFiles,electronPaths:t.electronPaths||defaultElectronPaths(n,t),updateCache:t.updateCache,saveUpdateCache:t.saveUpdateCache,now:"number"==typeof t.now?t.now:0,guiRequested:Boolean(t.guiRequested),guiImplied:t.guiImplied,vendorPairs:t.vendorPairs};return l.credentials=t.credentials||defaultCredentials(l),l.storePath=t.storePath||defaultStorePath(n,l),l.registry=t.registry||defaultRegistry(l),l}function diagnose(e){const t=resolveSeams(e),n=[],r=(e,t)=>n.push({level:"broken",code:e,detail:t}),o=(e,t)=>n.push({level:"warn",code:e,detail:t}),s=t.layout,a=inLayout(s,"one/package.json"),i=readJson(t,a),l=i.ok?{name:i.value.name||"aegisone",version:String(i.value.version||"")}:{name:"aegisone",version:""};i.ok||r("product-unreadable",`${a} ${i.unreadable?"is unreadable":"is missing"}`);let c=null;try{c=require("./release.js").deriveFaceVersions(l.version)}catch(e){c=null,i.ok&&r("product-version-invalid",`${l.version}: ${String(e&&e.message||e)}`)}const u={};for(const{dir:e,package:n}of FACE_PACKAGES){const o=inLayout(s,`${e}/package.json`),a=readJson(t,o),i=a.ok?String(a.value.version||""):"",d=c&&c[n]?c[n].version:null;a.ok?d&&i!==d&&r("version-mismatch",`${n} is ${i}, product ${l.version} derives ${d}`):r("face-unreadable",`${o} ${a.unreadable?"is unreadable":"is missing"}`),u[n]={dir:e,version:i,expected:d,ok:Boolean(d&&i===d)}}let d={key:"",source:"none",from:""};try{d=t.credentials.resolve({env:t.env})||d}catch{d={key:"",source:"none",from:""}}const h=t.electronPaths||{};let p=d.key?"env"===d.source?"env":(d.source,"env-file"):"none";if(!d.key&&h.keychain&&t.exists(h.keychain)){const e=(()=>{try{return t.readFile(h.keychain)}catch{return null}})();e&&/encrypt|safeStorage/i.test(e)&&(p="keychain")}"none"===p&&o("no-credential","no credential found (env, credentials.json, or the OS keychain)");const f={path:t.storePath,exists:!1,readable:null,legacy:null};try{f.exists=t.exists(t.storePath)}catch{f.exists=!1}let g,v=f.path;if(f.exists){let e=null;try{e=t.readFile(f.path)}catch(e){f.readable=!1,r("store-unreadable",`${f.path}: ${String(e&&e.message||e)}`)}if(null===f.readable)if(null==e)f.readable=!1,r("store-unreadable",`${f.path} exists but could not be read`);else try{const t=JSON.parse(e);f.readable=!0,f.legacy=t&&t.version||null}catch(e){f.readable=!1,r("store-unreadable",`${f.path} is not valid JSON: ${String(e&&e.message||e)}`)}v=path.basename(f.path)}f.display=v;try{g=checkVendor(t,t.vendorPairs)}catch(e){g={staged:0,matched:0,mismatch:[],missingSource:[],stale:!1,checked:0,error:String(e&&e.message||e)},r("vendor-unreadable",g.error)}for(const e of g.mismatch)r("vendor-hash-mismatch",`${e.staged} differs from ${e.source||"its source"}`);for(const e of g.missingSource)r("vendor-source-missing",`${e} has no source to be re-derived from`);g.stale&&(s.installed?r("vendor-missing","the ONE bundle is empty — reinstall aegisone"):o("vendor-stale","the ONE bundle has never been staged (one/vendor is empty) — run `npm run predist`"));const m={channel:"npm",current:l.version,latest:null,behind:!1,reason:null,checkedAt:null,cached:!0,action:"none",applier:"npm",instruction:null};try{const e=t.registry.check({current:l.version,cache:t.updateCache,save:t.saveUpdateCache,now:t.now})||{};m.latest=e.latest||null,m.behind=Boolean(e.behind),m.reason=e.reason||null}catch(e){m.reason="unavailable",m.error=String(e&&e.message||e)}try{const e=t.registry.plan({current:l.version,latest:m.latest,behind:m.behind});e&&(m.action=e.action,m.applier=e.applier,m.instruction=e.instruction)}catch{}m.behind&&o("update-available",`${m.current} → ${m.latest} (${m.instruction||"run the channel updater"})`);const y=h&&h.electron||null;t.guiRequested&&!y&&r("gui-without-electron","--gui was requested but Electron is not installed — use --tui");const b=n.filter((e=>"broken"===e.level)).length,k=n.filter((e=>"warn"===e.level)).length,j=b?EXIT.BROKEN:k?EXIT.WARN:EXIT.OK;return{report:{aegis:"one",status:b?"broken":k?"warn":"healthy",exitCode:j,product:l,faces:u,credential:{source:p,found:Boolean(d.key),from:d.key?d.from:""},store:{path:f.path,exists:f.exists,readable:f.exists?!0===f.readable:null},vendor:{staged:g.staged,matched:g.matched,mismatched:g.mismatch.length,missingSource:g.missingSource.length,stale:g.stale,verifiable:!s.installed},update:m,gui:{requested:Boolean(t.guiRequested),electron:y||null,usable:Boolean(y)&&(!t.guiImplied||t.guiImplied)},problems:n},code:j}}function render(e){const t=[];t.push(`aegis doctor — ${e.status} (exit ${e.exitCode})`),t.push(` product ${e.product.name} ${e.product.version}`);for(const[r,o]of Object.entries(e.faces)){const e=o.ok?"":` (expected ${o.expected||"unknown"})`;t.push(` ${n=r,14,String(n)+" ".repeat(Math.max(0,14-String(n).length))} ${o.version||"unknown"}${e}`)}var n;t.push(` credential ${e.credential.source}`),t.push(` shared store ${e.store.path} ${e.store.exists?e.store.readable?"(readable)":"(unreadable)":"(absent)"}`),t.push(!1===e.vendor.verifiable?` vendor ${e.vendor.staged} staged (sources not shipped — not re-derivable here)`:` vendor ${e.vendor.staged} staged, ${e.vendor.matched} matching, ${e.vendor.mismatched} mismatched, ${e.vendor.missingSource} without a source`+(e.vendor.stale?" (never staged)":""));const r=e.update;if(t.push(" update "+(r.behind?`${r.current} → ${r.latest}`:`${r.current} is current`)+` (next: ${r.action}${r.instruction?` — ${r.instruction}`:""})`),t.push(" window face "+(e.gui.electron?`Electron at ${e.gui.electron}`:"not installed")),e.problems.length){t.push(" problems:");for(const n of e.problems)t.push(` ${"broken"===n.level?"✗":"!"} ${n.code}: ${n.detail}`)}return t.join("\n")+"\n"}function wantsGui(e,t){return!!(Array.isArray(e)?e:[]).includes("--gui")||"gui"===(t||{}).AEGISONE_FACE}function main(e,t){const n=t||{},r=Array.isArray(e)?e:[],o=n.stdout||process.stdout,s=n.env||process.env||{},a=Object.assign({},n,{env:s,guiRequested:wantsGui(r,s)}),{report:i,code:l}=diagnose(a),c=r.includes("--json")?JSON.stringify(i)+"\n":render(i);try{o.write(c)}catch{}return l}module.exports={EXIT:EXIT,FACE_PACKAGES:FACE_PACKAGES,wantsGui:wantsGui,diagnose:diagnose,render:render,main:main,vendorPairs:vendorPairs,resolveSeams:resolveSeams},require.main===module&&(process.exitCode=main(process.argv.slice(2)));
|
|
@@ -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 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};
|
package/vendor/cli/README.md
CHANGED
|
@@ -60,7 +60,7 @@ product, so they are one name now:
|
|
|
60
60
|
| `aegis-terminal` | deprecated — the 0.1.x spelling of this package, folded into `aegiscode`. |
|
|
61
61
|
| `aegiscode-cli` | 4.0.3, an earlier name of this CLI's predecessor line. Untouched. |
|
|
62
62
|
| `aegis-cli` | 0.4.8 (unrelated). |
|
|
63
|
-
| `aegis` (bin) | claimed
|
|
63
|
+
| `aegis` (bin) | was claimed twice — by `aegiscode-cli` (→ `bin/cli.js`) and by `aegis-desktop` (→ `bin/aegis.js`), so whichever installed last won and installing both failed with `EEXIST`. **Resolved:** `aegis-desktop`'s bin is now `aegis-desktop`, and `aegis` belongs to `aegisone` alone. |
|
|
64
64
|
|
|
65
65
|
Publishing this host as `aegiscode` moves the `latest` dist-tag for that name
|
|
66
66
|
onto it. The previous line (`aegiscode@5.x`, the earlier agent build) is
|
package/vendor/cli/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aegiscode",
|
|
3
3
|
"productName": "AEGIS Code",
|
|
4
|
-
"version": "7.0.
|
|
4
|
+
"version": "7.0.39",
|
|
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",
|
package/vendor/desktop/README.md
CHANGED
|
@@ -14,7 +14,7 @@ package is on npm:
|
|
|
14
14
|
|
|
15
15
|
```bash
|
|
16
16
|
npm install -g aegis-desktop # requires Node 22+
|
|
17
|
-
aegis
|
|
17
|
+
aegis-desktop # launch
|
|
18
18
|
```
|
|
19
19
|
|
|
20
20
|
Either way, on first launch:
|
|
@@ -26,7 +26,10 @@ Either way, on first launch:
|
|
|
26
26
|
3. Pick a model class from the picker at the bottom of the composer.
|
|
27
27
|
|
|
28
28
|
The published package is [`aegis-desktop`](https://www.npmjs.com/package/aegis-desktop)
|
|
29
|
-
on npm; this repo is its source.
|
|
29
|
+
on npm; this repo is its source. Its command is `aegis-desktop` — bare `aegis`
|
|
30
|
+
belongs to [`aegisone`](https://www.npmjs.com/package/aegisone), the product that
|
|
31
|
+
dispatches between the window and the terminal, and the two can now be installed
|
|
32
|
+
side by side. If you only want one command for both faces, install `aegisone`. Two of the three classes bill your AEGIS
|
|
30
33
|
account — either the pooled margin, or the BYOK handling fee on top of your own
|
|
31
34
|
provider key; the free **Local** class runs on your own hardware and bills
|
|
32
35
|
nobody.
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "aegis-desktop",
|
|
3
3
|
"productName": "aegis one",
|
|
4
4
|
"desktopName": "aegis-desktop",
|
|
5
|
-
"version": "1.0.
|
|
5
|
+
"version": "1.0.39",
|
|
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",
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
"main": "main.js",
|
|
13
13
|
"homepage": "https://aegiscloud.org",
|
|
14
14
|
"bin": {
|
|
15
|
-
"aegis": "bin/aegis.js"
|
|
15
|
+
"aegis-desktop": "bin/aegis.js"
|
|
16
16
|
},
|
|
17
17
|
"files": [
|
|
18
18
|
"main.js",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
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",companionGo:"companion-go",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",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 G="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.",V=[{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"),oo(),Vn(),Yn(),function(){const e=document.getElementById("keys-overlay");if(!e)return;let t=!1;try{t="on"===localStorage.getItem(go)}catch{}t||null===de?e.hidden=!0:(vo(),Boolean(T)?ko():!0!==de||!0!==ue?Co():ko())}()}let pe=null,fe=null;function he(e){if(!l.updateBanner)return;pe=e;try{Ct()}catch{}const t=e&&e.status;if(!t||"idle"===t||"disabled"===t||"checking"===t||"up-to-date"===t||"unavailable"===t||t===fe)return void(l.updateBanner.hidden=!0);let n="",o=!1,s=!1,a=!1;const i=e.version?`v${e.version} `:"";if("available"===t)n=e.command?e.commandIsSentence?`Update ${i}available. ${e.command}`:`Update ${i}available — run: ${e.command}`:`Update ${i}available.`,o=!!e.canDownload,o&&(n=`Update ${i}available.`);else if("downloading"===t)n=`Downloading update${"number"==typeof e.progress?` (${Math.round(e.progress)}%)`:""}…`;else if("downloaded"===t)n=`Update ${i}downloaded — restart to install.`,s=!0;else{if("error"!==t)return void(l.updateBanner.hidden=!0);n=`Update check failed: ${e.error||"unknown error"}`,e.transient&&(n+=" — will retry automatically."),a=!0}l.updateBannerText.textContent=n,l.updateDownloadBtn.hidden=!o,l.updateRestartBtn.hidden=!s,l.updateRetryBtn&&(l.updateRetryBtn.hidden=!a),l.updateBanner.hidden=!1}let ye=null;function ge(e){ye=e&&"no-key"===e.status?e.reason:null,vo(),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 To(),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 ${kt(e.startedAt)}`:"working");else if("pending"===e.status)e.attempts&&t.push(`${e.attempts} attempt${1===e.attempts?"":"s"}`),e.created&&t.push(`queued ${kt(e.created)}`);else{e.attempts>1&&t.push(`${e.attempts} attempts`);const n=e.finishedAt||e.startedAt||e.created;n&&t.push(kt(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 Ge=null,Ve=!1;async function Qe(){if(Ge=null,!Ve){Ve=!0;try{await je()}finally{Ve=!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:Fo(),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}${No(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=Ro());const s=O,a=e&&e.model||"",i=e&&e.class||"",r=i||a?[i?i.toUpperCase():"",a].filter(Boolean).join(" · "):void 0;xo("user",t),xo("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(Ot())return!0;if(Vt())return!0;if(Jt())return!0;if(nn())return!0;if(dn())return!0;if(Sn())return!0;if(In())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),Oo(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}let gt=null;function vt(){gt=null,l.companionGo&&(l.companionGo.hidden=!0,l.companionGo.textContent="")}function Ct(){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 l.companionCard.hidden=!0,void vt();const n=window.aegisCompanion.pickMessage(yt(),e);if(!n||!n.text)return l.companionCard.hidden=!0,void vt();l.companionText.textContent=n.text,l.companionCard.dataset.kind=n.kind,l.companionCard.dataset.messageId=n.id,l.companionCard.hidden=!1;const o=function(e){switch(e){case"update-ready":return{label:"Open update",go(){fe&&(fe=null,he(pe)),mo(l.updateRestartBtn||l.updateBanner)}};case"connect":return{label:"Add key",go(){ro(),mo(l.apiKeyInput),l.apiKeyInput&&l.apiKeyInput.focus()}};case"provider-key":return{label:"Add key",go:()=>po()};case"tip-tools":return{label:"Open Tool approvals",go(){ro(),ao(l.confirmMode)}};case"queue":return{label:"Open Automations",go(){Promise.all([Ze().catch((()=>{})),je().catch((()=>{}))]).then((()=>co()))}};case"memory-held":return{label:"Open inspector",go:()=>Bt()};default:return null}}(n.id);gt=o?o.go:null,l.companionGo&&(l.companionGo.hidden=!o,l.companionGo.textContent=o?o.label:"")}function kt(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 bt(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 wt(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(bt):[];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 xt(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 St(e,t,n,o,s){if(!e)return;const a=null!=t.used?xt(t.used):"?",i=null!=t.limit?xt(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 Et(e,t){St(l.memoryHint,e,t)}async function $t(e){l.memoryHint.textContent="searching…";const t=await wt(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"===zo&&Yo("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?Et(t.upgrade,"cloud memory needs an active plan"):t.local?l.memoryHint.textContent=Lt:l.memoryHint.textContent=t.error||""}const Lt="offline — showing this device’s saved copy";function qt(e,t){const n=document.createElement("span");return n.className="mem-chip"+(t?` ${t}`:""),n.textContent=e,n}function Mt(e){const t=document.createElement("li");t.className="mem-card";const n=document.createElement("div");n.className="mem-card-head",n.appendChild(qt(e.source,"src")),e.role&&n.appendChild(qt(e.role,"role")),null!=e.importance&&n.appendChild(qt(`imp ${e.importance}`,"imp")),e.sentiment&&n.appendChild(qt(e.sentiment,"sent")),e.summary&&n.appendChild(qt("summary","flag"));const o=document.createElement("span");o.className="mem-card-meta";const s=[],a=kt(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(qt(t,"pill"));t.appendChild(e)}return i.addEventListener("click",(()=>{window.getSelection&&String(window.getSelection())||t.classList.toggle("expanded")})),t}function At(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 Nt(){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",At("source")],["role","role",At("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,Nt()})),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?xt(it.upgrade.used):"?",s=null!=it.upgrade.limit?xt(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(Mt(e))}async function Ht(e){it.loading=!0,it.error="",it.upgrade=null,it.local=!1,Nt();const t=await wt(e,at);it.entries=t.entries,it.error=t.error,it.upgrade=t.upgrade,it.local=!0===t.local,it.loading=!1,Nt()}function Bt(){l.memoryOverlay&&(En({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="",Nt(),Ht(it.query),l.memoryOverlayQuery&&l.memoryOverlayQuery.focus())}function It(){l.memoryOverlay&&(l.memoryOverlay.hidden=!0,document.body.classList.remove("memory-open"),l.memoryOpen&&l.memoryOpen.focus())}let Rt=null,Tt="";function Ot(){return!!l.sessionOverlay&&!l.sessionOverlay.hidden}function Ft(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(kt(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=()=>{jt(),us(e.id)};return n.addEventListener("click",r),n.addEventListener("keydown",(e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),r())})),n}function Dt(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=kt(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=()=>{jt(),Bt(),l.memoryOverlayQuery&&Rt&&(l.memoryOverlayQuery.value=Rt,it.query=Rt,Nt(),Ht(Rt))};return t.addEventListener("click",a),t.addEventListener("keydown",(e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),a())})),t}function Pt(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 Ut(e){const t=String(null==e?"":e).trim();if(Rt=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===Rt&&(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"!==Tt,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(Pt("Sessions",r.length));for(const e of r)l.sessionList.appendChild(Ft(e,t))}if(o.length){l.sessionList.appendChild(Pt("Memory",o.length));for(const e of o)l.sessionList.appendChild(Dt(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 _t(e){l.sessionOverlay&&(Tt="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"===Tt?"memory only — clear to search everything":""),Ut(""))}function Kt(){_t("memory")}function jt(){l.sessionOverlay&&(l.sessionOverlay.hidden=!0,document.body.classList.remove("memory-open"))}let Gt=null;function Vt(){return!!l.importOverlay&&!l.importOverlay.hidden}function Qt(){l.importOverlay&&(l.importOverlay.hidden=!0,document.body.classList.remove("memory-open"),l.importSessionBtn&&l.importSessionBtn.focus())}function Wt(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 zt(){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{Gt=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(Wt(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")}(Gt),Gt}())}async function Yt(){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)}}
|
|
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",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(fo)}catch{}t||null===de?e.hidden=!0:(ho(),Boolean(T)?go():!0!==de||!0!==ue?yo():go())}()}let pe=null,fe=null;function he(e){if(!l.updateBanner)return;pe=e;try{gt()}catch{}const t=e&&e.status;if(!t||"idle"===t||"disabled"===t||"checking"===t||"up-to-date"===t||"unavailable"===t||t===fe)return void(l.updateBanner.hidden=!0);let n="",o=!1,s=!1,a=!1;const i=e.version?`v${e.version} `:"";if("available"===t)n=e.command?e.commandIsSentence?`Update ${i}available. ${e.command}`:`Update ${i}available — run: ${e.command}`:`Update ${i}available.`,o=!!e.canDownload,o&&(n=`Update ${i}available.`);else if("downloading"===t)n=`Downloading update${"number"==typeof e.progress?` (${Math.round(e.progress)}%)`:""}…`;else if("downloaded"===t)n=`Update ${i}downloaded — restart to install.`,s=!0;else{if("error"!==t)return void(l.updateBanner.hidden=!0);n=`Update check failed: ${e.error||"unknown error"}`,e.transient&&(n+=" — will retry automatically."),a=!0}l.updateBannerText.textContent=n,l.updateDownloadBtn.hidden=!o,l.updateRestartBtn.hidden=!s,l.updateRetryBtn&&(l.updateRetryBtn.hidden=!a),l.updateBanner.hidden=!1}let ye=null;function ge(e){ye=e&&"no-key"===e.status?e.reason:null,ho(),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 Bo(),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:Ro(),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}${qo(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=Ho());const s=O,a=e&&e.model||"",i=e&&e.class||"",r=i||a?[i?i.toUpperCase():"",a].filter(Boolean).join(" · "):void 0;ko("user",t),ko("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),Io(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"===Go&&Qo("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(),cs(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 es()}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 Jt(){return!!l.creditsOverlay&&!l.creditsOverlay.hidden}function Xt(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 Zt(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(Xt("Vendored third-party code",t.code)),Array.isArray(t.fonts)&&t.fonts.length&&l.creditsBody.appendChild(Xt("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 en(){l.creditsOverlay&&(En({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 Zt(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=""),Zt(t)}())}function tn(){l.creditsOverlay&&(l.creditsOverlay.hidden=!0,document.body.classList.remove("memory-open"))}function nn(){return!!l.shortcutsOverlay&&!l.shortcutsOverlay.hidden}function on(){l.shortcutsOverlay&&(En({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 sn(){l.shortcutsOverlay&&(l.shortcutsOverlay.hidden=!0,document.body.classList.remove("memory-open"))}let an=[],rn=-1;function cn(){return{cliFace:void 0!==e&&e&&"function"==typeof e.openCliFace}}function ln(){return globalThis.AegisPaletteFilter||null}function dn(){return!!l.paletteOverlay&&!l.paletteOverlay.hidden}function un(e){if(!l.paletteList)return;const t=ln(),n=function(){const e=globalThis.AegisCommands;return e&&Array.isArray(e.COMMANDS)?e.availableCommands(e.COMMANDS,cn()):[]}();an=t?t.filterCommands(n,e):n.slice(),rn=t?t.initialIndex(an):an.length?0:-1,l.paletteList.replaceChildren();for(let e=0;e<an.length;e+=1){const t=an[e],n=document.createElement("li");n.className="palette-row"+(e===rn?" is-active":""),n.id=`palette-row-${e}`,n.setAttribute("role","option"),n.setAttribute("aria-selected",e===rn?"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(),rn=e,_n(t.action)})),l.paletteList.appendChild(n)}l.paletteEmpty&&(l.paletteEmpty.hidden=an.length>0),mn()}function mn(){if(!l.paletteList)return;const e=l.paletteList.children;for(let t=0;t<e.length;t+=1){const n=t===rn;e[t].classList.toggle("is-active",n),e[t].setAttribute("aria-selected",n?"true":"false")}l.paletteInput&&(rn>=0?l.paletteInput.setAttribute("aria-activedescendant",`palette-row-${rn}`):l.paletteInput.removeAttribute("aria-activedescendant"));const t=e[rn];t&&"function"==typeof t.scrollIntoView&&t.scrollIntoView({block:"nearest"})}function pn(e){const t=ln();t&&(rn=t.moveIndex(rn,an.length,e),mn())}function fn(){l.paletteOverlay&&(l.paletteOverlay.hidden=!1,document.body.classList.add("memory-open"),l.paletteInput&&(l.paletteInput.value="",l.paletteInput.focus()),un(""))}function hn(){l.paletteOverlay&&(l.paletteOverlay.hidden=!0,document.body.classList.remove("memory-open"),an=[],rn=-1)}function yn(){if(!l.side)return;const e=l.side.classList.toggle("is-collapsed");l.side.setAttribute("aria-hidden",e?"true":"false")}let gn={query:"",matches:[],index:-1,texts:[]},vn=AegisNavHistory.createHistory(),Cn=!1;function kn(){return globalThis.AegisFindInConversation||null}function bn(){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<gn.matches.length;e+=1){const o=gn.matches[e],s=gn.texts[o.textIndex];if(!s)continue;const a=document.createRange();a.setStart(s,o.start),a.setEnd(s,o.end),t.push(a),e===gn.index&&n.push(a)}t.length&&e.set("find-match",new Highlight(...t)),n.length&&e.set("find-match-current",new Highlight(...n))}function wn(e){const t=kn();if(!t)return;gn.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=gn.texts.map((e=>e.nodeValue||""));gn.matches=t.findMatches(n,gn.query,{caseSensitive:!1}),gn.index=gn.matches.length?0:-1,bn(),l.findCount&&(l.findCount.textContent=t.matchLabel(gn.index,gn.matches.length)),e&&xn()}function xn(){const e=gn.matches[gn.index];if(!e)return;const t=gn.texts[e.textIndex];if(!t)return;const n=t.parentElement;n&&"function"==typeof n.scrollIntoView&&n.scrollIntoView({block:"center",behavior:"smooth"})}function Sn(){return!!l.findBar&&!l.findBar.hidden}function En(e){Cn||(vn=AegisNavHistory.pushEntry(vn,e),$n())}function $n(){e.setNavState&&e.setNavState({back:AegisNavHistory.canGoBack(vn),forward:AegisNavHistory.canGoForward(vn)}).catch((()=>{}))}function Ln(e){if(e){Cn=!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?ro():"automations"===e.kind?co():"session"===e.kind&&e.id?us(e.id,{fromNav:!0}):"memory"===e.kind?Bt():"credits"===e.kind?en():"shortcuts"===e.kind?on():"keys"===e.kind?Co():lo()}finally{Cn=!1}}}function qn(){const e=AegisNavHistory.back(vn);e?(vn=e.state,Ln(e.entry),$n()):l.sessionsHint.textContent="already at the start of the history"}function Mn(){const e=AegisNavHistory.forward(vn);e?(vn=e.state,Ln(e.entry),$n()):l.sessionsHint.textContent="already at the newest place"}function An(){l.findBar&&(l.findBar.hidden=!1,l.findInput&&(l.findInput.focus(),"function"==typeof l.findInput.select&&l.findInput.select()),gn.query&&wn(!0))}function Nn(){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 Hn={kind:"",rows:[],index:-1,span:null,query:""};function Bn(){return globalThis.AegisComposerTriggers||null}function In(){return!!l.composerMenu&&!l.composerMenu.hidden}const Rn=new Set(["exportJson","toggleSidebar","keys","credits","find"]);function Tn(){Hn={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 On(){if(!l.composerMenuList)return;l.composerMenuList.replaceChildren();const e=Hn.rows;for(let t=0;t<e.length;t+=1){const n=e[t],o=document.createElement("li");o.className="composer-menu-row"+(t===Hn.index?" is-active":""),o.id=`composer-row-${t}`,o.setAttribute("role","option"),o.setAttribute("aria-selected",t===Hn.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(),Hn.index=t,Dn()})),l.composerMenuList.appendChild(o)}const t=l.composerMenuList.children[Hn.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"===Hn.kind?Hn.query?`nothing matches “${Hn.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 Fn(){const e=Bn(),t=l.prompt;if(!e||!t)return;const o=e.activeTrigger(t.value,t.selectionStart);if(!o)return void(In()&&Tn());const s={start:o.start,end:o.end};let a;if(Hn.kind=o.kind,Hn.span=s,Hn.query=o.query,"slash"===o.kind)a=e.rankRows(function(){const e=globalThis.AegisCommands;return e&&Array.isArray(e.COMMANDS)?e.availableCommands(e.COMMANDS,cn()).filter((e=>!Rn.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}Hn.rows=a,Hn.index=a.length?0:-1,On()}async function Dn(){const e=Hn.rows[Hn.index],t=l.prompt;if(!e||!t)return void Tn();const n=Hn.span,o=Hn.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(),Tn(),void _n(e.action);if(Tn(),"openSessionRow"===e.action&&e.session)return t.value=(s.slice(0,a)+r).replace(/\s{2,}/g," ").trimStart(),void us(e.session.id);if("stageMemory"===e.action&&e.memory){const n=e.memory,o=String(n.content||"");vs.some((e=>"text"===e.kind&&e.text===o))||(vs.push({kind:"text",name:n.scope?`memory: ${n.scope}`:"memory",path:"",size:o.length,mime:"text/plain",text:o,truncated:!1}),ws());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 Pn(e){const t=Bn();t&&Hn.rows.length&&(Hn.index=t.stepRow(Hn.rows.length,Hn.index,e),On())}function Un(e){const t=kn();t&&gn.matches.length&&(gn.index=t.stepMatch(gn.index,gn.matches.length,e),bn(),l.findCount&&(l.findCount.textContent=t.matchLabel(gn.index,gn.matches.length)),xn())}function _n(e){switch(hn(),e){case"newChat":return void ps();case"go-back":return void qn();case"go-forward":return void Mn();case"search":return void _t("");case"find":return void An();case"settings":return void ro();case"customizations":return ro(),void ao(l.confirmMode);case"automations":return void Promise.all([Ze().catch((()=>{})),je().catch((()=>{}))]).then((()=>co()));case"cli":return void(l.openCliFace&&l.openCliFace.click());case"import":return void(l.importSessionBtn&&l.importSessionBtn.click());case"exportMarkdown":return void ms("markdown");case"exportJson":return void ms("json");case"memory":return void Bt();case"fingerprint":return void(dt&&"function"==typeof dt.open&&dt.open());case"shortcuts":return void on();case"keys":return void Co();case"credits":return void en();case"toggleSidebar":return void yn();default:throw new Error(`palette: unknown action ${e}`)}}async function Kn(){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 Et(o.upgrade,"free plan limit reached"),void await jn();t.value="",l.memoryHint.textContent=o&&o.queued?"saved offline — syncs when AEGIS is reachable.":"saved.",await jn()}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 jn(){const e=l.memoryQuery?l.memoryQuery.value.trim():"";await $t(e),ct()&&await Ht(it.query)}function Gn(){const e=yt();return void 0===e.keyConfigured&&delete e.keyConfigured,e}function Vn(){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(Gn(),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 Qn="aegis.welcomeRowsDismissed";function Wn(){const e=window.aegisWelcomeRows;if(!e)return[];try{return e.parseDismissed(localStorage.getItem(Qn))}catch{return[]}}function zn(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":_t("");break;case"memory":Bt();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(Qn,t.withDismissed(Wn(),e))}catch{}Yn()}}(e.id))),t.appendChild(s),t}function Yn(){const t=document.getElementById("welcome-rows"),n=window.aegisWelcomeRows;if(!t||!n)return;const o=n.pickRows(function(){const t=Gn();return es.length&&(t.sessionCount=es.length),void 0!==e&&e&&"function"==typeof e.openCliFace&&(t.cliAvailable=!0),t}(),Wn());if(t.innerHTML="",o.length){for(const e of o)t.appendChild(zn(e));t.hidden=!1}else t.hidden=!0}const Jn="aegis.welcomeAiLine",Xn=120,Zn=200;function eo(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 to(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 no(){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?"}(),Vn(),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(Jn)||"null")}catch{t=null}return t&&"string"==typeof t.text&&t.text?t.day!==eo(e)?null:t.text:null}(n);if(o)return e.textContent=o,e.dataset.kind="ai",void(e.hidden=!1);const s=Gn(),a=l.classSelect&&l.classSelect.value?l.classSelect.value:"aegis",i=l.modelSelect&&l.modelSelect.value?l.modelSelect.value:"",r={class:a,prompt:to(s),maxTokens:Xn,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>Zn){const e=n.slice(0,Zn),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(Jn,JSON.stringify({day:eo(n),text:u}))}catch{}}}();const n=document.getElementById("welcome-byok");n&&n.addEventListener("click",po);const o=document.getElementById("welcome-cloud");o&&o.addEventListener("click",fo);const s=document.getElementById("welcome-dismiss");s&&s.addEventListener("click",yo),oo(),Yn()}function oo(){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,so("welcome-cloud",!n),so("welcome-cloud-note",!n),so("welcome-byok",!o),so("welcome-byok-note",!o)}function so(e,t){const n=document.getElementById(e);n&&(n.hidden=t)}function ao(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=()=>t.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop,o=()=>n.scrollTo({top:Math.max(0,e()),behavior:"smooth"});o();const s=Date.now()+3e3;let a=e();const i=()=>{const t=e();Math.abs(t-a)>=1&&(a=t,o()),Date.now()<s&&requestAnimationFrame(i)};requestAnimationFrame(i)}else try{t.scrollIntoView({block:"start",behavior:"smooth"})}catch{t.scrollIntoView()}t.classList.add("flash"),setTimeout((()=>t.classList.remove("flash")),1200)}let io=!1;function ro(){l.settingsView&&(l.settingsView.hidden=!1,l.settingsView.scrollTop=0),l.automationsView&&(l.automationsView.hidden=!0),l.chatCanvas&&(l.chatCanvas.hidden=!0),uo(l.railSettings),En({kind:"settings"}),function(){if(io)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),io=!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 co(){l.automationsView&&(l.automationsView.hidden=!1,l.automationsView.scrollTop=0),l.settingsView&&(l.settingsView.hidden=!0),l.chatCanvas&&(l.chatCanvas.hidden=!0),uo(l.railAutomations),En({kind:"automations"})}function lo(){l.settingsView&&(l.settingsView.hidden=!0),l.automationsView&&(l.automationsView.hidden=!0),l.chatCanvas&&(l.chatCanvas.hidden=!1),uo(null),En({kind:"conversations"})}function uo(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 mo(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 po(){if(ho("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"))),ro(),mo(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 mo(l.apiKeyInput);const e=l.settingsList?l.settingsList.querySelector('.setting-row input[type="password"]'):null;e&&e.focus()}function fo(){ho("cloud"),ro(),mo(l.apiKeyInput),l.apiKeyInput&&l.apiKeyInput.focus()}function ho(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 yo(){try{localStorage.setItem(y,"on")}catch{}const e=document.getElementById("welcome-connect");e&&(e.hidden=!0)}const go="aegis.keysPopupDismissed";function vo(){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 Co(){l.keysOverlay&&(vo(),l.keysOverlay.hidden&&(En({kind:"keys"}),l.keysOverlay.hidden=!1,document.body.classList.add("keys-open")))}function ko(){l.keysOverlay&&(l.keysOverlay.hidden=!0,document.body.classList.remove("keys-open"))}function bo(){try{localStorage.setItem(go,"on")}catch{}ko()}function wo(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 xo(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",wo(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=No(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 So(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 Io(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 Ao(t.tool):void Ho(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:`${G}\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)";wo(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 Eo(){return R||(R=xo("assistant",""),R.classList.remove("pending"),R)}function $o(e,{cancellable:t}={}){if(l.send.disabled=e,l.prompt.disabled=e,e){R=xo("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 Lo=72,qo=new Set(["editFile","writeFile","Edit","Write","MultiEdit"]),Mo=new Map;function Ao(e){if(!e||!qo.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&&Mo.set(e.id,n)}function No(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>Lo?`${i.slice(0,Lo-1)}…`:i;return`→ ${t}${r?` ${r}`:""} ${o}`}function Ho(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?Mo.get(n.id):null;if(i){Mo.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=No(n),a.appendChild(r),a}function Bo(e){return e.startsWith("@@")?"diff-hunk":e.startsWith("+++")||e.startsWith("---")?"diff-file":e.startsWith("+")?"diff-add":e.startsWith("-")?"diff-del":"diff-ctx"}function Io(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=Bo(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 Ro(){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 To(){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 Oo(l.classSelect.value)}async function Oo(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 Fo(){if(l.queueModelInput&&!l.queueModelInput.hidden){const e=l.queueModelInput.value.trim();if(e)return e}return l.queueModelSelect?l.queueModelSelect.value:""}async function Do(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 Po({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 Uo(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 _o(),await Oo(l.classSelect.value)}catch(e){l.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function _o(){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&&Uo(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",(()=>Uo(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",(()=>Qo(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(Po({provider:o,name:`BYOK: ${t.label||t.id}`,cfg:s,onSave:e=>Vo(o,e),onRemove:()=>Qo(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 _o(),await Oo(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 _o(),await Oo(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 _o(),await Oo(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 Ko()}catch(e){l.customStatus&&(l.customStatus.textContent=`custom provider: ${e&&e.message?e.message:e}`)}}async function Ko(){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 jo(){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 Ko(),void await Oo(l.classSelect.value).catch((()=>{}))}l.customModel&&(l.customModel.value=""),s(`saved ${e} with model ${o} — pick it under provider "byok", then the model.`),await Ko(),await _o(),await Oo(l.classSelect.value).catch((()=>{}))}async function Go(){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 Ko(),await _o(),await Oo(l.classSelect.value).catch((()=>{}))}async function Vo(e,n){l.settingsHint.textContent="saving…";try{const o={};n&&(o.key=n),await t.settings.set(e,o),l.settingsHint.textContent="saved.",await _o(),await Oo(l.classSelect.value)}catch(e){l.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function Qo(e){l.settingsHint.textContent="removing…";try{await t.settings.remove(e),l.settingsHint.textContent="removed.",await _o(),await Oo(l.classSelect.value)}catch(e){l.settingsHint.textContent=`remove failed: ${e&&e.message?e.message:e}`}}const Wo=["sessions","memory"];let zo="sessions";function Yo(e){const t=Wo.includes(e)?e:"sessions";zo=t;for(const e of Wo){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 Jo=new Set,Xo=3;function Zo(e){if(!e||!e.id||!0===e.named||Jo.has(e.id))return;const t=(Array.isArray(e.messages)?e.messages:[]).find((e=>e&&"user"===e.role&&e.content));if(!t)return;if(Jo.add(e.id),"function"!=typeof n.nameSession)return;const o=l.classSelect?l.classSelect.value:"";n.nameSession({sessionId:e.id,prompt:t.content,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=Xo;for(const n of e){if(t<=0)break;n&&!0!==n.named&&!Jo.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(as("no conversations yet"));if(!n.length)return void l.sessionsList.appendChild(as(`nothing matches “${String(e).trim()}”`));const o=Date.now(),s=ns?ns.groupSessions(n,o):[{key:"all",label:"",sessions:n}];for(const e of s){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)l.sessionsList.appendChild(is(t,o))}}function as(e){const t=document.createElement("li");return t.className="empty",t.textContent=e,t}function is(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&&ps(),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",(()=>us(t.id))),s.addEventListener("keydown",(e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),us(t.id))})),s}function rs(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 cs(){try{rs(await n.status())}catch{rs(null)}}function ls(){"function"==typeof n.auto&&n.auto().then((e=>{e&&e.upgrade&&St(l.sessionsHint,e.upgrade,"queued memory is waiting on the free-plan cap","See what Pro covers →")})).catch((()=>{}))}async function ds(){l.syncNow.disabled=!0,l.sessionsHint.textContent="syncing…";try{const e=await n.push(),t=await n.pull();e.upgrade||t.upgrade?St(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 cs(),await os()}}function us(e,t){n.open(e).then((e=>{if(!e)return void(l.sessionsHint.textContent="session not found");l.messages.innerHTML="",t&&t.fromNav||En({kind:"session",id:e.id});const n=Array.isArray(e.messages)?e.messages:[];n.length||no();for(const t of n){const n="assistant"===t.role?"assistant":"system"===t.role?"system":"user";xo(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 ms(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 ps(){z(),gn={query:"",matches:[],index:-1,texts:[]},l.findInput&&(l.findInput.value=""),Nn(),Tn(),O&&t.clearApprovals(O).catch((()=>{})),no(),l.sessionsHint.textContent="",R=null,T=null,J=null,X=null,O=null,F=[],Q=0,K(null)}function fs(e){e&&("open"===e.action&&e.sessionId?us(e.sessionId):"new"===e.action&&(ps(),e.prompt&&(l.prompt.value=e.prompt,l.prompt.focus())))}async function hs(){const e=l.prompt.value.trim(),o=vs.length?vs.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=vs,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;vs=[],Cs=[],ws();const d=++Y;J=d,X=null,xo("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=Ro());const h=O;T=h,ko();const y=replayHistory(F);F.push({role:"user",content:o&&!bs()?qs(e,o):c}),$o(!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=Eo();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=Eo();return t.classList.remove("pending"),Io(t,e.approval,".body"),void ee({force:!0})}if(e&&e.rounds){const n=Eo();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 Ao(e.tool);b.push(e.tool);const t=Eo();return t.classList.remove("pending"),Ho(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),xo("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{}ls(),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",(()=>{So(V[Q%V.length],a,e)})),a.appendChild(i),t.appendChild(n),t.appendChild(a),l.messages.appendChild(t);for(const t of V.slice(0,2))So(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}`),xo("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{}ls()}else xo("assistant",`Error: ${t&&t.message?t.message:t}`,"request failed")}finally{$o(!1),J===d&&(J=null,T=null),os()}}let ys=!1;function gs(){const e=l.messages;e&&(ys=!0,e.scrollTo({top:e.scrollHeight,behavior:"smooth"}),l.scrollBottom&&(l.scrollBottom.hidden=!0))}let vs=[],Cs=[],ks=0;function bs(){return l.classSelect&&"pro"===l.classSelect.value}function ws(){const e=l.attachRow,t=l.attachNote;if(!e)return;e.textContent="";const n=vs.length+Cs.length;if(e.hidden=0===n,t&&(t.hidden=!0,t.textContent=""),n){for(const t of vs){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} · ${Ss(t.size)}${t.truncated?" (truncated)":""}`,n.appendChild(s),n.appendChild(xs((()=>{vs=vs.filter((e=>e!==t)),ws()}))),e.appendChild(n)}for(const t of Cs){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(xs((()=>{Cs=Cs.filter((e=>e!==t)),ws()}))),e.appendChild(n)}if(t&&bs()){const e=vs.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 xs(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 Ss(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 Es(t){const n=(t||"").split(/[\\/]/).pop()||t;if(vs.length>=8)return Cs.push({path:t,name:n,reason:"at most 8 files per message"}),void ws();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 Cs.push({path:t,name:n,reason:o&&o.reason||"not attached"}),void ws();vs.some((e=>e.path===o.attachment.path))||(vs.push(o.attachment),ws())}const $s=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Ls(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 qs(e,t){const n=[],o="string"==typeof e?e:"";o.trim()&&n.push({type:"text",text:o});for(const e of t||[]){const t=Ls(e);"image"===e.kind&&e.dataUrl&&$s.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 Ms="aegis.onboardingSeen";async function As(){!function(){const t=document.getElementById("onboard-overlay");if(!t)return;let n=!1;try{n="1"===localStorage.getItem(Ms)}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(Ms,"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(),ro();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),Oo(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(ro(),mo(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",ps),l.railAutomations&&l.railAutomations.addEventListener("click",(async()=>{await Promise.all([Ze().catch((()=>{})),je().catch((()=>{}))]),co()})),l.automationsBack&&l.automationsBack.addEventListener("click",lo),l.railSettings&&l.railSettings.addEventListener("click",ro),l.settingsBack&&l.settingsBack.addEventListener("click",lo),l.importSessionBtn&&l.importSessionBtn.addEventListener("click",zt),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",Qt),l.importBackdrop&&l.importBackdrop.addEventListener("click",Qt),l.importSessionsBtn&&l.importSessionsBtn.addEventListener("click",Yt),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 St(n,s.upgrade,`import stopped after ${s.saved||0} entries`),void await jn();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 jn()}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(ps),e.onMenuSearch&&e.onMenuSearch((()=>_t(""))),e.onMenuSearchMemory&&e.onMenuSearchMemory(Kt),
|
|
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?so():"automations"===e.kind?ao():"session"===e.kind&&e.id?cs(e.id,{fromNav:!0}):"memory"===e.kind?Nt():"credits"===e.kind?Xt():"shortcuts"===e.kind?tn():"keys"===e.kind?yo():io()}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 cs(e.session.id);if("stageMemory"===e.action&&e.memory){const n=e.memory,o=String(n.content||"");hs.some((e=>"text"===e.kind&&e.text===o))||(hs.push({kind:"text",name:n.scope?`memory: ${n.scope}`:"memory",path:"",size:o.length,mime:"text/plain",text:o,truncated:!1}),Cs());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 ds();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 so();case"customizations":return so(),void function(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=()=>t.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop,o=()=>n.scrollTo({top:Math.max(0,e()),behavior:"smooth"});o();const s=Date.now()+3e3;let a=e();const i=()=>{const t=e();Math.abs(t-a)>=1&&(a=t,o()),Date.now()<s&&requestAnimationFrame(i)};requestAnimationFrame(i)}else try{t.scrollIntoView({block:"start",behavior:"smooth"})}catch{t.scrollIntoView()}t.classList.add("flash"),setTimeout((()=>t.classList.remove("flash")),1200)}(l.confirmMode);case"automations":return void Promise.all([Ze().catch((()=>{})),je().catch((()=>{}))]).then((()=>ao()));case"cli":return void(l.openCliFace&&l.openCliFace.click());case"import":return void(l.importSessionBtn&&l.importSessionBtn.click());case"exportMarkdown":return void ls("markdown");case"exportJson":return void ls("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 yo();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 Jo.length&&(t.sessionCount=Jo.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",lo);const o=document.getElementById("welcome-cloud");o&&o.addEventListener("click",uo);const s=document.getElementById("welcome-dismiss");s&&s.addEventListener("click",po),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)}let oo=!1;function so(){l.settingsView&&(l.settingsView.hidden=!1,l.settingsView.scrollTop=0),l.automationsView&&(l.automationsView.hidden=!0),l.chatCanvas&&(l.chatCanvas.hidden=!0),ro(l.railSettings),xn({kind:"settings"}),function(){if(oo)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),oo=!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 ao(){l.automationsView&&(l.automationsView.hidden=!1,l.automationsView.scrollTop=0),l.settingsView&&(l.settingsView.hidden=!0),l.chatCanvas&&(l.chatCanvas.hidden=!0),ro(l.railAutomations),xn({kind:"automations"})}function io(){l.settingsView&&(l.settingsView.hidden=!0),l.automationsView&&(l.automationsView.hidden=!0),l.chatCanvas&&(l.chatCanvas.hidden=!1),ro(null),xn({kind:"conversations"})}function ro(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 co(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 lo(){if(mo("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"))),so(),co(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 co(l.apiKeyInput);const e=l.settingsList?l.settingsList.querySelector('.setting-row input[type="password"]'):null;e&&e.focus()}function uo(){mo("cloud"),so(),co(l.apiKeyInput),l.apiKeyInput&&l.apiKeyInput.focus()}function mo(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 po(){try{localStorage.setItem(y,"on")}catch{}const e=document.getElementById("welcome-connect");e&&(e.hidden=!0)}const fo="aegis.keysPopupDismissed";function ho(){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 yo(){l.keysOverlay&&(ho(),l.keysOverlay.hidden&&(xn({kind:"keys"}),l.keysOverlay.hidden=!1,document.body.classList.add("keys-open")))}function go(){l.keysOverlay&&(l.keysOverlay.hidden=!0,document.body.classList.remove("keys-open"))}function vo(){try{localStorage.setItem(fo,"on")}catch{}go()}function Co(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 ko(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",Co(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=qo(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 bo(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 No(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 Lo(t.tool):void Mo(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)";Co(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 wo(){return R||(R=ko("assistant",""),R.classList.remove("pending"),R)}function xo(e,{cancellable:t}={}){if(l.send.disabled=e,l.prompt.disabled=e,e){R=ko("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 So=72,Eo=new Set(["editFile","writeFile","Edit","Write","MultiEdit"]),$o=new Map;function Lo(e){if(!e||!Eo.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&&$o.set(e.id,n)}function qo(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>So?`${i.slice(0,So-1)}…`:i;return`→ ${t}${r?` ${r}`:""} ${o}`}function Mo(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?$o.get(n.id):null;if(i){$o.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=qo(n),a.appendChild(r),a}function Ao(e){return e.startsWith("@@")?"diff-hunk":e.startsWith("+++")||e.startsWith("---")?"diff-file":e.startsWith("+")?"diff-add":e.startsWith("-")?"diff-del":"diff-ctx"}function No(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=Ao(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 Ho(){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 Bo(){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 Io(l.classSelect.value)}async function Io(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 Ro(){if(l.queueModelInput&&!l.queueModelInput.hidden){const e=l.queueModelInput.value.trim();if(e)return e}return l.queueModelSelect?l.queueModelSelect.value:""}async function To(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 Oo({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 Fo(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 Do(),await Io(l.classSelect.value)}catch(e){l.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function Do(){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&&Fo(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",(()=>Fo(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",(()=>jo(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(Oo({provider:o,name:`BYOK: ${t.label||t.id}`,cfg:s,onSave:e=>Ko(o,e),onRemove:()=>jo(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 Do(),await Io(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 Do(),await Io(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 Do(),await Io(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 Po()}catch(e){l.customStatus&&(l.customStatus.textContent=`custom provider: ${e&&e.message?e.message:e}`)}}async function Po(){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 Uo(){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 Po(),void await Io(l.classSelect.value).catch((()=>{}))}l.customModel&&(l.customModel.value=""),s(`saved ${e} with model ${o} — pick it under provider "byok", then the model.`),await Po(),await Do(),await Io(l.classSelect.value).catch((()=>{}))}async function _o(){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 Po(),await Do(),await Io(l.classSelect.value).catch((()=>{}))}async function Ko(e,n){l.settingsHint.textContent="saving…";try{const o={};n&&(o.key=n),await t.settings.set(e,o),l.settingsHint.textContent="saved.",await Do(),await Io(l.classSelect.value)}catch(e){l.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function jo(e){l.settingsHint.textContent="removing…";try{await t.settings.remove(e),l.settingsHint.textContent="removed.",await Do(),await Io(l.classSelect.value)}catch(e){l.settingsHint.textContent=`remove failed: ${e&&e.message?e.message:e}`}}const Vo=["sessions","memory"];let Go="sessions";function Qo(e){const t=Vo.includes(e)?e:"sessions";Go=t;for(const e of Vo){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 Wo=new Set,zo=3;function Yo(e){if(!e||!e.id||!0===e.named||Wo.has(e.id))return;const t=(Array.isArray(e.messages)?e.messages:[]).find((e=>e&&"user"===e.role&&e.content));if(!t)return;if(Wo.add(e.id),"function"!=typeof n.nameSession)return;const o=l.classSelect?l.classSelect.value:"";n.nameSession({sessionId:e.id,prompt:t.content,class:o,model:ae()}).then((e=>{e&&es().catch((()=>{}))})).catch((()=>{}))}let Jo=[],Xo=null;const Zo="undefined"!=typeof window&&window.aegisLibrary||null;async function es(){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}`)}Jo=e;let t=zo;for(const n of e){if(t<=0)break;n&&!0!==n.named&&!Wo.has(n.id)&&(t-=1,Yo(n))}ts()}function ts(){if(!l.sessionsList)return;const e=l.sessionsFilter?l.sessionsFilter.value:"",t=Jo,n=Zo?Zo.filterSessions(e,t):t;if(l.sessionsCount&&(l.sessionsCount.textContent=Zo?Zo.countLabel(n.length,t.length):""),l.sessionsList.innerHTML="",!t.length)return void l.sessionsList.appendChild(ns("no conversations yet"));if(!n.length)return void l.sessionsList.appendChild(ns(`nothing matches “${String(e).trim()}”`));const o=Date.now(),s=Zo?Zo.groupSessions(n,o):[{key:"all",label:"",sessions:n}];for(const e of s){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)l.sessionsList.appendChild(os(t,o))}}function ns(e){const t=document.createElement("li");return t.className="empty",t.textContent=e,t}function os(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"),Xo&&t&&t.id===Xo)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(Xo=null,!o||o===(e&&e.title||""))return void ts();if("function"!=typeof n.rename)return l.sessionsHint.textContent="rename is unavailable in this build.",void ts();const s=Jo.find((t=>t&&t.id===e.id));s&&(s.title=o,s.named=!0),ts();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 es()}(e,t.value)):"Escape"===o.key&&(o.preventDefault(),Xo=null,ts())})),t.addEventListener("blur",(()=>{Xo===(e&&e.id)&&(Xo=null,ts())})),setTimeout((()=>{try{t.focus(),t.select()}catch{}}),0),t}(t)),s;const a=document.createElement("span");a.className="session-title",a.textContent=Zo?Zo.sessionTitle(t):t&&t.title||t&&t.id||"untitled",s.appendChild(a);const i=document.createElement("span");i.className="session-meta",i.textContent=Zo?Zo.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&&(Xo=e.id,ts())}(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=Zo?Zo.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&&ds(),l.sessionsHint.textContent=`deleted “${t}”`,await es()}}(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",(()=>cs(t.id))),s.addEventListener("keydown",(e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),cs(t.id))})),s}function ss(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 as(){try{ss(await n.status())}catch{ss(null)}}function is(){"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 rs(){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 as(),await es()}}function cs(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";ko(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 ls(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 ds(){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 us(e){e&&("open"===e.action&&e.sessionId?cs(e.sessionId):"new"===e.action&&(ds(),e.prompt&&(l.prompt.value=e.prompt,l.prompt.focus())))}async function ms(){const e=l.prompt.value.trim(),o=hs.length?hs.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=hs,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;hs=[],ys=[],Cs();const d=++Y;J=d,X=null,ko("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=Ho());const h=O;T=h,go();const y=replayHistory(F);F.push({role:"user",content:o&&!vs()?Es(e,o):c}),xo(!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=wo();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=wo();return t.classList.remove("pending"),No(t,e.approval,".body"),void ee({force:!0})}if(e&&e.rounds){const n=wo();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 Lo(e.tool);b.push(e.tool);const t=wo();return t.classList.remove("pending"),Mo(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),ko("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&&es().catch((()=>{}))})).catch((()=>{}))}catch{}is(),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",(()=>{bo(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))bo(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}`),ko("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{}is()}else ko("assistant",`Error: ${t&&t.message?t.message:t}`,"request failed")}finally{xo(!1),J===d&&(J=null,T=null),es()}}let ps=!1;function fs(){const e=l.messages;e&&(ps=!0,e.scrollTo({top:e.scrollHeight,behavior:"smooth"}),l.scrollBottom&&(l.scrollBottom.hidden=!0))}let hs=[],ys=[],gs=0;function vs(){return l.classSelect&&"pro"===l.classSelect.value}function Cs(){const e=l.attachRow,t=l.attachNote;if(!e)return;e.textContent="";const n=hs.length+ys.length;if(e.hidden=0===n,t&&(t.hidden=!0,t.textContent=""),n){for(const t of hs){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} · ${bs(t.size)}${t.truncated?" (truncated)":""}`,n.appendChild(s),n.appendChild(ks((()=>{hs=hs.filter((e=>e!==t)),Cs()}))),e.appendChild(n)}for(const t of ys){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(ks((()=>{ys=ys.filter((e=>e!==t)),Cs()}))),e.appendChild(n)}if(t&&vs()){const e=hs.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 ks(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 bs(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 ws(t){const n=(t||"").split(/[\\/]/).pop()||t;if(hs.length>=8)return ys.push({path:t,name:n,reason:"at most 8 files per message"}),void Cs();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 ys.push({path:t,name:n,reason:o&&o.reason||"not attached"}),void Cs();hs.some((e=>e.path===o.attachment.path))||(hs.push(o.attachment),Cs())}const xs=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Ss(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 Es(e,t){const n=[],o="string"==typeof e?e:"";o.trim()&&n.push({type:"text",text:o});for(const e of t||[]){const t=Ss(e);"image"===e.kind&&e.dataUrl&&xs.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 $s="aegis.onboardingSeen";async function Ls(){!function(){const t=document.getElementById("onboard-overlay");if(!t)return;let n=!1;try{n="1"===localStorage.getItem($s)}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($s,"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(),so();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),Io(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(so(),co(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",ds),l.railAutomations&&l.railAutomations.addEventListener("click",(async()=>{await Promise.all([Ze().catch((()=>{})),je().catch((()=>{}))]),ao()})),l.automationsBack&&l.automationsBack.addEventListener("click",io),l.railSettings&&l.railSettings.addEventListener("click",so),l.settingsBack&&l.settingsBack.addEventListener("click",io),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(ds),e.onMenuSearch&&e.onMenuSearch((()=>Pt(""))),e.onMenuSearchMemory&&e.onMenuSearchMemory(Ut),
|
|
6
6
|
// Help > Credits & licence… — the AGPL, the program notice and every vendored
|
|
7
|
-
e.onMenuCredits&&e.onMenuCredits(en),e.onMenuPalette&&e.onMenuPalette(fn),e.onMenuToggleSidebar&&e.onMenuToggleSidebar(yn),e.onMenuFind&&e.onMenuFind(An),e.onMenuGoBack&&e.onMenuGoBack(qn),e.onMenuGoForward&&e.onMenuGoForward(Mn),l.findInput&&(l.findInput.addEventListener("input",(()=>{gn.query=l.findInput.value,wn(!0)})),l.findInput.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),Un(e.shiftKey?-1:1))}))),l.findNext&&l.findNext.addEventListener("click",(()=>Un(1))),l.findPrev&&l.findPrev.addEventListener("click",(()=>Un(-1))),l.findClose&&l.findClose.addEventListener("click",Nn),l.paletteInput&&(l.paletteInput.addEventListener("input",(()=>un(l.paletteInput.value))),l.paletteInput.addEventListener("keydown",(e=>{if("ArrowDown"===e.key)return e.preventDefault(),void pn(1);if("ArrowUp"===e.key)return e.preventDefault(),void pn(-1);if("Enter"===e.key){const t=an[rn];if(!t)return;e.preventDefault(),_n(t.action)}}))),l.paletteBackdrop&&l.paletteBackdrop.addEventListener("click",hn),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((()=>ms("markdown"))),e.onMenuExportJson&&e.onMenuExportJson((()=>ms("json"))),e.onDeepLink&&e.onDeepLink(fs),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",ds),l.sessionsExport.addEventListener("click",(()=>ms("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",jo),l.customRemove&&l.customRemove.addEventListener("click",Go);for(const e of[l.customBaseUrl,l.customKey,l.customModel])e&&e.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),jo())}));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(ys){if(!(o<=24))return void(t.hidden=!0);ys=!1}t.hidden=o<=24}(e)}),l.scrollBottom&&l.scrollBottom.addEventListener("click",gs),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(),hs()})),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"))&&(ks+=1,document.body.classList.add("is-dropping"))})),window.addEventListener("dragleave",(()=>{ks=Math.max(0,ks-1),0===ks&&document.body.classList.remove("is-dropping")})),window.addEventListener("dragover",(e=>{e.dataTransfer&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")})),window.addEventListener("drop",(t=>{ks=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 Es(n):(Cs.push({name:t.name||"file",reason:"no path available"}),ws())}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",ws),ws()),l.prompt.addEventListener("keydown",(e=>{if(In()){if("ArrowDown"===e.key)return e.preventDefault(),void Pn(1);if("ArrowUp"===e.key)return e.preventDefault(),void Pn(-1);if(("Enter"===e.key||"Tab"===e.key)&&Hn.rows.length)return e.preventDefault(),void Dn()}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),l.composer.requestSubmit())})),l.prompt.addEventListener("input",(()=>{Fn().catch((()=>{}))})),l.prompt.addEventListener("click",(()=>{In()&&Fn().catch((()=>{}))})),l.tabSessions&&l.tabSessions.addEventListener("click",(()=>Yo("sessions"))),l.tabMemory&&l.tabMemory.addEventListener("click",(()=>Yo("memory"))),l.memorySearchForm.addEventListener("submit",(e=>{e.preventDefault(),$t(l.memoryQuery.value.trim())})),l.memorySaveBtn.addEventListener("click",Kn),l.sessionClose&&l.sessionClose.addEventListener("click",jt),l.sessionBackdrop&&l.sessionBackdrop.addEventListener("click",jt),l.sessionClear&&l.sessionClear.addEventListener("click",(()=>{l.sessionQuery&&(l.sessionQuery.value=""),Tt="",l.sessionHint&&(l.sessionHint.textContent=""),Ut(""),l.sessionQuery&&l.sessionQuery.focus()})),l.sessionFilters&&l.sessionFilters.addEventListener("submit",(e=>{e.preventDefault(),Ut(l.sessionQuery?l.sessionQuery.value:"")})),l.sessionQuery&&l.sessionQuery.addEventListener("input",(()=>{Ut(l.sessionQuery.value)})),l.creditsClose&&l.creditsClose.addEventListener("click",tn),l.creditsBackdrop&&l.creditsBackdrop.addEventListener("click",tn),l.shortcutsClose&&l.shortcutsClose.addEventListener("click",sn),l.shortcutsBackdrop&&l.shortcutsBackdrop.addEventListener("click",sn),l.memoryOpen&&l.memoryOpen.addEventListener("click",Bt),l.memoryClose&&l.memoryClose.addEventListener("click",It),l.memoryBackdrop&&l.memoryBackdrop.addEventListener("click",It),l.memoryOverlaySave&&l.memoryOverlaySave.addEventListener("click",Kn),l.memoryFilters&&l.memoryFilters.addEventListener("submit",(e=>{e.preventDefault(),it.query=l.memoryOverlayQuery.value.trim(),Ht(it.query)})),l.memoryFiltersClear&&l.memoryFiltersClear.addEventListener("click",(()=>{l.memoryOverlayQuery.value="",it.query="",it.source="",it.role="",Nt()})),l.keysClose&&l.keysClose.addEventListener("click",ko),l.keysBackdrop&&l.keysBackdrop.addEventListener("click",ko),l.keysDismiss&&l.keysDismiss.addEventListener("click",bo),l.keysGotoAegis&&l.keysGotoAegis.addEventListener("click",(()=>{ko(),ro(),mo(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",(()=>{ko(),po()})),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(Ve){if(null!=Ge)return;Ge=setTimeout(Qe,60)}else null!=Ge&&clearTimeout(Ge),Ge=setTimeout(Qe,60)}()})),l.queueClassSelect&&l.queueClassSelect.addEventListener("change",(()=>{localStorage.setItem(u,l.queueClassSelect.value),Do(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 Do(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(Ot())jt();else if(Vt())Qt();else if(Jt())tn();else if(nn())sn();else if(dn())hn();else if(Sn())Nn();else if(In())Tn();else if(lt())ko();else{if(dt&&"function"==typeof dt.close)try{return void dt.close()}catch(e){}It()}},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")||no(),En({kind:"conversations"}),await To(),await _o(),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 cs(),Ce(),Yo("sessions"),l.memoryQuietFloor&&(l.memoryQuietFloor.textContent=String(st)),$t("");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.companionGo&&l.companionGo.addEventListener("click",(()=>{"function"==typeof gt&>()})),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,vt()})),Ct(),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",As):As()}();
|
|
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((()=>ls("markdown"))),e.onMenuExportJson&&e.onMenuExportJson((()=>ls("json"))),e.onDeepLink&&e.onDeepLink(us),e.onQuickLauncherPush&&e.onQuickLauncherPush(nt),l.sessionsRefresh.addEventListener("click",es),l.sessionsFilter&&(l.sessionsFilter.addEventListener("input",(()=>ts())),l.sessionsFilter.addEventListener("keydown",(e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),l.sessionsFilter.value="",ts())}))),l.syncNow.addEventListener("click",rs),l.sessionsExport.addEventListener("click",(()=>ls("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",Uo),l.customRemove&&l.customRemove.addEventListener("click",_o);for(const e of[l.customBaseUrl,l.customKey,l.customModel])e&&e.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),Uo())}));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(ps){if(!(o<=24))return void(t.hidden=!0);ps=!1}t.hidden=o<=24}(e)}),l.scrollBottom&&l.scrollBottom.addEventListener("click",fs),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(),ms()})),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"))&&(gs+=1,document.body.classList.add("is-dropping"))})),window.addEventListener("dragleave",(()=>{gs=Math.max(0,gs-1),0===gs&&document.body.classList.remove("is-dropping")})),window.addEventListener("dragover",(e=>{e.dataTransfer&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")})),window.addEventListener("drop",(t=>{gs=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 ws(n):(ys.push({name:t.name||"file",reason:"no path available"}),Cs())}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",Cs),Cs()),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",(()=>Qo("sessions"))),l.tabMemory&&l.tabMemory.addEventListener("click",(()=>Qo("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",go),l.keysBackdrop&&l.keysBackdrop.addEventListener("click",go),l.keysDismiss&&l.keysDismiss.addEventListener("click",vo),l.keysGotoAegis&&l.keysGotoAegis.addEventListener("click",(()=>{go(),so(),co(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",(()=>{go(),lo()})),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),To(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 To(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())go();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 Bo(),await Do(),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 es(),await as(),Ce(),Qo("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",Ls):Ls()}();
|
|
@@ -872,12 +872,6 @@
|
|
|
872
872
|
<h2>Today</h2>
|
|
873
873
|
<p class="companion-line" id="companion-text"></p>
|
|
874
874
|
<div class="companion-row">
|
|
875
|
-
<!-- Only shown when companionActionTarget() has a real destination for
|
|
876
|
-
this message's id (app.js renderCompanion) — an 'action' message
|
|
877
|
-
that names a place gets a one-click way there, not just the name
|
|
878
|
-
of the place. Hidden in markup so the card never reflows on first
|
|
879
|
-
paint, same reason companion-dismiss is always present. -->
|
|
880
|
-
<button type="button" id="companion-go" class="ghost-btn" hidden></button>
|
|
881
875
|
<button type="button" id="companion-dismiss" class="ghost-btn">Got it</button>
|
|
882
876
|
</div>
|
|
883
877
|
</section>
|
|
@@ -5056,17 +5056,10 @@ body.keys-open {
|
|
|
5056
5056
|
gap: 8px;
|
|
5057
5057
|
}
|
|
5058
5058
|
/* An 'action' message is something to do, so it reads a shade stronger than a
|
|
5059
|
-
tip
|
|
5060
|
-
neither gets a badge or a colour that implies urgency. */
|
|
5059
|
+
tip. Both are plain text — no badge, no colour that implies urgency. */
|
|
5061
5060
|
#companion-card[data-kind='action'] .companion-line {
|
|
5062
5061
|
font-weight: var(--fw-semibold);
|
|
5063
5062
|
}
|
|
5064
|
-
/* Hidden by default in markup; renderCompanion() (app.js) reveals it only
|
|
5065
|
-
when companionActionTarget() resolves msg.id to a real destination, so a
|
|
5066
|
-
'tip' message (the rotation) never grows a button with nowhere to go. */
|
|
5067
|
-
#companion-go[hidden] {
|
|
5068
|
-
display: none;
|
|
5069
|
-
}
|
|
5070
5063
|
/* Same author-stylesheet-beats-UA-stylesheet gotcha as .update-banner above:
|
|
5071
5064
|
.card's `display: grid` (or similar) outranks the UA sheet's
|
|
5072
5065
|
`[hidden] { display: none }`, so the card's initial `hidden` in index.html
|
|
@@ -60,7 +60,7 @@ product, so they are one name now:
|
|
|
60
60
|
| `aegis-terminal` | deprecated — the 0.1.x spelling of this package, folded into `aegiscode`. |
|
|
61
61
|
| `aegiscode-cli` | 4.0.3, an earlier name of this CLI's predecessor line. Untouched. |
|
|
62
62
|
| `aegis-cli` | 0.4.8 (unrelated). |
|
|
63
|
-
| `aegis` (bin) | claimed
|
|
63
|
+
| `aegis` (bin) | was claimed twice — by `aegiscode-cli` (→ `bin/cli.js`) and by `aegis-desktop` (→ `bin/aegis.js`), so whichever installed last won and installing both failed with `EEXIST`. **Resolved:** `aegis-desktop`'s bin is now `aegis-desktop`, and `aegis` belongs to `aegisone` alone. |
|
|
64
64
|
|
|
65
65
|
Publishing this host as `aegiscode` moves the `latest` dist-tag for that name
|
|
66
66
|
onto it. The previous line (`aegiscode@5.x`, the earlier agent build) is
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aegiscode",
|
|
3
3
|
"productName": "AEGIS Code",
|
|
4
|
-
"version": "7.0.
|
|
4
|
+
"version": "7.0.39",
|
|
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",
|