aegisone 1.0.55 → 1.0.57
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/package.json +2 -1
- package/scripts/postinstall.mjs +4 -0
- package/scripts/predist.mjs +1 -1
- package/vendor/cli/package.json +2 -1
- package/vendor/cli/scripts/postinstall.mjs +4 -0
- package/vendor/cli/vendor/client/install-register.js +3 -0
- package/vendor/cli/vendor/client/prefs.js +1 -1
- package/vendor/cli/vendor/client/session-store.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/cli/vendor/desktop/lib/settings.js +1 -1
- package/vendor/cli/vendor/desktop/main.js +83 -24
- package/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/lib/settings.js +1 -1
- package/vendor/desktop/main.js +83 -24
- package/vendor/desktop/package.json +1 -1
- package/vendor/desktop/preload.js +1 -1
- package/vendor/desktop/renderer/app.js +3 -3
- package/vendor/desktop/renderer/index.html +18 -0
- package/vendor/desktop/vendor/faces/cli/package.json +2 -1
- package/vendor/desktop/vendor/faces/cli/scripts/postinstall.mjs +4 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/install-register.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/session-store.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +3 -3
- package/vendor/desktop/vendor/install-register.js +3 -0
- package/vendor/desktop/vendor/prefs.js +1 -1
- package/vendor/desktop/vendor/session-store.js +1 -1
|
@@ -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",settingsGoogleSignin:"settings-google-signin",classSelect:"class-select",modelSelect:"model-select",providerMark:"provider-mark",ptSearch:"pt-search",ptRefresh:"pt-refresh",ptList:"pt-list",ptCount:"pt-count",ptHint:"pt-hint",companionCard:"companion-card",companionText:"companion-text",companionDismiss:"companion-dismiss",modelFree:"model-input",budgetHint:"budget-hint",autonomousToggle:"autonomous-toggle",autonomousToggleWrap:"autonomous-toggle-wrap",autonomousControls:"autonomous-controls",effortSelect:"effort-select",autonomousWorkers:"autonomous-workers",modelHint:"model-hint",settingsList:"settings-list",settingsHint:"settings-hint",customBaseUrl:"custom-base-url",customKey:"custom-key",customModel:"custom-model",customSave:"custom-save",customRemove:"custom-remove",customStatus:"custom-status",quickLauncherEnabled:"quick-launcher-enabled",quickLauncherShortcut:"quick-launcher-shortcut",quickLauncherSave:"quick-launcher-save",quickLauncherHint:"quick-launcher-hint",permRulesList:"perm-rules-list",permRulesForm:"perm-rules-form",permRulesInput:"perm-rules-input",permRulesListSelect:"perm-rules-list-select",permRulesAdd:"perm-rules-add",permRulesStatus:"perm-rules-status",permRulesHint:"perm-rules-hint",sandboxMode:"sandbox-mode-select",sandboxNetwork:"sandbox-network-toggle",sandboxStatus:"sandbox-policy-status",confirmMode:"confirm-mode-toggle",confirmModeHint:"confirm-mode-hint",fontScale:"font-scale-select",fontScaleHint:"font-scale-hint",accentSelect:"accent-select",accentHint:"accent-hint",planMode:"plan-mode-toggle",planModeHint:"plan-mode-hint",autoMode:"auto-mode-toggle",autoModeLabel:"auto-mode-label",autoModeHint:"auto-mode-hint",sessionsRefresh:"sessions-refresh",sessionsExport:"sessions-export",sessionsList:"sessions-list",sessionsHint:"sessions-hint",sessionsFilter:"sessions-filter",sessionsCount:"sessions-count",syncNow:"sync-now",syncStatus:"sync-status",sessionMeter:"session-meter",newChat:"new-chat",openCliFace:"open-cli-face",chatCanvas:"chat-canvas",railAutomations:"rail-automations",railSettings:"rail-settings",avatarPaneMount:"avatar-pane-mount",settingsView:"settings-view",automationsView:"automations-view",automationsBack:"automations-back",queueModelField:"queue-model-field",conversationsView:"conversations-view",sideScroll:"side-scroll",settingsBack:"settings-back",settingsJump:"settings-jump",memorySearchForm:"memory-search-form",memoryQuery:"memory-query",memoryResults:"memory-results",memoryEntry:"memory-entry",memorySaveBtn:"memory-save-btn",importSessionBtn:"import-session-btn",importOverlay:"import-overlay",importBackdrop:"import-backdrop",importClose:"import-close",importHint:"import-hint",importList:"import-list",importCount:"import-count",importSync:"import-sync",importSessionsBtn:"import-sessions-btn",importMemoryBtn:"import-memory-btn",memoryHint:"memory-hint",memoryOpen:"memory-open",memoryBox:"memory-box",memoryQuiet:"memory-quiet",memoryQuietFloor:"memory-quiet-floor",paneTabs:"pane-tabs",tabSessions:"tab-sessions",tabMemory:"tab-memory",paneSessions:"pane-sessions",paneMemory:"pane-memory",memoryOverlay:"memory-overlay",memoryBackdrop:"memory-backdrop",memoryClose:"memory-close",memoryFilters:"memory-filters",memoryOverlayQuery:"memory-overlay-query",memoryFiltersClear:"memory-filters-clear",memoryChips:"memory-chips",memoryList:"memory-list",memoryCount:"memory-count",memoryOverlayEntry:"memory-overlay-entry",memoryOverlaySave:"memory-overlay-save",sessionOverlay:"session-overlay",sessionBackdrop:"session-backdrop",sessionClose:"session-close",sessionFilters:"session-filters",sessionQuery:"session-query",sessionClear:"session-clear",sessionHint:"session-hint",sessionList:"session-list",sessionCount:"session-count",paletteOverlay:"palette-overlay",paletteBackdrop:"palette-backdrop",paletteInput:"palette-input",composerMenu:"composer-menu",composerMenuList:"composer-menu-list",composerMenuHint:"composer-menu-hint",paletteList:"palette-list",paletteEmpty:"palette-empty",findBar:"find-bar",findInput:"find-input",findCount:"find-count",findPrev:"find-prev",findNext:"find-next",findClose:"find-close",side:"side",creditsOverlay:"credits-overlay",creditsBackdrop:"credits-backdrop",creditsClose:"credits-close",creditsBody:"credits-body",creditsStatus:"credits-status",creditsLicenceTag:"credits-licence-tag",fpCardStatus:"fp-card-status",fpOpen:"fp-open",fpOverlay:"fp-overlay",messages:"messages",scrollBottom:"scroll-bottom",composer:"composer",prompt:"prompt",send:"send",attachRow:"attach-row",attachNote:"attach-note",dropVeil:"drop-veil",exploreToggle:"explore-toggle",queueTask:"queue-task",queueClassSelect:"queue-class-select",queueModelSelect:"queue-model-select",queueModelInput:"queue-model-input",queueModelHint:"queue-model-hint",queueCwd:"queue-cwd",queueCommit:"queue-commit",queueEnqueue:"queue-enqueue",queueDrain:"queue-drain",queueProceed:"queue-proceed",queueStop:"queue-stop",queueList:"queue-list",queueHint:"queue-hint",queueFanout:"queue-fanout",queueFanoutLabel:"queue-fanout-label",queueAuto:"queue-auto",queueAutoLabel:"queue-auto-label",queueAutoInterval:"queue-auto-interval",queueAutoHint:"queue-auto-hint",queueBoundary:"queue-boundary",queueUpgrade:"queue-upgrade",queueCard:"queue-card",shortcutsOverlay:"shortcuts-overlay",shortcutsBackdrop:"shortcuts-backdrop",shortcutsClose:"shortcuts-close",shortcutsBody:"shortcuts-body",shortcutsCount:"shortcuts-count",keysOverlay:"keys-overlay",keysBackdrop:"keys-backdrop",keysClose:"keys-close",keysCount:"keys-count",keysRowAegis:"keys-row-aegis",keysRowByok:"keys-row-byok",keysAegisState:"keys-aegis-state",keysByokState:"keys-byok-state",keysGotoAegis:"keys-goto-aegis",keysGotoByok:"keys-goto-byok",keysHint:"keys-hint",keysDismiss:"keys-dismiss"},l={};for(const[e,t]of Object.entries(c))Object.defineProperty(l,e,{get:()=>document.getElementById(t),enumerable:!0,configurable:!0});const d="aegis.class",u="aegis.queueClass",m="aegis.autonomous",p="aegis.effort",f="aegis.autonomousWorkers",h="aegis.explore",y="aegis.welcomeConnectDismissed",g="aegis",v=new Set(["__aegis","aegis"]),C="local",k="custom",b="http://localhost:11434",w="https://aegiscloud.org/key?s=desktop&c=key_prompt",x="The autonomous queue keeps running after you close the laptop.",S="https://aegiscloud.org",E=/^[a-z0-9][a-z0-9_-]{0,63}$/;function $(e,t){const n=new URL(`${S}/go/${e}`);n.searchParams.set("s","desktop");const o=null==t?"":String(t).trim().toLowerCase();return E.test(o)&&n.searchParams.set("c",o),n.toString()}function L(e){return $("upgrade",e)}function q(e){return $("topup",e)}const M={welcome_cloud:"welcome",queue_cap:"queue",memory_quota:"memory",status_card:"status",topup_bank:"topup"},A="upgrade_prompt_rendered",N="upgrade_prompt_clicked";let H=!1;function B(e,t){try{const n=M[t];if(!n)return;const o=window.aegis;if(!o||"function"!=typeof o.telemetryEvent)return;const s=o.telemetryEvent(e,{campaign:t,surface:n});s&&"function"==typeof s.catch&&s.catch((()=>{}))}catch(e){if(!H){H=!0;try{console.debug("telemetry: prompt event failed (suppressed)",e)}catch{}}}}function I(e,t,n,o){const s=document.createElement("a");return s.href=function(e,t){const n="topup_bank"===t?q(t):L(t);if(!e)return n;let o;try{o=new URL(e,S)}catch{return e}return o.origin!==S||o.searchParams.get("s")||o.searchParams.get("utm_source")?e:/topup/.test(o.pathname)?q(t):n}(t,n),s.target="_blank",s.rel="noreferrer noopener",s.textContent=o,s.addEventListener("click",(()=>B(N,n))),e.appendChild(s),!1===e.isConnected||e.hidden||B(A,n),s}let R=null,T=null,O=null,F=[],D=[],P=new Map;const U=new Map;function _(e,t,n={}){const o=e||"",s=rollTurn(function(e){const t=e||"";return U.has(t)||U.set(t,emptyRoll()),U.get(t)}(o),t,n);return U.set(o,s),K(o),s}function K(e,t){const n=l.sessionMeter,o=t?function(e){const t="string"==typeof e.reply?e.reply:"",n="string"==typeof e.reasoning?e.reasoning:"",o="number"==typeof e.measuredReasoningTokens&&e.measuredReasoningTokens>0?e.measuredReasoningTokens:0;if(!t&&!n&&!o)return"↓0 tokens";let s=0;try{const o=estimatedBuckets(e.prompt,t,n);o&&"number"==typeof o.output&&o.output>0&&(s=o.output)}catch(e){}if(!s){let e=0;for(const o of[t,n]){let t=0;for(;t<o.length;)t+=o.codePointAt(t)>65535?2:1,e+=1}s=Math.ceil(e/4)}return s+=o,s?`↓${o>0?"≥":""}${Math.round(s)} tokens`:""}(t):"",s=t?function(){if(!R)return null;let e=R.querySelector(".typing-tokens");return e||(e=document.createElement("span"),e.className="typing-tokens",e.hidden=!0,R.appendChild(e)),e}():null;if(s&&(s.textContent=o,s.hidden=!o),!n)return;if(O!==e)return void(n.hidden=!0);let a=U.get(e||"");t&&(a=rollTurn(a||emptyRoll(),void 0,{prompt:t.prompt,reply:t.reply,reasoning:t.reasoning,measuredReasoningTokens:t.measuredReasoningTokens}));const i=a?fmtRoll(a):"";return n.textContent=i,n.hidden=!i,n.classList.toggle("live",!!t&&!!i),i&&(n.title="This session, counted the way the CLI counts it — every turn rolled into one running total"),a}function j(e,t,n,o){const s=ledgerRow(e,n,{model:t,costUsd:n&&n.real&&"number"==typeof n.cost?n.cost:void 0,calls:o&&o.calls,prompt:o&&o.prompt,reply:o&&o.reply,reasoning:o&&o.reasoning}),a=s?Object.assign({},s):{};return t&&(a.model=t),a}const 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"),to(),jn(),Wn(),function(){const e=document.getElementById("keys-overlay");if(!e)return;let t=!1;try{t="on"===localStorage.getItem(ho)}catch{}t||null===de?e.hidden=!0:(yo(),Boolean(T)?vo():!0!==de||!0!==ue?go():vo())}()}let pe=null,fe=null;function he(e){if(!l.updateBanner)return;pe=e;try{gt()}catch{}const t=e&&e.status,n=!t||"idle"===t||"disabled"===t||"checking"===t||"up-to-date"===t||"unavailable"===t;if("decomposed"===t)return l.updateBannerText.textContent="This version is DECOMPOSED — update to the latest release."+(e.version?` v${e.version}`:""),l.updateDownloadBtn.hidden=!0,l.updateRestartBtn.hidden=!0,l.updateRetryBtn&&(l.updateRetryBtn.hidden=!0),void(l.updateBanner.hidden=!1);if(n||t===fe)return void(l.updateBanner.hidden=!0);let o="",s=!1,a=!1,i=!1;const r=e.version?`v${e.version} `:"";if("available"===t)o=e.command?e.commandIsSentence?`Update ${r}available. ${e.command}`:`Update ${r}available — run: ${e.command}`:`Update ${r}available.`,s=!!e.canDownload,s&&(o=`Update ${r}available.`);else if("downloading"===t)o=`Downloading update${"number"==typeof e.progress?` (${Math.round(e.progress)}%)`:""}…`;else if("downloaded"===t)o=`Update ${r}downloaded — restart to install.`,a=!0;else{if("error"!==t)return void(l.updateBanner.hidden=!0);o=`Update check failed: ${e.error||"unknown error"}`,e.transient&&(o+=" — will retry automatically."),i=!0}l.updateBannerText.textContent=o,l.updateDownloadBtn.hidden=!s,l.updateRestartBtn.hidden=!a,l.updateRetryBtn&&(l.updateRetryBtn.hidden=!i),l.updateBanner.hidden=!1}let ye=null;function ge(e){ye=e&&"no-key"===e.status?e.reason:null,yo(),l.accountBanner&&(ye?(l.accountBannerText.textContent=`No AEGIS account key on this machine: ${ye}.`,l.accountBanner.hidden=!1):l.accountBanner.hidden=!0)}function ve(t){t.disabled=!0,e.registerAccount().then((e=>{if(ge(e),!e)return be()})).catch((e=>ge({status:"no-key",reason:String(e&&e.message||e)}))).finally((()=>{t.disabled=!1}))}async function Ce(){try{const t=await e.verifyApiKey();t&&t.ok?l.plan.textContent=t.valid?t.plan||"active":"invalid key":l.plan.textContent="unavailable"}catch{l.plan.textContent="unavailable"}try{const t=await e.tokenBankBalance();l.balance.textContent=t&&null!=t.balance_eur?`€${t.balance_eur}`:"–"}catch{l.balance.textContent="unavailable"}}async function ke(t){const n=Math.round(Number(l.topupAmount&&l.topupAmount.value)||10),o="topup"===t?l.topupBtn:l.upgradePlan;if(o&&(o.disabled=!0),"topup"===t&&!1===de)return o&&(o.disabled=!1),void(l.billingHint.textContent="add your AEGIS API key above — a top-up is credited to your account");l.billingHint.textContent="topup"===t?`creating a €${n} top-up…`:"creating checkout…";try{const o="topup"===t?await e.tokenBankTopup(n):await e.billingCheckout();if(!o||!0!==o.ok||!o.url)return void function(e,t){const n="topup"===t?"top-up":"upgrade";if(401!==e.status&&403!==e.status)return e.upgrade?(l.billingHint.textContent=`free plan cap reached — ${n} lifts it. `,void I(l.billingHint,e.upgrade.url,"topup"===t?"topup_bank":"status_card","See plans →")):void(e.setupRequired?l.billingHint.textContent="checkout is not configured on the server yet (no Stripe price id)":l.billingHint.textContent=`${n} failed: ${e.reason||"the server returned no checkout URL"}`);l.billingHint.textContent=`add your AEGIS API key above — a ${n} needs an account`}(o||{},t);l.billingHint.textContent="opening checkout…";const s=await e.openExternal(o.url);if(s&&!1===s.ok)return void(l.billingHint.textContent=`could not open the checkout page: ${s.reason||"unknown reason"}`);l.billingHint.textContent="topup"===t?"checkout opened in your browser — the bank is credited when Stripe confirms":"checkout opened in your browser — your plan updates when Stripe confirms"}catch(e){l.billingHint.textContent=`billing failed: ${e&&e.message?e.message:e}`}finally{o&&(o.disabled=!1)}}async function be(){try{me(await e.status())}catch{me(null)}await Io(),await Ce()}async function we(){const t=l.apiKeyInput.value.trim();l.apiKeySave.disabled=!0,l.apiKeyVerify.disabled=!0,l.apiKeyHint.textContent="saving…";try{const n=await e.setApiKey(t);if(!n||!n.ok)throw new Error(n&&n.error||"save failed");l.apiKeyInput.value="",l.apiKeyHint.textContent=t?`saved (${n.keyMask?n.keyMask:"configured"})`:"key cleared",await be()}catch(e){l.apiKeyHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{l.apiKeySave.disabled=!1,l.apiKeyVerify.disabled=!1}}async function xe(){l.apiKeyVerify.disabled=!0,l.apiKeyHint.textContent="verifying…";try{const t=await e.verifyApiKey();if(!t||!t.ok)throw new Error(t&&t.error||"verify failed");l.apiKeyHint.textContent=t.valid?`valid (${t.plan||"active"})`:"invalid key"}catch(e){l.apiKeyHint.textContent=`verify failed: ${e&&e.message?e.message:e}`}finally{l.apiKeyVerify.disabled=!1}}function Se(e){if(!e)return;l.quickLauncherEnabled.checked=Boolean(e.enabled),l.quickLauncherShortcut.value=e.shortcut||"",l.quickLauncherShortcut.placeholder=e.shortcut||"CmdOrCtrl+Shift+Space";const t=[];e.packaged&&t.push("always on in this packaged build"),t.push(e.active?`active — press ${e.shortcut} anywhere`:"inactive"),e.reason&&t.push(e.reason),l.quickLauncherHint.textContent=t.join(" · ")}async function Ee(){if(o){l.quickLauncherSave.disabled=!0,l.quickLauncherHint.textContent="saving…";try{Se(await o.setConfig({enabled:l.quickLauncherEnabled.checked,shortcut:l.quickLauncherShortcut.value.trim()}))}catch(e){l.quickLauncherHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{l.quickLauncherSave.disabled=!1}}}function $e(e){if(!l.confirmMode||!e)return;const t=!1!==e.enabled;l.confirmMode.checked=t,l.confirmModeHint.textContent=t?"On — exec, writeFile and editFile ask for your approval before they run.":"Off — the agent runs exec, writeFile and editFile without asking.",Le(t)}function Le(e){if(!l.autoMode)return;const t=!e;l.autoMode.setAttribute("aria-pressed",t?"true":"false"),l.autoMode.classList.toggle("is-auto",t),l.autoModeLabel&&(l.autoModeLabel.textContent=t?"auto mode":"ask before tools"),l.autoModeHint&&(l.autoModeHint.textContent=t?"on — tools run without asking. Click to require approval.":"off — click for auto mode, or use Settings → Tool approvals.")}function qe(e){const t=Number(e),n=Number.isFinite(t)?Math.min(1.3,Math.max(.85,t)):1;if(document.documentElement.style.setProperty("--app-font-scale",String(n)),l.fontScale){const e=Array.from(l.fontScale.options||[]);let t=null;for(const o of e){const e=Number(o.value);Number.isFinite(e)&&(!t||Math.abs(e-n)<Math.abs(Number(t.value)-n))&&(t=o)}t&&(l.fontScale.value=t.value)}l.fontScaleHint&&(l.fontScaleHint.textContent=`Interface text at ${Math.round(100*n)}%.`)}function Me(e){const t=["default","cobalt","amber"].includes(String(e))?String(e):"default";if(document.body.dataset.accent=t,l.accentSelect&&(l.accentSelect.value=t),l.accentHint){const e={default:"teal",cobalt:"cobalt",amber:"amber"}[t];l.accentHint.textContent=`Accent set to ${e}.`}}async function Ae(t){if(l.confirmMode){l.confirmMode.disabled=!0,l.autoMode&&(l.autoMode.disabled=!0);try{$e(await e.setConfirmMode(t))}catch(e){l.confirmMode.checked=!t,l.confirmModeHint.textContent=`save failed: ${e&&e.message?e.message:e}`,Le(l.confirmMode.checked)}finally{l.confirmMode.disabled=!1,l.autoMode&&(l.autoMode.disabled=!1)}}}function Ne(e){if(!l.planMode||!e)return;const t="plan"===e.mode;l.planMode.checked=t,l.planModeHint&&(l.planModeHint.textContent=t?"On — writeFile, editFile and mutating exec calls are refused; read-only shell and search still run.":'Off — tool calls follow "confirm before running tools" above, as usual.')}const He=["deny","allow","ask"];function Be(e){if(!l.permRulesList)return;l.permRulesList.innerHTML="";const t=e&&!0===e.ok,n=t&&e.rules?e.rules:null;if(!n){const n=document.createElement("li");return n.className="rules-row rules-row-muted",n.textContent=t?"no stored rules":`rules unavailable: ${e&&e.reason||"the permission store could not be read"}`,l.permRulesList.appendChild(n),void(l.permRulesHint&&(l.permRulesHint.dataset.residual=""))}let o=0;for(const e of He){const t=Array.isArray(n[e])?n[e]:[];for(const n of t){o+=1;const t=document.createElement("li");t.className="rules-row",t.dataset.list=e,t.dataset.rule=n;const s=document.createElement("span");s.className=`rules-tag rules-tag-${e}`,s.textContent=e,t.appendChild(s);const a=document.createElement("code");a.className="rules-pattern",a.textContent=n,t.appendChild(a);const i=document.createElement("button");i.type="button",i.className="ghost-btn danger rules-remove",i.textContent="Remove",i.addEventListener("click",(()=>Ie(e,n))),t.appendChild(i),l.permRulesList.appendChild(t)}}if(!o){const e=document.createElement("li");e.className="rules-row rules-row-muted",e.textContent="no stored rules",l.permRulesList.appendChild(e)}var s;l.permRulesHint&&(l.permRulesHint.textContent=`A rule is tool(pattern) — exec(npm test), exec(npm run *), writeFile(src/**). Deny beats allow. ${s=n.defaultMode,"allow"===s?"unmatched calls run without asking":"deny"===s?"unmatched calls are refused":"unmatched calls ask"}.`)}async function Ie(t,n){if(e.permRulesRemove)try{const o=await e.permRulesRemove(t,n);o&&!0===o.ok?(Be(o),l.permRulesStatus&&(l.permRulesStatus.textContent=!1===o.removed?`already gone: ${n}`:`removed: ${n}`)):l.permRulesStatus&&(l.permRulesStatus.textContent=`remove failed: ${o&&o.reason||"the store refused it"}`)}catch(e){l.permRulesStatus&&(l.permRulesStatus.textContent=`remove failed: ${e&&e.message?e.message:e}`)}}const Re={"workspace-write":"Commands may write inside the open workspace and /tmp; everything else is read-only.","read-only":"Commands may write nothing at all. Every path is mounted read-only.",off:"No sandbox. Commands run with your full user permissions."};function Te(e){if(!l.sandboxMode)return;const t=e&&"string"==typeof e.mode?e.mode:"workspace-write",n=e&&"open"===e.network?"open":"restricted";if(Array.isArray(e&&e.modes)&&e.modes.length&&Array.from(l.sandboxMode.options).map((e=>e.value)).join("\0")!==e.modes.join("\0")){l.sandboxMode.innerHTML="";for(const t of e.modes){const e=document.createElement("option");e.value=t,e.textContent=t,l.sandboxMode.appendChild(e)}}l.sandboxMode.value=t,l.sandboxNetwork&&(l.sandboxNetwork.checked="open"===n),l.sandboxStatus&&(l.sandboxStatus.textContent=e&&!1!==e.ok?function(e){const t=e&&"string"==typeof e.mode?e.mode:"workspace-write",n=e&&"open"===e.network?"open":"restricted",o=e&&"string"==typeof e.sentence?e.sentence:null,s=e?e.enforced:null;if(!1===s)return`${o||`sandbox: OFF — no mechanism available (mode ${t} is not being enforced)`}. Commands are NOT confined.`;if(null===s||!o){const e=null===s?"the sandbox probe could not be completed":"no mechanism reported";return`${Re[t]||t} Sandbox status unknown: ${e}, so this posture may not be enforced.`}return`${null!==o?o:""} ${Re[t]||t} Network: ${"open"===n?"allowed":"blocked"}.`.trim()}(e):`could not read the posture: ${e&&e.reason||"unknown error"}`)}async function Oe(){if(l.sandboxMode&&e.getSandboxPolicy)try{Te(await e.getSandboxPolicy())}catch(e){Te({ok:!1,reason:e&&e.message||String(e)})}}async function Fe(t,n){if(e.setSandboxPolicy)try{Te(await e.setSandboxPolicy(t,n))}catch(e){l.sandboxStatus&&(l.sandboxStatus.textContent=`not saved: ${e&&e.message?e.message:e}`),Oe()}}let De="",Pe=!1;function Ue(e){De=e||"",l.queueHint&&(l.queueHint.textContent=De)}function _e(e){const t=document.createElement("li");t.className="queue-task",t.dataset.status=e.status;const n=document.createElement("div");n.className="queue-task-head";const o=document.createElement("span");o.className="queue-task-id",o.textContent=`#${e.id}`,n.appendChild(o);const s=document.createElement("span");s.className="queue-task-pill",s.textContent=String(e.status||"pending"),n.appendChild(s);const a=document.createElement("div");if(a.className="queue-task-actions","done"===e.status||"error"===e.status){const t=document.createElement("button");t.type="button",t.className="ghost-btn",t.textContent="Retry",t.title="Put this task back in line and run it again",t.addEventListener("click",(()=>Je("retry",e.id))),a.appendChild(t)}if("running"!==e.status){const t=document.createElement("button");t.type="button",t.className="ghost-btn",t.textContent="Remove",t.addEventListener("click",(()=>Je("remove",e.id))),a.appendChild(t)}a.childNodes.length&&n.appendChild(a),t.appendChild(n);const i=document.createElement("p");i.className="queue-task-prompt",i.textContent=String(e.task||"").trim()||"(no prompt)",t.appendChild(i);const r=document.createElement("p");r.className="queue-task-meta",r.textContent=function(e){const t=[];if(e.model&&t.push(e.model),t.push(!1===e.singlePass||!0===e.autonomous?"fan-out":"single pass"),e.cwd&&t.push(e.cwd),"running"===e.status)t.push(e.startedAt?`started ${vt(e.startedAt)}`:"working");else if("pending"===e.status)e.attempts&&t.push(`${e.attempts} attempt${1===e.attempts?"":"s"}`),e.created&&t.push(`queued ${vt(e.created)}`);else{e.attempts>1&&t.push(`${e.attempts} attempts`);const n=e.finishedAt||e.startedAt||e.created;n&&t.push(vt(n))}return t.join(" · ")}(e),t.appendChild(r);let c="";if("error"===e.status?c=e.error?String(e.error):"failed — no reason recorded":"done"===e.status&&(c=(e.result&&e.result.output?String(e.result.output):"").trim()),c){const n=document.createElement("p");n.className="error"===e.status?"queue-task-result is-error":"queue-task-result",n.textContent=c,t.appendChild(n)}const l=e.result&&Array.isArray(e.result.files)?e.result.files:[];if(l.length){const e=document.createElement("ul");e.className="queue-task-files";for(const t of l){const n=document.createElement("li");n.textContent=String(t),e.appendChild(n)}t.appendChild(e)}return t}function Ke(e){if(!l.queueList||!e||"object"!=typeof e)return;Pe=Boolean(e.draining),l.queueCwd&&!l.queueCwd.value&&(l.queueCwd.value=e.defaultCwd||""),l.queueEnqueue&&(l.queueEnqueue.disabled=Pe),l.queueDrain&&(l.queueDrain.disabled=Pe),l.queueProceed&&(l.queueProceed.disabled=Pe),l.queueStop&&(l.queueStop.hidden=!Pe);const t=Array.isArray(e.items)?e.items:[];if(l.queueList.innerHTML="",t.length)for(const e of t)l.queueList.appendChild(_e(e));else{const e=document.createElement("li");e.className="empty",e.textContent="queue is empty",l.queueList.appendChild(e)}const n=[];e.running?n.push(`running #${e.running.id}`):Pe&&n.push("draining…"),n.push(`${e.pending||0} pending`),e.defaultModel&&n.push(`Aegis Cloud · ${e.defaultModel}`),Pe&&e.stopping&&n.push("stopping after this task"),function(e){const t=e&&e.entitlement?e.entitlement:null,n=Boolean(t&&t.source&&"unresolved"!==t.source),o=Boolean(t&&t.entitled);if(l.queueFanout&&(l.queueFanout.disabled=!o,o||(l.queueFanout.checked=!1)),l.queueBoundary&&(l.queueBoundary.textContent=n?o?t.pro?`${t.tierName||"Pro"} — the cloud drain and the fan-out are unlocked.`:"Balance on your account — the cloud drain and the fan-out are unlocked.":t.refusal||"":""),l.queueUpgrade&&(l.queueUpgrade.innerHTML="",n&&!o)){const e="balance"===t.wall;I(l.queueUpgrade,t.upgradeUrl,t.campaign,e?"Top up your balance ↗":"See what Pro covers ↗")}}(e),l.queueHint&&(l.queueHint.textContent=[De,n.join(" · ")].filter(Boolean).join(" · "))}async function je(){if(!s||!l.queueList)return null;try{const e=await s.list();return Ke(e),e}catch(e){return Ue(`queue list failed: ${e&&e.message?e.message:e}`),null}}let 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:To(),commit:!!l.queueCommit&&l.queueCommit.checked});t&&t.ok?(l.queueTask.value="",Ue(`queued #${t.item.id}`)):Ue(t&&t.reason||"enqueue failed"),Ke(t)}catch(e){Ue(`enqueue failed: ${e&&e.message?e.message:e}`)}finally{l.queueEnqueue&&(l.queueEnqueue.disabled=Pe)}}else Ue("type a task first")}async function ze(e){if(s){Pe=!0,Ue("one"===e?"running one task…":"draining the queue…"),l.queueDrain&&(l.queueDrain.disabled=!0),l.queueProceed&&(l.queueProceed.disabled=!0),l.queueEnqueue&&(l.queueEnqueue.disabled=!0),l.queueStop&&(l.queueStop.hidden=!1);try{const t=await("one"===e?s.drain():s.proceed());Ue(function(e){if(!e||"object"!=typeof e)return"the drain did not answer";if(e.locked){const t=e.holder&&e.holder.pid;return"another drain is already running"+(t?` (pid ${t})`:"")}if(!1===e.ok)return e.reason||"the drain did not run";const t=Array.isArray(e.ran)?e.ran:[];if(!t.length)return e.stopped?"stopped before the next task":"nothing pending";const n=t.filter((e=>!e.ok)),o=[`ran ${t.length} — ${t.length-n.length} done`];return n.length&&o.push(`failed #${n.map((e=>e.id)).join(", #")}`),e.stopped&&o.push("stopped"),o.join(" · ")}(t)),Ke(t)}catch(e){Pe=!1,l.queueDrain&&(l.queueDrain.disabled=!1),l.queueProceed&&(l.queueProceed.disabled=!1),l.queueEnqueue&&(l.queueEnqueue.disabled=!1),l.queueStop&&(l.queueStop.hidden=!0),Ue(`drain failed: ${e&&e.message?e.message:e}`)}}}async function Ye(){if(s){l.queueStop&&(l.queueStop.disabled=!0),Ue("stopping…");try{const e=await s.stop(),t=e&&e.cancelled&&e.cancelled.ok;De=t?"stopped the running task":"stop requested",Ke(e)}catch(e){Ue(`stop failed: ${e&&e.message?e.message:e}`)}finally{l.queueStop&&(l.queueStop.disabled=!1)}}}async function Je(e,t){if(s){Ue(`${e} #${t}…`);try{const n=await s[e](t);n&&!1===n.ok?Ue(n.reason||`${e} failed`):Ue(`${"retry"===e?"re-queued":"removed"} #${t}`),Ke(n)}catch(t){Ue(`${e} failed: ${t&&t.message?t.message:t}`)}}}function Xe(e){e&&"object"==typeof e&&e.drain&&function(e){if(!l.queueAuto||!e||"object"!=typeof e)return;const t=!0===e.enabled;if(l.queueAuto.checked=t,l.queueAutoInterval){l.queueAutoInterval.disabled=!t;const n=Number(e.intervalMs);Number.isFinite(n)&&(l.queueAutoInterval.value=String(n))}if(l.queueAutoLabel&&(l.queueAutoLabel.textContent=t?`drain automatically · ${function(e){const t=Number(e);if(!Number.isFinite(t)||t<=0)return"every interval";if(t<6e4)return`every ${Math.round(t/1e3)}s`;const n=t/6e4;return Number.isInteger(n)?`every ${n} min`:`every ${n.toFixed(1)} min`}(e.intervalMs)}`:"drain automatically"),!l.queueAutoHint)return;if(!t)return void(l.queueAutoHint.textContent="off — Run one / Drain all are the only triggers");const n=[];e.busy?n.push("a drain is running"):e.armed&&n.push("armed"),e.ticks&&n.push(`${e.ticks} tick${1===e.ticks?"":"s"}`),e.drains&&n.push(`${e.drains} drained`);const o=e.lastSkip&&e.lastSkip.reason;o?n.push(`last check skipped: ${function(e,t={}){if("empty"===e)return"queue is empty";if("busy"===e)return"the previous drain is still running";if("locked"===e){const e=t.holder&&t.holder.pid;return e?`another drain holds the lock (pid ${e})`:"another drain holds the lock"}return"disabled"===e?"switched off":"no queue access"===e?"this window has no queue access":String(e)}(o,e.lastSkip)}`):e.ticks||n.push("first check one interval after arming"),l.queueAutoHint.textContent=n.join(" · ")}(e.drain)}async function Ze(){if(!a||"function"!=typeof a.status)return null;try{const e=await a.status();return Xe(e),e}catch(e){return l.queueAutoHint&&(l.queueAutoHint.textContent=`automation status unavailable: ${e&&e.message?e.message:e}`),null}}async function et(e){if(!a||"function"!=typeof a.setDrain)return;const t={enabled:Boolean(e)};l.queueAutoInterval&&l.queueAutoInterval.value&&(t.intervalMs=Number(l.queueAutoInterval.value));try{const e=await a.setDrain(t);e&&!1===e.ok&&l.queueAutoHint&&(l.queueAutoHint.textContent=e.error||"could not save that"),Xe(e)}catch(e){l.queueAutoHint&&(l.queueAutoHint.textContent=`could not save that: ${e&&e.message?e.message:e}`)}}function tt(e){if(!e||"object"!=typeof e)return;const t=null==e.taskId?"":`#${e.taskId} `;if("start"===e.type)Ue(`${t}running${e.model?` on ${e.model}`:""}…`);else if("tool"===e.type&&e.tool)Ue(`${t}${Mo(e.tool)}`);else if("finish"===e.type)Ue(`${t}${e.ok?"done":"failed"} — refreshing`),je(),Ze();else if("recovered"===e.type){const t=Array.isArray(e.ids)?e.ids:[];Ue(`recovered ${t.length} stalled task${1===t.length?"":"s"}`),Ze()}else"locked"===e.type?(Ue("another drain is already running"),Ze()):"queued"===e.type&&Ue(`queued phase ${e.phase}`)}function nt(e){const t=e&&e.prompt,o=e&&e.response;if(!t||!o)return;O||(O=Bo());const s=O,a=e&&e.model||"",i=e&&e.class||"",r=i||a?[i?i.toUpperCase():"",a].filter(Boolean).join(" · "):void 0;bo("user",t),bo("assistant",o,r,s),F.push({role:"user",content:t}),F.push({role:"assistant",content:o}),n.append(s,{role:"user",content:t}).catch((()=>{})),n.append(s,{role:"assistant",content:o}).catch((()=>{}))}const ot=10,st=6,at=50,it={entries:[],query:"",source:"",role:"",error:"",upgrade:null,local:!1,loading:!1};function rt(){if(ct())return!0;if(Rt())return!0;if(jt())return!0;if(zt())return!0;if(en())return!0;if(cn())return!0;if(wn())return!0;if(Hn())return!0;if(lt())return!0;if(dt&&"function"==typeof dt.isOpen)try{return!!dt.isOpen()}catch(e){return!1}return!1}function ct(){return!!l.memoryOverlay&&!l.memoryOverlay.hidden}function lt(){return!!l.keysOverlay&&!l.keysOverlay.hidden}let dt=null,ut=null,mt=!1;async function pt(e){if(!ut)return;if(mt&&!e)return;l.ptHint&&(l.ptHint.textContent="listing providers…");const n=await async function(){let e=[];try{e=await t.listClasses()||[]}catch(e){return l.ptHint.textContent=`listClasses failed: ${e&&e.message?e.message:e}`,[]}const n=[];for(const o of e){if(!o||!o.class)continue;let e=null;try{e=await t.listModels(o.class)}catch(t){e={models:[],error:t&&t.message||String(t)}}n.push({class:o.class,classLabel:o.label,classConfigured:Boolean(o.configured),list:e})}return n}();mt=!0,ut.set(n)}function ft(e){e&&e.class&&Array.from(l.classSelect.options).some((t=>t.value===e.class))&&(l.classSelect.value=e.class,localStorage.setItem(d,e.class),ie(e.class),Ro(e.class).then((()=>{e.model&&Array.from(l.modelSelect.options).some((t=>t.value===e.model))&&(l.modelSelect.value=e.model,l.modelSelect.dispatchEvent(new Event("change")))})))}const ht="aegis.companion.dismissed";function yt(){const e={keyConfigured:null===de?void 0:de};return Array.isArray(it.entries)&&it.entries.length&&(e.memoryCount=it.entries.length),pe&&"downloaded"===pe.status&&pe.version&&(e.updatePending=String(pe.version)),D.length&&l.modelSelect&&l.modelSelect.options.length>1&&(e.modelCount=l.modelSelect.options.length),e}function gt(){if(!window.aegisCompanion||!l.companionCard||!l.companionText)return;const e=new Date;let t=null;try{t=JSON.parse(localStorage.getItem(ht)||"null")}catch{t=null}if(window.aegisCompanion.dismissedToday(t,e))return void(l.companionCard.hidden=!0);const n=window.aegisCompanion.pickMessage(yt(),e);n&&n.text?(l.companionText.textContent=n.text,l.companionCard.dataset.kind=n.kind,l.companionCard.dataset.messageId=n.id,l.companionCard.hidden=!1):l.companionCard.hidden=!0}function vt(e){if(!Number.isFinite(e))return"";const t=Math.round((Date.now()-e)/1e3);if(t<45)return"just now";const n=Math.round(t/60);if(n<60)return`${n}m ago`;const o=Math.round(n/60);if(o<24)return`${o}h ago`;const s=Math.round(o/24);if(s<30)return`${s}d ago`;const a=Math.round(s/30);return a<12?`${a}mo ago`:`${Math.round(a/12)}y ago`}function Ct(e){const t=e&&"object"==typeof e?e:{},n=e=>Array.isArray(e)?e.filter((e=>null!=e&&""!==e)):[],o=e=>"string"==typeof e?e:"",s=e=>Number.isFinite(Number(e))?Number(e):null,a=o(t.content)||o(t.text)||o(t.entry);return{id:null!=t.id?String(t.id):"",content:a,source:o(t.source)||"(unknown source)",role:o(t.role),tags:n(t.tags),entities:n(t.entities),session:o(t.session),sentiment:o(t.sentiment),importance:s(t.importance),tokenCount:s(t.tokenCount),summary:!0===t.summary,createdAt:s(t.createdAt),timestamp:o(t.timestamp)}}async function kt(t,n){try{const o=t?await e.memorySearch(t,n):await e.memoryList(n),s=o&&(o.entries||o.results),a=Array.isArray(s)?s.map(Ct):[];return o&&o.upgrade?{entries:a,error:"",upgrade:o.upgrade,local:!0===o.local}:{entries:a,error:"",upgrade:null,local:o&&!0===o.local}}catch(e){const t=e&&e.status,n=e&&e.data&&e.data.error;return 402===t||"free_session_limit_reached"===n?{entries:[],error:"",upgrade:{url:e.data&&e.data.upgradeUrl||L("memory_quota"),used:e.data&&(null!=e.data.tokensUsed?e.data.tokensUsed:e.data.sessionsUsed),limit:e.data&&(null!=e.data.tokenLimit?e.data.tokenLimit:e.data.freeSessionLimit)}}:{entries:[],error:`search failed: ${e&&e.message?e.message:e}`,upgrade:null,local:!1}}}function bt(e){if(null==e||isNaN(e))return"?";const t=Number(e);return t>=1e6?`${(t/1e6).toFixed(t%1e6==0?0:1)}M`:t>=1e4?`${Math.round(t/1e3)}k`:t.toLocaleString("en-US")}function wt(e,t,n,o,s){if(!e)return;const a=null!=t.used?bt(t.used):"?",i=null!=t.limit?bt(t.limit):"?";e.textContent=`${n||"sync limit reached"} — ${a} of ${i} tokens synced. Nothing was lost. ${x} `,I(e,t.url,s||"memory_quota",o||"See what Pro covers →")}function xt(e,t){wt(l.memoryHint,e,t)}async function St(e){l.memoryHint.textContent="searching…";const t=await kt(e,ot);(function(e,t,n,o=!1){l.memoryResults.innerHTML="";const s=Array.isArray(e)?e:[],a=function(e,t,n,o){return!o||!(!t&&!n)||e.some((e=>function(e){return e&&null!=e.importance?e.importance:5}(e)>=st))}(s,t,n,o),i=!!o&&!t&&!n&&s.length>0&&!a;if(function(e){const t=!!e.hasAny,n=!!e.hasBox,o=!!e.quietNotice;l.tabMemory&&(l.tabMemory.hidden=!(t||n||o)),l.memoryBox&&(l.memoryBox.hidden=!n),l.memoryQuiet&&(l.memoryQuiet.hidden=!o),l.tabMemory&&l.tabMemory.hidden&&"memory"===Qo&&Wo("sessions")}({hasAny:s.length>0,hasBox:a,quietNotice:i}),a){if(n){const e=document.createElement("li");return e.className="empty mem-side-upgrade",l.memoryResults.appendChild(e),void I(e,n.url,"memory_quota","Free plan limit reached — see what Pro covers →")}if(t){const e=document.createElement("li");return e.className="empty",e.textContent=t,void l.memoryResults.appendChild(e)}if(!s.length){const e=document.createElement("li");return e.className="empty",e.textContent="no memory entries",void l.memoryResults.appendChild(e)}for(const e of s){const t=document.createElement("li"),n=document.createElement("span");n.className="mem-side-src",n.textContent=e.source;const o=document.createElement("span");o.className="mem-side-body",o.textContent=e.content||"(empty)",t.appendChild(n),t.appendChild(o),l.memoryResults.appendChild(t)}}})(t.entries,t.error,t.upgrade,""===e),t.upgrade?xt(t.upgrade,"cloud memory needs an active plan"):t.local?l.memoryHint.textContent=Et:l.memoryHint.textContent=t.error||""}const Et="offline — showing this device’s saved copy";function $t(e,t){const n=document.createElement("span");return n.className="mem-chip"+(t?` ${t}`:""),n.textContent=e,n}function Lt(e){const t=document.createElement("li");t.className="mem-card";const n=document.createElement("div");n.className="mem-card-head",n.appendChild($t(e.source,"src")),e.role&&n.appendChild($t(e.role,"role")),null!=e.importance&&n.appendChild($t(`imp ${e.importance}`,"imp")),e.sentiment&&n.appendChild($t(e.sentiment,"sent")),e.summary&&n.appendChild($t("summary","flag"));const o=document.createElement("span");o.className="mem-card-meta";const s=[],a=vt(e.createdAt);a?s.push(a):e.timestamp&&s.push(e.timestamp),e.session&&s.push(`session ${e.session}`),null!=e.tokenCount&&s.push(`${e.tokenCount} tokens`),o.textContent=s.join(" · "),n.appendChild(o),t.appendChild(n);const i=document.createElement("p");i.className="mem-card-body",i.textContent=e.content||"(empty)",t.appendChild(i);const r=[...e.tags,...e.entities];if(r.length){const e=document.createElement("div");e.className="mem-card-pills";for(const t of r)e.appendChild($t(t,"pill"));t.appendChild(e)}return i.addEventListener("click",(()=>{window.getSelection&&String(window.getSelection())||t.classList.toggle("expanded")})),t}function qt(e){const t=new Map;for(const n of it.entries){const o=n[e];o&&t.set(o,(t.get(o)||0)+1)}return[...t.entries()].sort(((e,t)=>t[1]-e[1]))}function Mt(){if(!ct())return;const e=it.entries.length;if(l.memoryList.innerHTML="",function(){if(l.memoryChips.innerHTML="",it.upgrade||it.error)return;const e=[["source","source",qt("source")],["role","role",qt("role")]];for(const[t,n,o]of e){if(o.length<2)continue;const e=document.createElement("div");e.className="mem-chip-group";const s=document.createElement("span");s.className="mem-chip-label",s.textContent=n,e.appendChild(s);for(const[n,s]of o){const o=document.createElement("button");o.type="button",o.className="mem-chip btn"+(it[t]===n?" on":""),o.textContent=`${n} ${s}`,o.addEventListener("click",(()=>{it[t]=it[t]===n?"":n,Mt()})),e.appendChild(o)}l.memoryChips.appendChild(e)}}(),it.loading)return void(l.memoryCount.textContent="loading…");if(it.upgrade){l.memoryCount.textContent="";const e=document.createElement("li");e.className="mem-empty mem-upgrade";const t=document.createElement("strong");t.textContent="Cloud memory is paused on the free plan";const n=document.createElement("span"),o=null!=it.upgrade.used?bt(it.upgrade.used):"?",s=null!=it.upgrade.limit?bt(it.upgrade.limit):"?";return n.textContent=`This account has used ${o} of ${s} tokens of synced conversation. Saved memory is still readable — only new saves are paused until there is room again. `+x,e.appendChild(t),e.appendChild(n),l.memoryList.appendChild(e),void I(e,it.upgrade.url,"memory_quota","Open subscribe page ↗")}if(it.error){l.memoryCount.textContent="";const e=document.createElement("li");return e.className="mem-empty",e.textContent=it.error,void l.memoryList.appendChild(e)}if(!e){l.memoryCount.textContent="0 entries";const e=document.createElement("li");return e.className="mem-empty",e.textContent="No memory entries yet — save a note below, or import from other AI tools.",void l.memoryList.appendChild(e)}const t=it.query.trim().toLowerCase(),n=it.entries.filter((e=>(!it.source||e.source===it.source)&&(!it.role||e.role===it.role)&&(!t||function(e,t){return[e.content,e.source,e.role,e.session,e.sentiment,...e.tags,...e.entities].join("\n").toLowerCase().includes(String(null==t?"":t).toLowerCase())}(e,t)))),o=new Set(it.entries.map((e=>e.source))).size,s=it.local?`offline · saved on this device · ${o} source${1===o?"":"s"}`:`${o} source${1===o?"":"s"}`;if(l.memoryCount.textContent=`${n.length} of ${e} shown · ${s}`+(e>=at?` · newest ${at}`:""),!n.length){const e=document.createElement("li");return e.className="mem-empty",e.textContent="Nothing matches those filters.",void l.memoryList.appendChild(e)}for(const e of n)l.memoryList.appendChild(Lt(e))}async function At(e){it.loading=!0,it.error="",it.upgrade=null,it.local=!1,Mt();const t=await kt(e,at);it.entries=t.entries,it.error=t.error,it.upgrade=t.upgrade,it.local=!0===t.local,it.loading=!1,Mt()}function Nt(){l.memoryOverlay&&(xn({kind:"memory"}),l.memoryOverlay.hidden=!1,document.body.classList.add("memory-open"),l.memoryOverlayQuery.value=l.memoryQuery?l.memoryQuery.value.trim():"",it.query=l.memoryOverlayQuery.value,it.source="",it.role="",Mt(),At(it.query),l.memoryOverlayQuery&&l.memoryOverlayQuery.focus())}function Ht(){l.memoryOverlay&&(l.memoryOverlay.hidden=!0,document.body.classList.remove("memory-open"),l.memoryOpen&&l.memoryOpen.focus())}let Bt=null,It="";function Rt(){return!!l.sessionOverlay&&!l.sessionOverlay.hidden}function Tt(e,t){const n=document.createElement("li");n.className="session-row",n.tabIndex=0;const o=document.createElement("span");o.className="session-title",o.textContent=e&&e.title||e&&e.id||"untitled",n.appendChild(o);const s=document.createElement("span");s.className="session-meta";const a=[],i=e&&Array.isArray(e.messages)&&e.messages.length||0;i&&a.push(`${i} msg${1===i?"":"s"}`),e&&e.updatedAt&&a.push(vt(new Date(e.updatedAt).getTime())||String(e.updatedAt)),t&&e&&e.reason&&a.push(`match: ${e.reason}`),s.textContent=a.join(" · "),n.appendChild(s);const r=()=>{_t(),ms(e.id)};return n.addEventListener("click",r),n.addEventListener("keydown",(e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),r())})),n}function Ot(e){const t=document.createElement("li");t.className="session-row mem-result-row",t.tabIndex=0;const n=document.createElement("span");n.className="session-title mem-result-body",n.textContent=e&&e.content||"(empty)",t.appendChild(n);const o=document.createElement("span");o.className="session-meta";const s=[];if(e&&e.scope&&s.push(e.scope),e&&e.updated){const t=vt(new Date(e.updated).getTime());s.push(t||String(e.updated))}e&&Array.isArray(e.tags)&&e.tags.length&&s.push(e.tags.slice(0,4).join(", ")),o.textContent=s.join(" · "),t.appendChild(o);const a=()=>{_t(),Nt(),l.memoryOverlayQuery&&Bt&&(l.memoryOverlayQuery.value=Bt,it.query=Bt,Mt(),At(Bt))};return t.addEventListener("click",a),t.addEventListener("keydown",(e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),a())})),t}function Ft(e,t){const n=document.createElement("li");return n.className="session-section-head",n.setAttribute("role","presentation"),n.textContent=null==t?e:`${e} · ${t}`,n}async function Dt(e){const t=String(null==e?"":e).trim();if(Bt=t,l.sessionHint&&(l.sessionHint.textContent=t?`searching “${t}”…`:""),!n||"function"!=typeof n.searchSessions)return void(l.sessionHint&&(l.sessionHint.textContent="session search is unavailable in this build."));let o=null;try{o=await n.searchSessions(t,50)}catch(e){return void(l.sessionHint&&(l.sessionHint.textContent=`search failed: ${e&&e.message||e}`))}t===Bt&&(l.sessionHint&&(l.sessionHint.textContent=""),function(e,t){if(!l.sessionList)return;l.sessionList.innerHTML="";const n=e&&e.sessions||[],o=e&&e.memory||[],s=e&&e.memoryStatus||"ok",a="ok"!==s,i="memory"!==It,r=i?n:[];if(l.sessionCount){const t=[`${r.length} session${1===r.length?"":"s"}`];a?t.push("unavailable"===s?"memory needs Node ≥ 22.5":"memory index unreadable"):t.push(`${o.length} memor${1===o.length?"y":"ies"}`),e&&Number.isInteger(e.total)&&e.total>r.length&&i&&(t[0]=`${r.length} of ${e.total} sessions`),l.sessionCount.textContent=t.join(" · ")}if(r.length||o.length){if(r.length){l.sessionList.appendChild(Ft("Sessions",r.length));for(const e of r)l.sessionList.appendChild(Tt(e,t))}if(o.length){l.sessionList.appendChild(Ft("Memory",o.length));for(const e of o)l.sessionList.appendChild(Ot(e))}}else{const e=document.createElement("li");if(e.className="empty",a){const t="unavailable"===s?"needs Node ≥ 22.5":"index could not be read";e.textContent=i?`no matching sessions — memory search ${t}`:`memory search ${t}`}else e.textContent=t?`nothing matches “${t}”`:"nothing to search yet — start a conversation or save a memory";l.sessionList.appendChild(e)}}(o,t))}function Pt(e){l.sessionOverlay&&(It="memory"===e?"memory":"",l.sessionOverlay.hidden=!1,document.body.classList.add("memory-open"),l.sessionQuery&&(l.sessionQuery.value="",l.sessionQuery.focus()),l.sessionHint&&(l.sessionHint.textContent="memory"===It?"memory only — clear to search everything":""),Dt(""))}function Ut(){Pt("memory")}function _t(){l.sessionOverlay&&(l.sessionOverlay.hidden=!0,document.body.classList.remove("memory-open"))}let Kt=null;function jt(){return!!l.importOverlay&&!l.importOverlay.hidden}function Gt(){l.importOverlay&&(l.importOverlay.hidden=!0,document.body.classList.remove("memory-open"),l.importSessionBtn&&l.importSessionBtn.focus())}function Vt(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(Vt(e));const o=(n.sessions||0)>0;l.importSessionsBtn&&(l.importSessionsBtn.disabled=!o),l.importHint&&(l.importHint.textContent=o?"read-only scan — nothing is copied until you press Import sessions":"nothing importable was found; the Memory card can still import memory fragments")}(Kt),Kt}())}async function Wt(){if(!n||"function"!=typeof n.sessionsImport)return;const e=l.importSessionsBtn;e&&(e.disabled=!0),l.importHint&&(l.importHint.textContent="copying sessions into AEGIS…");try{const e=await n.sessionsImport({confirm:!0,limit:500,sync:!(!l.importSync||!l.importSync.checked)});if(!e||!e.ok)return void(l.importHint&&(l.importHint.textContent=`import stopped: ${e&&e.reason||"unknown error"}`));const t=e.skippedExisting?`, ${e.skippedExisting} already here`:"";l.importHint&&(l.importHint.textContent=`imported ${e.imported} session(s)${t}.`),await os()}catch(e){l.importHint&&(l.importHint.textContent=`import failed: ${e&&e.message||e}`)}finally{e&&(e.disabled=!1)}}
|
|
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",settingsGoogleSignin:"settings-google-signin",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",developerCard:"developer-card",devMode:"dev-mode-toggle",devModeHint:"dev-mode-hint",fontScale:"font-scale-select",fontScaleHint:"font-scale-hint",accentSelect:"accent-select",accentHint:"accent-hint",planMode:"plan-mode-toggle",planModeHint:"plan-mode-hint",autoMode:"auto-mode-toggle",autoModeLabel:"auto-mode-label",autoModeHint:"auto-mode-hint",sessionsRefresh:"sessions-refresh",sessionsExport:"sessions-export",sessionsList:"sessions-list",sessionsHint:"sessions-hint",sessionsFilter:"sessions-filter",sessionsCount:"sessions-count",syncNow:"sync-now",syncStatus:"sync-status",sessionMeter:"session-meter",newChat:"new-chat",openCliFace:"open-cli-face",chatCanvas:"chat-canvas",railAutomations:"rail-automations",railSettings:"rail-settings",avatarPaneMount:"avatar-pane-mount",settingsView:"settings-view",automationsView:"automations-view",automationsBack:"automations-back",queueModelField:"queue-model-field",conversationsView:"conversations-view",sideScroll:"side-scroll",settingsBack:"settings-back",settingsJump:"settings-jump",memorySearchForm:"memory-search-form",memoryQuery:"memory-query",memoryResults:"memory-results",memoryEntry:"memory-entry",memorySaveBtn:"memory-save-btn",importSessionBtn:"import-session-btn",importOverlay:"import-overlay",importBackdrop:"import-backdrop",importClose:"import-close",importHint:"import-hint",importList:"import-list",importCount:"import-count",importSync:"import-sync",importSessionsBtn:"import-sessions-btn",importMemoryBtn:"import-memory-btn",memoryHint:"memory-hint",memoryOpen:"memory-open",memoryBox:"memory-box",memoryQuiet:"memory-quiet",memoryQuietFloor:"memory-quiet-floor",paneTabs:"pane-tabs",tabSessions:"tab-sessions",tabMemory:"tab-memory",paneSessions:"pane-sessions",paneMemory:"pane-memory",memoryOverlay:"memory-overlay",memoryBackdrop:"memory-backdrop",memoryClose:"memory-close",memoryFilters:"memory-filters",memoryOverlayQuery:"memory-overlay-query",memoryFiltersClear:"memory-filters-clear",memoryChips:"memory-chips",memoryList:"memory-list",memoryCount:"memory-count",memoryOverlayEntry:"memory-overlay-entry",memoryOverlaySave:"memory-overlay-save",sessionOverlay:"session-overlay",sessionBackdrop:"session-backdrop",sessionClose:"session-close",sessionFilters:"session-filters",sessionQuery:"session-query",sessionClear:"session-clear",sessionHint:"session-hint",sessionList:"session-list",sessionCount:"session-count",paletteOverlay:"palette-overlay",paletteBackdrop:"palette-backdrop",paletteInput:"palette-input",composerMenu:"composer-menu",composerMenuList:"composer-menu-list",composerMenuHint:"composer-menu-hint",paletteList:"palette-list",paletteEmpty:"palette-empty",findBar:"find-bar",findInput:"find-input",findCount:"find-count",findPrev:"find-prev",findNext:"find-next",findClose:"find-close",side:"side",creditsOverlay:"credits-overlay",creditsBackdrop:"credits-backdrop",creditsClose:"credits-close",creditsBody:"credits-body",creditsStatus:"credits-status",creditsLicenceTag:"credits-licence-tag",fpCardStatus:"fp-card-status",fpOpen:"fp-open",fpOverlay:"fp-overlay",messages:"messages",scrollBottom:"scroll-bottom",composer:"composer",prompt:"prompt",send:"send",attachRow:"attach-row",attachNote:"attach-note",dropVeil:"drop-veil",exploreToggle:"explore-toggle",queueTask:"queue-task",queueClassSelect:"queue-class-select",queueModelSelect:"queue-model-select",queueModelInput:"queue-model-input",queueModelHint:"queue-model-hint",queueCwd:"queue-cwd",queueCommit:"queue-commit",queueEnqueue:"queue-enqueue",queueDrain:"queue-drain",queueProceed:"queue-proceed",queueStop:"queue-stop",queueList:"queue-list",queueHint:"queue-hint",queueFanout:"queue-fanout",queueFanoutLabel:"queue-fanout-label",queueAuto:"queue-auto",queueAutoLabel:"queue-auto-label",queueAutoInterval:"queue-auto-interval",queueAutoHint:"queue-auto-hint",queueBoundary:"queue-boundary",queueUpgrade:"queue-upgrade",queueCard:"queue-card",shortcutsOverlay:"shortcuts-overlay",shortcutsBackdrop:"shortcuts-backdrop",shortcutsClose:"shortcuts-close",shortcutsBody:"shortcuts-body",shortcutsCount:"shortcuts-count",keysOverlay:"keys-overlay",keysBackdrop:"keys-backdrop",keysClose:"keys-close",keysCount:"keys-count",keysRowAegis:"keys-row-aegis",keysRowByok:"keys-row-byok",keysAegisState:"keys-aegis-state",keysByokState:"keys-byok-state",keysGotoAegis:"keys-goto-aegis",keysGotoByok:"keys-goto-byok",keysHint:"keys-hint",keysDismiss:"keys-dismiss"},l={};for(const[e,t]of Object.entries(c))Object.defineProperty(l,e,{get:()=>document.getElementById(t),enumerable:!0,configurable:!0});const d="aegis.class",u="aegis.queueClass",m="aegis.autonomous",p="aegis.effort",f="aegis.autonomousWorkers",h="aegis.explore",y="aegis.welcomeConnectDismissed",g="aegis",v=new Set(["__aegis","aegis"]),C="local",k="custom",b="http://localhost:11434",w="https://aegiscloud.org/key?s=desktop&c=key_prompt",x="The autonomous queue keeps running after you close the laptop.",S="https://aegiscloud.org",E=/^[a-z0-9][a-z0-9_-]{0,63}$/;function $(e,t){const n=new URL(`${S}/go/${e}`);n.searchParams.set("s","desktop");const o=null==t?"":String(t).trim().toLowerCase();return E.test(o)&&n.searchParams.set("c",o),n.toString()}function L(e){return $("upgrade",e)}function q(e){return $("topup",e)}const M={welcome_cloud:"welcome",queue_cap:"queue",memory_quota:"memory",status_card:"status",topup_bank:"topup"},A="upgrade_prompt_rendered",N="upgrade_prompt_clicked";let H=!1;function B(e,t){try{const n=M[t];if(!n)return;const o=window.aegis;if(!o||"function"!=typeof o.telemetryEvent)return;const s=o.telemetryEvent(e,{campaign:t,surface:n});s&&"function"==typeof s.catch&&s.catch((()=>{}))}catch(e){if(!H){H=!0;try{console.debug("telemetry: prompt event failed (suppressed)",e)}catch{}}}}function I(e,t,n,o){const s=document.createElement("a");return s.href=function(e,t){const n="topup_bank"===t?q(t):L(t);if(!e)return n;let o;try{o=new URL(e,S)}catch{return e}return o.origin!==S||o.searchParams.get("s")||o.searchParams.get("utm_source")?e:/topup/.test(o.pathname)?q(t):n}(t,n),s.target="_blank",s.rel="noreferrer noopener",s.textContent=o,s.addEventListener("click",(()=>B(N,n))),e.appendChild(s),!1===e.isConnected||e.hidden||B(A,n),s}let R=null,T=null,O=null,D=[],F=[],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"),ao(),Wn(),Xn(),function(){const e=document.getElementById("keys-overlay");if(!e)return;let t=!1;try{t="on"===localStorage.getItem(Co)}catch{}t||null===de?e.hidden=!0:(ko(),Boolean(T)?wo():!0!==de||!0!==ue?bo():wo())}()}let pe=null,fe=null;function he(e){if(!l.updateBanner)return;pe=e;try{bt()}catch{}const t=e&&e.status,n=!t||"idle"===t||"disabled"===t||"checking"===t||"up-to-date"===t||"unavailable"===t;if("decomposed"===t)return l.updateBannerText.textContent="This version is DECOMPOSED — update to the latest release."+(e.version?` v${e.version}`:""),l.updateDownloadBtn.hidden=!0,l.updateRestartBtn.hidden=!0,l.updateRetryBtn&&(l.updateRetryBtn.hidden=!0),void(l.updateBanner.hidden=!1);if(n||t===fe)return void(l.updateBanner.hidden=!0);let o="",s=!1,a=!1,i=!1;const r=e.version?`v${e.version} `:"";if("available"===t)o=e.command?e.commandIsSentence?`Update ${r}available. ${e.command}`:`Update ${r}available — run: ${e.command}`:`Update ${r}available.`,s=!!e.canDownload,s&&(o=`Update ${r}available.`);else if("downloading"===t)o=`Downloading update${"number"==typeof e.progress?` (${Math.round(e.progress)}%)`:""}…`;else if("downloaded"===t)o=`Update ${r}downloaded — restart to install.`,a=!0;else{if("error"!==t)return void(l.updateBanner.hidden=!0);o=`Update check failed: ${e.error||"unknown error"}`,e.transient&&(o+=" — will retry automatically."),i=!0}l.updateBannerText.textContent=o,l.updateDownloadBtn.hidden=!s,l.updateRestartBtn.hidden=!a,l.updateRetryBtn&&(l.updateRetryBtn.hidden=!i),l.updateBanner.hidden=!1}let ye=null;function ge(e){ye=e&&"no-key"===e.status?e.reason:null,ko(),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 Do(),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.")}const qe="nborneklint";function Me(e){l.developerCard&&(l.developerCard.hidden=e!==qe)}async function Ae(t){if(e.setAccountUsername){try{await e.setAccountUsername(t||null)}catch{}Me(t||null)}}function Ne(e){if(!l.devMode||!e)return;const t=!0===e.enabled;l.devMode.checked=t,l.devModeHint.textContent=t?"On — provider failures and aborted turns print their full detail to the console.":"Off — the console stays quiet, same as every other install."}function He(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 Be(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 Ie(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 Re(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 Te=["deny","allow","ask"];function Oe(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 Te){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",(()=>De(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 De(t,n){if(e.permRulesRemove)try{const o=await e.permRulesRemove(t,n);o&&!0===o.ok?(Oe(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 Fe={"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 Pe(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`${Fe[t]||t} Sandbox status unknown: ${e}, so this posture may not be enforced.`}return`${null!==o?o:""} ${Fe[t]||t} Network: ${"open"===n?"allowed":"blocked"}.`.trim()}(e):`could not read the posture: ${e&&e.reason||"unknown error"}`)}async function Ue(){if(l.sandboxMode&&e.getSandboxPolicy)try{Pe(await e.getSandboxPolicy())}catch(e){Pe({ok:!1,reason:e&&e.message||String(e)})}}async function _e(t,n){if(e.setSandboxPolicy)try{Pe(await e.setSandboxPolicy(t,n))}catch(e){l.sandboxStatus&&(l.sandboxStatus.textContent=`not saved: ${e&&e.message?e.message:e}`),Ue()}}let Ke="",je=!1;function Ge(e){Ke=e||"",l.queueHint&&(l.queueHint.textContent=Ke)}function Ve(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",(()=>tt("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",(()=>tt("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 ${wt(e.startedAt)}`:"working");else if("pending"===e.status)e.attempts&&t.push(`${e.attempts} attempt${1===e.attempts?"":"s"}`),e.created&&t.push(`queued ${wt(e.created)}`);else{e.attempts>1&&t.push(`${e.attempts} attempts`);const n=e.finishedAt||e.startedAt||e.created;n&&t.push(wt(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 Qe(e){if(!l.queueList||!e||"object"!=typeof e)return;je=Boolean(e.draining),l.queueCwd&&!l.queueCwd.value&&(l.queueCwd.value=e.defaultCwd||""),l.queueEnqueue&&(l.queueEnqueue.disabled=je),l.queueDrain&&(l.queueDrain.disabled=je),l.queueProceed&&(l.queueProceed.disabled=je),l.queueStop&&(l.queueStop.hidden=!je);const t=Array.isArray(e.items)?e.items:[];if(l.queueList.innerHTML="",t.length)for(const e of t)l.queueList.appendChild(Ve(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}`):je&&n.push("draining…"),n.push(`${e.pending||0} pending`),e.defaultModel&&n.push(`Aegis Cloud · ${e.defaultModel}`),je&&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=[Ke,n.join(" · ")].filter(Boolean).join(" · "))}async function We(){if(!s||!l.queueList)return null;try{const e=await s.list();return Qe(e),e}catch(e){return Ge(`queue list failed: ${e&&e.message?e.message:e}`),null}}let ze=null,Ye=!1;async function Je(){if(ze=null,!Ye){Ye=!0;try{await We()}finally{Ye=!1}}}async function Xe(){if(!s||!l.queueTask)return;const e=l.queueTask.value.trim();if(e){l.queueEnqueue&&(l.queueEnqueue.disabled=!0),Ge("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:Po(),commit:!!l.queueCommit&&l.queueCommit.checked});t&&t.ok?(l.queueTask.value="",Ge(`queued #${t.item.id}`)):Ge(t&&t.reason||"enqueue failed"),Qe(t)}catch(e){Ge(`enqueue failed: ${e&&e.message?e.message:e}`)}finally{l.queueEnqueue&&(l.queueEnqueue.disabled=je)}}else Ge("type a task first")}async function Ze(e){if(s){je=!0,Ge("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());Ge(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)),Qe(t)}catch(e){je=!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),Ge(`drain failed: ${e&&e.message?e.message:e}`)}}}async function et(){if(s){l.queueStop&&(l.queueStop.disabled=!0),Ge("stopping…");try{const e=await s.stop(),t=e&&e.cancelled&&e.cancelled.ok;Ke=t?"stopped the running task":"stop requested",Qe(e)}catch(e){Ge(`stop failed: ${e&&e.message?e.message:e}`)}finally{l.queueStop&&(l.queueStop.disabled=!1)}}}async function tt(e,t){if(s){Ge(`${e} #${t}…`);try{const n=await s[e](t);n&&!1===n.ok?Ge(n.reason||`${e} failed`):Ge(`${"retry"===e?"re-queued":"removed"} #${t}`),Qe(n)}catch(t){Ge(`${e} failed: ${t&&t.message?t.message:t}`)}}}function nt(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 ot(){if(!a||"function"!=typeof a.status)return null;try{const e=await a.status();return nt(e),e}catch(e){return l.queueAutoHint&&(l.queueAutoHint.textContent=`automation status unavailable: ${e&&e.message?e.message:e}`),null}}async function st(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"),nt(e)}catch(e){l.queueAutoHint&&(l.queueAutoHint.textContent=`could not save that: ${e&&e.message?e.message:e}`)}}function at(e){if(!e||"object"!=typeof e)return;const t=null==e.taskId?"":`#${e.taskId} `;if("start"===e.type)Ge(`${t}running${e.model?` on ${e.model}`:""}…`);else if("tool"===e.type&&e.tool)Ge(`${t}${Bo(e.tool)}`);else if("finish"===e.type)Ge(`${t}${e.ok?"done":"failed"} — refreshing`),We(),ot();else if("recovered"===e.type){const t=Array.isArray(e.ids)?e.ids:[];Ge(`recovered ${t.length} stalled task${1===t.length?"":"s"}`),ot()}else"locked"===e.type?(Ge("another drain is already running"),ot()):"queued"===e.type&&Ge(`queued phase ${e.phase}`)}function it(e){const t=e&&e.prompt,o=e&&e.response;if(!t||!o)return;O||(O=Oo());const s=O,a=e&&e.model||"",i=e&&e.class||"",r=i||a?[i?i.toUpperCase():"",a].filter(Boolean).join(" · "):void 0;Eo("user",t),Eo("assistant",o,r,s),D.push({role:"user",content:t}),D.push({role:"assistant",content:o}),n.append(s,{role:"user",content:t}).catch((()=>{})),n.append(s,{role:"assistant",content:o}).catch((()=>{}))}const rt=10,ct=6,lt=50,dt={entries:[],query:"",source:"",role:"",error:"",upgrade:null,local:!1,loading:!1};function ut(){if(mt())return!0;if(Ft())return!0;if(Wt())return!0;if(Zt())return!0;if(sn())return!0;if(mn())return!0;if($n())return!0;if(Tn())return!0;if(pt())return!0;if(ft&&"function"==typeof ft.isOpen)try{return!!ft.isOpen()}catch(e){return!1}return!1}function mt(){return!!l.memoryOverlay&&!l.memoryOverlay.hidden}function pt(){return!!l.keysOverlay&&!l.keysOverlay.hidden}let ft=null,ht=null,yt=!1;async function gt(e){if(!ht)return;if(yt&&!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}();yt=!0,ht.set(n)}function vt(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),Fo(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 Ct="aegis.companion.dismissed";function kt(){const e={keyConfigured:null===de?void 0:de};return Array.isArray(dt.entries)&&dt.entries.length&&(e.memoryCount=dt.entries.length),pe&&"downloaded"===pe.status&&pe.version&&(e.updatePending=String(pe.version)),F.length&&l.modelSelect&&l.modelSelect.options.length>1&&(e.modelCount=l.modelSelect.options.length),e}function bt(){if(!window.aegisCompanion||!l.companionCard||!l.companionText)return;const e=new Date;let t=null;try{t=JSON.parse(localStorage.getItem(Ct)||"null")}catch{t=null}if(window.aegisCompanion.dismissedToday(t,e))return void(l.companionCard.hidden=!0);const n=window.aegisCompanion.pickMessage(kt(),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 wt(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 xt(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 St(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(xt):[];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 Et(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 $t(e,t,n,o,s){if(!e)return;const a=null!=t.used?Et(t.used):"?",i=null!=t.limit?Et(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 Lt(e,t){$t(l.memoryHint,e,t)}async function qt(e){l.memoryHint.textContent="searching…";const t=await St(e,rt);(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)>=ct))}(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"===Jo&&Xo("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?Lt(t.upgrade,"cloud memory needs an active plan"):t.local?l.memoryHint.textContent=Mt:l.memoryHint.textContent=t.error||""}const Mt="offline — showing this device’s saved copy";function At(e,t){const n=document.createElement("span");return n.className="mem-chip"+(t?` ${t}`:""),n.textContent=e,n}function Nt(e){const t=document.createElement("li");t.className="mem-card";const n=document.createElement("div");n.className="mem-card-head",n.appendChild(At(e.source,"src")),e.role&&n.appendChild(At(e.role,"role")),null!=e.importance&&n.appendChild(At(`imp ${e.importance}`,"imp")),e.sentiment&&n.appendChild(At(e.sentiment,"sent")),e.summary&&n.appendChild(At("summary","flag"));const o=document.createElement("span");o.className="mem-card-meta";const s=[],a=wt(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(At(t,"pill"));t.appendChild(e)}return i.addEventListener("click",(()=>{window.getSelection&&String(window.getSelection())||t.classList.toggle("expanded")})),t}function Ht(e){const t=new Map;for(const n of dt.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 Bt(){if(!mt())return;const e=dt.entries.length;if(l.memoryList.innerHTML="",function(){if(l.memoryChips.innerHTML="",dt.upgrade||dt.error)return;const e=[["source","source",Ht("source")],["role","role",Ht("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"+(dt[t]===n?" on":""),o.textContent=`${n} ${s}`,o.addEventListener("click",(()=>{dt[t]=dt[t]===n?"":n,Bt()})),e.appendChild(o)}l.memoryChips.appendChild(e)}}(),dt.loading)return void(l.memoryCount.textContent="loading…");if(dt.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!=dt.upgrade.used?Et(dt.upgrade.used):"?",s=null!=dt.upgrade.limit?Et(dt.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,dt.upgrade.url,"memory_quota","Open subscribe page ↗")}if(dt.error){l.memoryCount.textContent="";const e=document.createElement("li");return e.className="mem-empty",e.textContent=dt.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=dt.query.trim().toLowerCase(),n=dt.entries.filter((e=>(!dt.source||e.source===dt.source)&&(!dt.role||e.role===dt.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(dt.entries.map((e=>e.source))).size,s=dt.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>=lt?` · newest ${lt}`:""),!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(Nt(e))}async function It(e){dt.loading=!0,dt.error="",dt.upgrade=null,dt.local=!1,Bt();const t=await St(e,lt);dt.entries=t.entries,dt.error=t.error,dt.upgrade=t.upgrade,dt.local=!0===t.local,dt.loading=!1,Bt()}function Rt(){l.memoryOverlay&&(Ln({kind:"memory"}),l.memoryOverlay.hidden=!1,document.body.classList.add("memory-open"),l.memoryOverlayQuery.value=l.memoryQuery?l.memoryQuery.value.trim():"",dt.query=l.memoryOverlayQuery.value,dt.source="",dt.role="",Bt(),It(dt.query),l.memoryOverlayQuery&&l.memoryOverlayQuery.focus())}function Tt(){l.memoryOverlay&&(l.memoryOverlay.hidden=!0,document.body.classList.remove("memory-open"),l.memoryOpen&&l.memoryOpen.focus())}let Ot=null,Dt="";function Ft(){return!!l.sessionOverlay&&!l.sessionOverlay.hidden}function Pt(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(wt(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=()=>{Vt(),ys(e.id)};return n.addEventListener("click",r),n.addEventListener("keydown",(e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),r())})),n}function Ut(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=wt(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=()=>{Vt(),Rt(),l.memoryOverlayQuery&&Ot&&(l.memoryOverlayQuery.value=Ot,dt.query=Ot,Bt(),It(Ot))};return t.addEventListener("click",a),t.addEventListener("keydown",(e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),a())})),t}function _t(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 Kt(e){const t=String(null==e?"":e).trim();if(Ot=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===Ot&&(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"!==Dt,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(_t("Sessions",r.length));for(const e of r)l.sessionList.appendChild(Pt(e,t))}if(o.length){l.sessionList.appendChild(_t("Memory",o.length));for(const e of o)l.sessionList.appendChild(Ut(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 jt(e){l.sessionOverlay&&(Dt="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"===Dt?"memory only — clear to search everything":""),Kt(""))}function Gt(){jt("memory")}function Vt(){l.sessionOverlay&&(l.sessionOverlay.hidden=!0,document.body.classList.remove("memory-open"))}let Qt=null;function Wt(){return!!l.importOverlay&&!l.importOverlay.hidden}function zt(){l.importOverlay&&(l.importOverlay.hidden=!0,document.body.classList.remove("memory-open"),l.importSessionBtn&&l.importSessionBtn.focus())}function Yt(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 Jt(){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{Qt=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(Yt(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")}(Qt),Qt}())}async function Xt(){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 rs()}catch(e){l.importHint&&(l.importHint.textContent=`import failed: ${e&&e.message||e}`)}finally{e&&(e.disabled=!1)}}
|
|
4
4
|
// at all before this: the AGPL lived in file headers and LICENSE, the plain
|
|
5
|
-
function zt(){return!!l.creditsOverlay&&!l.creditsOverlay.hidden}function Yt(e,t){const n=document.createElement("section");n.className="credits-section";const o=document.createElement("h3");o.textContent=e,n.appendChild(o);const s=document.createElement("ul");s.className="credits-rows";for(const e of t){const t=document.createElement("li");t.className="credits-row";const n=document.createElement("span");n.className="credits-name",n.textContent=e.name||"",t.appendChild(n);const o=document.createElement("span");if(o.className="credits-meta",o.textContent=[e.version,e.licence,e.copyright].filter(Boolean).join(" · "),t.appendChild(o),e.url){const n=document.createElement("a");n.href=e.url,n.textContent=e.url.replace(/^https?:\/\//,""),n.target="_blank",n.rel="noopener noreferrer",t.appendChild(n)}s.appendChild(t)}return n.appendChild(s),n}function Jt(e){if(!l.creditsBody)return;l.creditsBody.innerHTML="";const t=e&&"object"==typeof e?e:{},n=t.program||{};l.creditsLicenceTag&&(l.creditsLicenceTag.textContent=n.licence||"");const o=document.createElement("section");o.className="credits-section";const s=document.createElement("h3");s.textContent="This program",o.appendChild(s);const a=document.createElement("p");if(a.className="credits-line",a.textContent=`${n.name||"AGPL"} — ${n.licence||""}`,o.appendChild(a),n.copyright){const e=document.createElement("p");e.className="credits-line",e.textContent=n.copyright,o.appendChild(e)}if(n.url){const e=document.createElement("p");e.className="credits-line";const t=document.createElement("a");t.href=n.url,t.textContent="Full licence text",t.target="_blank",t.rel="noopener noreferrer",e.appendChild(t),o.appendChild(e)}if(n.source){const e=document.createElement("p");e.className="credits-line";const t=document.createElement("a");t.href=n.source,t.textContent="Corresponding source",t.target="_blank",t.rel="noopener noreferrer",e.appendChild(t),o.appendChild(e)}if(n.notice){const e=document.createElement("pre");e.className="credits-notice",e.textContent=n.notice,o.appendChild(e)}if(l.creditsBody.appendChild(o),Array.isArray(t.code)&&t.code.length&&l.creditsBody.appendChild(Yt("Vendored third-party code",t.code)),Array.isArray(t.fonts)&&t.fonts.length&&l.creditsBody.appendChild(Yt("Vendored webfonts",t.fonts)),Array.isArray(t.missing)&&t.missing.length){const e=document.createElement("p");e.className="hint",e.textContent=`Could not read: ${t.missing.join(", ")} — the in-app attribution list may be incomplete.`,l.creditsBody.appendChild(e)}}function Xt(){l.creditsOverlay&&(xn({kind:"credits"}),l.creditsOverlay.hidden=!1,document.body.classList.add("memory-open"),async function(){if(!l.creditsBody)return;if(l.creditsStatus&&(l.creditsStatus.textContent="loading…"),!e||"function"!=typeof e.credits)return Jt(null),void(l.creditsStatus&&(l.creditsStatus.textContent=""));let t=null;try{t=await e.credits()}catch(e){return void(l.creditsStatus&&(l.creditsStatus.textContent=`could not read the licence files: ${e&&e.message||e}`))}l.creditsStatus&&(l.creditsStatus.textContent=""),Jt(t)}())}function Zt(){l.creditsOverlay&&(l.creditsOverlay.hidden=!0,document.body.classList.remove("memory-open"))}function en(){return!!l.shortcutsOverlay&&!l.shortcutsOverlay.hidden}function tn(){l.shortcutsOverlay&&(xn({kind:"shortcuts"}),function(){if(!l.shortcutsBody)return;const e=window.aegisShortcuts,t=window.aegis&&window.aegis.platform||navigator.platform||"";if(l.shortcutsBody.textContent="",!e||!Array.isArray(e.SHORTCUTS)){const e=document.createElement("p");return e.className="hint",e.textContent="The shortcut table failed to load (renderer/shortcuts.js).",void l.shortcutsBody.appendChild(e)}let n=0;for(const o of e.groups()){const s=e.rowsFor(o),a=document.createElement("section");a.className="shortcuts-section";const i=document.createElement("h3");i.className="shortcuts-group",i.textContent=o,a.appendChild(i);const r=document.createElement("div");r.className="keys-rows";for(const o of s){n+=1;const s=document.createElement("div");s.className="keys-row";const a=document.createElement("span");a.className="keys-state shortcuts-chord",a.textContent=e.platformize(o.chord,t);const i=document.createElement("div");i.className="keys-body";const c=document.createElement("b");c.textContent=o.label,i.appendChild(c);const l=o.note||o.where;if(l&&i.appendChild(document.createTextNode(` — ${l}`)),o.hidden){const e=document.createElement("span");e.className="hint shortcuts-hidden-note",e.textContent=" Not in the menu; the chord still works.",i.appendChild(e)}s.appendChild(a),s.appendChild(i),r.appendChild(s)}a.appendChild(r),l.shortcutsBody.appendChild(a)}l.shortcutsCount&&(l.shortcutsCount.textContent=`${n} chord${1===n?"":"s"}`)}(),l.shortcutsOverlay.hidden=!1,document.body.classList.add("memory-open"))}function nn(){l.shortcutsOverlay&&(l.shortcutsOverlay.hidden=!0,document.body.classList.remove("memory-open"))}let on=[],sn=-1;function an(){return{cliFace:void 0!==e&&e&&"function"==typeof e.openCliFace}}function rn(){return globalThis.AegisPaletteFilter||null}function cn(){return!!l.paletteOverlay&&!l.paletteOverlay.hidden}function ln(e){if(!l.paletteList)return;const t=rn(),n=function(){const e=globalThis.AegisCommands;return e&&Array.isArray(e.COMMANDS)?e.availableCommands(e.COMMANDS,an()):[]}();on=t?t.filterCommands(n,e):n.slice(),sn=t?t.initialIndex(on):on.length?0:-1,l.paletteList.replaceChildren();for(let e=0;e<on.length;e+=1){const t=on[e],n=document.createElement("li");n.className="palette-row"+(e===sn?" is-active":""),n.id=`palette-row-${e}`,n.setAttribute("role","option"),n.setAttribute("aria-selected",e===sn?"true":"false"),n.dataset.index=String(e);const o=document.createElement("span");if(o.className="palette-row-label",o.textContent=t.label,n.appendChild(o),t.hint){const e=document.createElement("span");e.className="palette-row-hint",e.textContent=t.hint,n.appendChild(e)}n.addEventListener("mousedown",(n=>{n.preventDefault(),sn=e,Pn(t.action)})),l.paletteList.appendChild(n)}l.paletteEmpty&&(l.paletteEmpty.hidden=on.length>0),dn()}function dn(){if(!l.paletteList)return;const e=l.paletteList.children;for(let t=0;t<e.length;t+=1){const n=t===sn;e[t].classList.toggle("is-active",n),e[t].setAttribute("aria-selected",n?"true":"false")}l.paletteInput&&(sn>=0?l.paletteInput.setAttribute("aria-activedescendant",`palette-row-${sn}`):l.paletteInput.removeAttribute("aria-activedescendant"));const t=e[sn];t&&"function"==typeof t.scrollIntoView&&t.scrollIntoView({block:"nearest"})}function un(e){const t=rn();t&&(sn=t.moveIndex(sn,on.length,e),dn())}function mn(){l.paletteOverlay&&(l.paletteOverlay.hidden=!1,document.body.classList.add("memory-open"),l.paletteInput&&(l.paletteInput.value="",l.paletteInput.focus()),ln(""))}function pn(){l.paletteOverlay&&(l.paletteOverlay.hidden=!0,document.body.classList.remove("memory-open"),on=[],sn=-1)}function fn(){if(!l.side)return;const e=l.side.classList.toggle("is-collapsed");l.side.setAttribute("aria-hidden",e?"true":"false")}let hn={query:"",matches:[],index:-1,texts:[]},yn=AegisNavHistory.createHistory(),gn=!1;function vn(){return globalThis.AegisFindInConversation||null}function Cn(){const e="undefined"!=typeof CSS&&CSS.highlights?CSS.highlights:null;if(!e)return;e.delete("find-match"),e.delete("find-match-current");const t=[],n=[];for(let e=0;e<hn.matches.length;e+=1){const o=hn.matches[e],s=hn.texts[o.textIndex];if(!s)continue;const a=document.createRange();a.setStart(s,o.start),a.setEnd(s,o.end),t.push(a),e===hn.index&&n.push(a)}t.length&&e.set("find-match",new Highlight(...t)),n.length&&e.set("find-match-current",new Highlight(...n))}function kn(e){const t=vn();if(!t)return;hn.texts=function(){const e=l.messages;if(!e||"function"!=typeof document.createTreeWalker)return[];const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null),n=[];let o=t.nextNode();for(;o;)o.nodeValue&&o.nodeValue.trim()&&n.push(o),o=t.nextNode();return n}();const n=hn.texts.map((e=>e.nodeValue||""));hn.matches=t.findMatches(n,hn.query,{caseSensitive:!1}),hn.index=hn.matches.length?0:-1,Cn(),l.findCount&&(l.findCount.textContent=t.matchLabel(hn.index,hn.matches.length)),e&&bn()}function bn(){const e=hn.matches[hn.index];if(!e)return;const t=hn.texts[e.textIndex];if(!t)return;const n=t.parentElement;n&&"function"==typeof n.scrollIntoView&&n.scrollIntoView({block:"center",behavior:"smooth"})}function wn(){return!!l.findBar&&!l.findBar.hidden}function xn(e){gn||(yn=AegisNavHistory.pushEntry(yn,e),Sn())}function Sn(){e.setNavState&&e.setNavState({back:AegisNavHistory.canGoBack(yn),forward:AegisNavHistory.canGoForward(yn)}).catch((()=>{}))}function En(e){if(e){gn=!0;try{!function(){for(const e of[l.memoryOverlay,l.creditsOverlay,l.shortcutsOverlay,l.keysOverlay])e&&(e.hidden=!0);document.body.classList.remove("memory-open","keys-open")}(),"settings"===e.kind?ao():"automations"===e.kind?io():"session"===e.kind&&e.id?ms(e.id,{fromNav:!0}):"memory"===e.kind?Nt():"credits"===e.kind?Xt():"shortcuts"===e.kind?tn():"keys"===e.kind?go():ro()}finally{gn=!1}}}function $n(){const e=AegisNavHistory.back(yn);e?(yn=e.state,En(e.entry),Sn()):l.sessionsHint.textContent="already at the start of the history"}function Ln(){const e=AegisNavHistory.forward(yn);e?(yn=e.state,En(e.entry),Sn()):l.sessionsHint.textContent="already at the newest place"}function qn(){l.findBar&&(l.findBar.hidden=!1,l.findInput&&(l.findInput.focus(),"function"==typeof l.findInput.select&&l.findInput.select()),hn.query&&kn(!0))}function Mn(){l.findBar&&(l.findBar.hidden=!0,"undefined"!=typeof CSS&&CSS.highlights&&(CSS.highlights.delete("find-match"),CSS.highlights.delete("find-match-current")),l.prompt&&"function"==typeof l.prompt.focus&&l.prompt.focus())}let An={kind:"",rows:[],index:-1,span:null,query:""};function Nn(){return globalThis.AegisComposerTriggers||null}function Hn(){return!!l.composerMenu&&!l.composerMenu.hidden}const Bn=new Set(["exportJson","toggleSidebar","keys","credits","find"]);function In(){An={kind:"",rows:[],index:-1,span:null,query:""},l.composerMenu&&(l.composerMenu.hidden=!0),l.composerMenuHint&&(l.composerMenuHint.hidden=!0),l.composerMenuList&&l.composerMenuList.replaceChildren()}function Rn(){if(!l.composerMenuList)return;l.composerMenuList.replaceChildren();const e=An.rows;for(let t=0;t<e.length;t+=1){const n=e[t],o=document.createElement("li");o.className="composer-menu-row"+(t===An.index?" is-active":""),o.id=`composer-row-${t}`,o.setAttribute("role","option"),o.setAttribute("aria-selected",t===An.index?"true":"false"),o.dataset.index=String(t);const s=document.createElement("span");if(s.className="composer-menu-label",s.textContent=n.label,o.appendChild(s),n.hint){const e=document.createElement("span");e.className="composer-menu-hint-text",e.textContent=n.hint,o.appendChild(e)}o.addEventListener("mousedown",(e=>{e.preventDefault(),An.index=t,On()})),l.composerMenuList.appendChild(o)}const t=l.composerMenuList.children[An.index];if(t&&"function"==typeof t.scrollIntoView&&t.scrollIntoView({block:"nearest"}),l.composerMenu&&(l.composerMenu.hidden=0===e.length),l.composerMenuHint){const t=0===e.length;l.composerMenuHint.hidden=!t,t&&(l.composerMenuHint.textContent="mention"===An.kind?An.query?`nothing matches “${An.query}”`:"no sessions or memories to mention yet":"no command matches")}e.length&&function(){if(!l.composerMenu)return;const e=l.composer||l.prompt&&l.prompt.parentElement;if(!e)return;const t=e.getBoundingClientRect(),n=l.composerMenu.offsetHeight||0;l.composerMenu.style.left=`${Math.round(t.left)}px`,l.composerMenu.style.width=`${Math.round(t.width)}px`,l.composerMenu.style.top=`${Math.round(t.top-n-6)}px`}()}async function Tn(){const e=Nn(),t=l.prompt;if(!e||!t)return;const o=e.activeTrigger(t.value,t.selectionStart);if(!o)return void(Hn()&&In());const s={start:o.start,end:o.end};let a;if(An.kind=o.kind,An.span=s,An.query=o.query,"slash"===o.kind)a=e.rankRows(function(){const e=globalThis.AegisCommands;return e&&Array.isArray(e.COMMANDS)?e.availableCommands(e.COMMANDS,an()).filter((e=>!Bn.has(e.action))).map((e=>({label:`/${e.label}`,hint:e.hint||"",keywords:e.keywords||"",action:e.action,row:"command"}))):[]}(),o.query);else{a=e.rankRows(await async function(e){if(!n||"function"!=typeof n.searchSessions)return[];let t=null;try{t=await n.searchSessions(e,8)}catch(e){return[]}const o=[],s=Array.isArray(t&&t.memory)?t.memory:[];for(const e of s){const t=String(e&&e.content||"").replace(/\s+/g," ").trim();t&&o.push({label:t.length>72?`${t.slice(0,71)}…`:t,hint:e.scope?`memory · ${e.scope}`:"memory",keywords:Array.isArray(e.tags)?e.tags.join(" "):"",action:"stageMemory",row:"memory",memory:e})}const a=Array.isArray(t&&t.sessions)?t.sessions:[];for(const e of a){const t=String(e&&e.title||"").trim()||"(untitled)";o.push({label:t,hint:"session · open",keywords:"",action:"openSessionRow",row:"session",session:e})}return o}(o.query),o.query);const i=e.activeTrigger(t.value,t.selectionStart);if(!i||"mention"!==i.kind||i.start!==s.start)return}An.rows=a,An.index=a.length?0:-1,Rn()}async function On(){const e=An.rows[An.index],t=l.prompt;if(!e||!t)return void In();const n=An.span,o=An.kind,s=t.value,a=Math.max(0,Math.min(n?n.start:s.length,s.length)),i=Math.max(a,Math.min(n?n.end:s.length,s.length)),r=s.slice(i);if("slash"===o)return t.value=(s.slice(0,a)+r).replace(/\s{2,}/g," ").trimStart(),In(),void Pn(e.action);if(In(),"openSessionRow"===e.action&&e.session)return t.value=(s.slice(0,a)+r).replace(/\s{2,}/g," ").trimStart(),void ms(e.session.id);if("stageMemory"===e.action&&e.memory){const n=e.memory,o=String(n.content||"");Cs.some((e=>"text"===e.kind&&e.text===o))||(Cs.push({kind:"text",name:n.scope?`memory: ${n.scope}`:"memory",path:"",size:o.length,mime:"text/plain",text:o,truncated:!1}),xs());const i=n.scope?`@${n.scope}`:"@memory";t.value=s.slice(0,a)+i+r;const c=a+i.length;t.setSelectionRange(c,c),t.focus()}}function Fn(e){const t=Nn();t&&An.rows.length&&(An.index=t.stepRow(An.rows.length,An.index,e),Rn())}function Dn(e){const t=vn();t&&hn.matches.length&&(hn.index=t.stepMatch(hn.index,hn.matches.length,e),Cn(),l.findCount&&(l.findCount.textContent=t.matchLabel(hn.index,hn.matches.length)),bn())}function Pn(e){switch(pn(),e){case"newChat":return void fs();case"go-back":return void $n();case"go-forward":return void Ln();case"search":return void Pt("");case"find":return void qn();case"settings":return void ao();case"customizations":return ao(),void oo(l.confirmMode);case"automations":return void Promise.all([Ze().catch((()=>{})),je().catch((()=>{}))]).then((()=>io()));case"cli":return void(l.openCliFace&&l.openCliFace.click());case"import":return void(l.importSessionBtn&&l.importSessionBtn.click());case"exportMarkdown":return void ps("markdown");case"exportJson":return void ps("json");case"memory":return void Nt();case"fingerprint":return void(dt&&"function"==typeof dt.open&&dt.open());case"shortcuts":return void tn();case"keys":return void go();case"credits":return void Xt();case"toggleSidebar":return void fn();default:throw new Error(`palette: unknown action ${e}`)}}async function Un(){const t=ct()&&l.memoryOverlayEntry?l.memoryOverlayEntry:l.memoryEntry;if(!t)return;const n=t.value.trim();if(n){l.memorySaveBtn.disabled=!0,l.memoryOverlaySave&&(l.memoryOverlaySave.disabled=!0),l.memoryHint.textContent="saving…";try{const o=await e.memorySave({text:n,source:"aegis-desktop"});if(o&&o.upgrade)return xt(o.upgrade,"free plan limit reached"),void await _n();t.value="",l.memoryHint.textContent=o&&o.queued?"saved offline — syncs when AEGIS is reachable.":"saved.",await _n()}catch(e){l.memoryHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{l.memorySaveBtn.disabled=!1,l.memoryOverlaySave&&(l.memoryOverlaySave.disabled=!1)}}}async function _n(){const e=l.memoryQuery?l.memoryQuery.value.trim():"";await St(e),ct()&&await At(it.query)}function Kn(){const e=yt();return void 0===e.keyConfigured&&delete e.keyConfigured,e}function jn(){const e=document.getElementById("welcome-personal");if(!e)return;const t=function(e){const t=window.aegisCompanion;if(!t||"function"!=typeof t.pickMessage)return null;const n=t.pickMessage(Kn(),new Date);return n&&n.text?{text:n.text,kind:n.kind||"tip"}:null}();if(!t)return e.textContent="",void(e.hidden=!0);e.textContent=t.text,e.dataset.kind=t.kind,e.hidden=!1}const Gn="aegis.welcomeRowsDismissed";function Vn(){const e=window.aegisWelcomeRows;if(!e)return[];try{return e.parseDismissed(localStorage.getItem(Gn))}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(Gn,t.withDismissed(Vn(),e))}catch{}Wn()}}(e.id))),t.appendChild(s),t}function Wn(){const t=document.getElementById("welcome-rows"),n=window.aegisWelcomeRows;if(!t||!n)return;const o=n.pickRows(function(){const t=Kn();return es.length&&(t.sessionCount=es.length),void 0!==e&&e&&"function"==typeof e.openCliFace&&(t.cliAvailable=!0),t}(),Vn());if(t.innerHTML="",o.length){for(const e of o)t.appendChild(Qn(e));t.hidden=!1}else t.hidden=!0}const zn="aegis.welcomeAiLine",Yn=120,Jn=200;function Xn(e){const t=e instanceof Date?e:new Date(null==e?Date.now():e);if(Number.isNaN(t.getTime()))return"";const n=e=>String(e).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}`}function Zn(e){const t=(new Date).getHours(),n=t>=5&&t<12?"morning":t>=12&&t<17?"afternoon":t>=17&&t<22?"evening":"late night",o=[];return"number"==typeof e.memoryCount&&o.push(`${e.memoryCount} entries saved in the user's memory`),"number"==typeof e.modelCount&&o.push(`${e.modelCount} models available`),"string"==typeof e.updatePending&&o.push(`update ${e.updatePending} is downloaded and installs on quit`),!0===e.keyConfigured&&o.push("the account key is connected"),!1===e.keyConfigured&&o.push("no account key is connected yet"),["Write the one sentence shown at the top of a coding assistant's empty",`chat panel. It is ${n} for the person reading it.`,o.length?`What you know about their setup: ${o.join("; ")}.`:"","Rules: one sentence, at most 25 words, second person, no greeting cliché",'like "Welcome back", no exclamation marks, no quotes, no preamble, no',"markdown. Say something specific and useful about their work right now, or","ask one short question that helps them start. Reply with the sentence only."].filter(Boolean).join(" ")}function eo(){const e=document.getElementById("welcome-template");if(!e)return;l.messages.innerHTML="",l.messages.appendChild(e.content.cloneNode(!0)),function(){const e=document.getElementById("chat-greeting");if(!e)return;const t=(new Date).getHours();e.textContent=t>=5&&t<12?"Good morning":t>=12&&t<17?"Good afternoon":t>=17&&t<22?"Good evening":"Working late?"}(),jn(),async function(){const e=document.getElementById("welcome-personal");if(!e)return;if(void 0===t||!t||"function"!=typeof t.chat)return;if(!(!0===de||l.modelSelect&&l.modelSelect.options&&l.modelSelect.options.length>1))return;const n=new Date,o=function(e){let t=null;try{t=JSON.parse(localStorage.getItem(zn)||"null")}catch{t=null}return t&&"string"==typeof t.text&&t.text?t.day!==Xn(e)?null:t.text:null}(n);if(o)return e.textContent=o,e.dataset.kind="ai",void(e.hidden=!1);const s=Kn(),a=l.classSelect&&l.classSelect.value?l.classSelect.value:"aegis",i=l.modelSelect&&l.modelSelect.value?l.modelSelect.value:"",r={class:a,prompt:Zn(s),maxTokens:Yn,tools:!1,singlePass:!0,effort:"low",bestEffort:!0};i&&(r.model=i);let c=null;try{c=await t.chat(r)}catch{return}const d=c&&c.choices&&c.choices[0]||{},u=function(e){let t,n=String(null==e?"":e).trim();if(!n)return"";n=n.replace(/^(assistant|greeting|response)\s*:\s*/i,"");do{t=n,n=n.replace(/^(?:sure|certainly|of course|absolutely|okay|ok|got it|no problem|here(?:'s| is)\b[^.!?:]*)\s*[.!?:,—–-]\s*/i,"")}while(n!==t&&n);const o=n.match(/^["'“”'']([\s\S]+)["'“”'']$/);o&&(n=o[1].trim()),n=n.replace(/\s+/g," ");const s=n.match(/^[\s\S]*?[.!?](?=\s|$)/);if(s&&(n=s[0].trim()),n.length>Jn){const e=n.slice(0,Jn),t=Math.max(e.lastIndexOf(". "),e.lastIndexOf("! "),e.lastIndexOf("? "));n=t>40?e.slice(0,t+1):`${e.replace(/[,;:\s]+$/,"")}…`}return n.length>=12?n:""}(d.message&&d.message.content||"");if(!u)return;const m=document.getElementById("welcome-personal");if(m){m.textContent=u,m.dataset.kind="ai",m.hidden=!1;try{localStorage.setItem(zn,JSON.stringify({day:Xn(n),text:u}))}catch{}}}();const n=document.getElementById("welcome-byok");n&&n.addEventListener("click",uo);const o=document.getElementById("welcome-cloud");o&&o.addEventListener("click",mo);const s=document.getElementById("welcome-dismiss");s&&s.addEventListener("click",fo),to(),Wn()}function to(){const e=document.getElementById("welcome-connect");if(!e)return;let t=!1;try{t="on"===localStorage.getItem(y)}catch{}const n=!0!==de,o=!0!==ue;e.hidden=t||!n&&!o,no("welcome-cloud",!n),no("welcome-cloud-note",!n),no("welcome-byok",!o),no("welcome-byok-note",!o)}function no(e,t){const n=document.getElementById(e);n&&(n.hidden=t)}function oo(e){if(!e)return;const t=e.closest("label")||e;let n=t.parentElement;for(;n;){const e=getComputedStyle(n).overflowY;if("auto"===e||"scroll"===e)break;n=n.parentElement}if(n){const e=n.querySelector(":scope > .settings-view-header"),o=e?e.offsetHeight:0,s=()=>t.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-o,a=()=>n.scrollTo({top:Math.max(0,s()),behavior:"smooth"});a();const i=Date.now()+3e3;let r=s();const c=()=>{const e=s();Math.abs(e-r)>=1&&(r=e,a()),Date.now()<i&&requestAnimationFrame(c)};requestAnimationFrame(c)}else try{t.scrollIntoView({block:"start",behavior:"smooth"})}catch{t.scrollIntoView()}t.classList.add("flash"),setTimeout((()=>t.classList.remove("flash")),1200)}let so=!1;function ao(){l.settingsView&&(l.settingsView.hidden=!1,l.settingsView.scrollTop=0),l.automationsView&&(l.automationsView.hidden=!0),l.chatCanvas&&(l.chatCanvas.hidden=!0),co(l.railSettings),xn({kind:"settings"}),function(){if(so)return;const t=l.avatarPaneMount;if(!t)return;const n="undefined"!=typeof window?window.AegisAvatarPane:null;if(!n||"function"!=typeof n.buildPane)return void(t.textContent="companion pane unavailable in this build");const o="function"==typeof e.personaRead?e.personaRead:null,s="function"==typeof e.personaPatch?e.personaPatch:null;if(!o||!s)return void(t.textContent="companion pane unavailable in this build");let a;try{a=o()}catch(e){return void(t.textContent=`could not read the persona: ${e&&e.message||e}`)}Promise.resolve(a).then((e=>{const o=e&&!1!==e.ok?e:null;let a;try{a=n.buildPane({doc:document,persona:o&&o.persona,capabilities:o&&o.capabilities,onPatch:e=>s(e)})}catch(e){return void(t.textContent=`could not build the pane: ${e&&e.message||e}`)}t.appendChild(a.root),so=!0,o&&Array.isArray(o.warnings)&&o.warnings.length?a.setStatus(`repaired — ${o.warnings.join("; ")}`):o||a.setStatus(e&&e.reason||"could not read the persona")}),(e=>{t.textContent=`could not read the persona: ${e&&e.message||e}`}))}()}function io(){l.automationsView&&(l.automationsView.hidden=!1,l.automationsView.scrollTop=0),l.settingsView&&(l.settingsView.hidden=!0),l.chatCanvas&&(l.chatCanvas.hidden=!0),co(l.railAutomations),xn({kind:"automations"})}function ro(){l.settingsView&&(l.settingsView.hidden=!0),l.automationsView&&(l.automationsView.hidden=!0),l.chatCanvas&&(l.chatCanvas.hidden=!1),co(null),xn({kind:"conversations"})}function co(e){for(const t of[l.railAutomations,l.railSettings]){if(!t)continue;const n=t===e;t.classList.toggle("is-active",n),n?t.setAttribute("aria-current","true"):t.removeAttribute("aria-current")}}function lo(e){if(!e)return;const t=e.closest("section.card")||e;try{t.scrollIntoView({block:"center",behavior:"smooth"})}catch{t.scrollIntoView()}t.classList.add("flash"),setTimeout((()=>t.classList.remove("flash")),1200)}async function uo(){if(po("byok"),Array.from(l.classSelect.options).some((e=>"byok"===e.value))&&"byok"!==l.classSelect.value&&(l.classSelect.value="byok",l.classSelect.dispatchEvent(new Event("change"))),ao(),lo(l.settingsList),!1===de&&l.apiKeyHint&&(l.apiKeyHint.textContent="BYOK needs an AEGIS key too — the handling fee is billed to it. Paste one above, then add your provider key below."),!1===de&&l.apiKeyInput)return l.apiKeyInput.focus(),void lo(l.apiKeyInput);const e=l.settingsList?l.settingsList.querySelector('.setting-row input[type="password"]'):null;e&&e.focus()}function mo(){po("cloud"),ao(),lo(l.apiKeyInput),l.apiKeyInput&&l.apiKeyInput.focus()}function po(e){const t=l.apiKeyHint;if(!t)return;t.textContent="","byok"===e?t.appendChild(document.createTextNode("Bring your own key: everything on this machine stays free, and a local model server needs no account at all. A key relayed through AEGIS is a cloud turn, so it bills a small handling fee — paste the AEGIS key here, then add the provider key in Provider settings. No key yet? ")):t.appendChild(document.createTextNode(`Connect AEGIS Cloud: ${x} Paste your AEGIS key, then Save. Free key at `));const n=document.createElement("a");n.href=w,n.target="_blank",n.rel="noreferrer noopener",n.textContent="aegiscloud.org",t.appendChild(n),t.appendChild(document.createTextNode("."))}function fo(){try{localStorage.setItem(y,"on")}catch{}const e=document.getElementById("welcome-connect");e&&(e.hidden=!0)}const ho="aegis.keysPopupDismissed";function yo(){const e=!0===de,t=!0===ue;l.keysAegisState&&(l.keysAegisState.textContent=e?"set":"not set"),l.keysByokState&&(l.keysByokState.textContent=t?"set":"not set"),l.keysRowAegis&&l.keysRowAegis.classList.toggle("set",e),l.keysRowByok&&l.keysRowByok.classList.toggle("set",t),l.keysCount&&(l.keysCount.textContent=(e?1:0)+(t?1:0)+" / 2"),l.keysAccount&&(l.keysAccount.hidden=!ye,l.keysAccount.textContent=ye?`The AEGIS account key could not be set up: ${ye}.`:""),l.keysAccountRetry&&(l.keysAccountRetry.hidden=!ye),l.keysHint&&(l.keysHint.textContent=e&&t?"Both keys are on this machine — both surfaces run.":`Missing: ${[e?null:"the AEGIS key",t?null:"your provider (BYOK) key"].filter(Boolean).join(" and ")}. Add it above, then both aegis one and the aegiscode CLI run.`)}function go(){l.keysOverlay&&(yo(),l.keysOverlay.hidden&&(xn({kind:"keys"}),l.keysOverlay.hidden=!1,document.body.classList.add("keys-open")))}function vo(){l.keysOverlay&&(l.keysOverlay.hidden=!0,document.body.classList.remove("keys-open"))}function Co(){try{localStorage.setItem(ho,"on")}catch{}vo()}function ko(e,t,n){"assistant"===t&&window.AegisMarkdown?(e.classList.add("md-body"),window.AegisMarkdown.renderInto(e,n)):(e.classList.remove("md-body"),e.textContent=n)}function bo(e,t,n,o,s,a){!function(){const e=document.getElementById("chat-welcome");e&&e.remove()}();const i=document.createElement("div");i.className=`msg ${e}`;const r=document.createElement("div");if(r.className="body",ko(r,e,t),"user"===e&&Array.isArray(a)&&a.length){const e=document.createElement("div");e.className="msg-attachments";for(const t of a){const n=document.createElement("span");n.className="msg-attachment",n.innerHTML=Ms;const o=document.createElement("span");o.textContent=t.name||t.path||"",n.appendChild(o),e.appendChild(n)}i.appendChild(e)}if(Array.isArray(s)&&s.length){const e=document.createElement("div");e.className="tool-activity";for(const t of s){const n=document.createElement("div");n.textContent=Mo(t),e.appendChild(n)}i.appendChild(e)}if(i.appendChild(r),n){const e=document.createElement("div");e.className="meta",e.textContent=n,i.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))),i.appendChild(e)}return l.messages.appendChild(i),ee(),i}function wo(e,n,o){const s=document.createElement("article");s.className="flow-card pending",s.dataset.path=e.key;const a=document.createElement("div");a.className="flow-head";const i=document.createElement("span");i.className="flow-badge",i.textContent=e.badge;const r=document.createElement("span");r.className="flow-title",r.textContent=e.title;const c=document.createElement("span");c.className="flow-state",c.textContent="queued",a.appendChild(i),a.appendChild(r),a.appendChild(c);const l=document.createElement("div");l.className="flow-body",l.textContent="…";const d=document.createElement("div");d.className="flow-meta";const u=document.createElement("button");u.type="button",u.className="ghost-btn flow-abort",u.textContent="stop",u.addEventListener("click",(()=>{s.dataset.session&&t.cancel(s.dataset.session),c.textContent="stopped",s.classList.remove("pending"),s.classList.add("stopped"),u.remove()})),s.appendChild(a),s.appendChild(l),s.appendChild(d),s.appendChild(u);const m=n.querySelector(".flow-add");return m?n.insertBefore(s,m):n.appendChild(s),async function(e,n){const o=`${n.parentSessionId}::flow${++Q}`;e.dataset.session=o,W.add(o);const s=e.querySelector(".flow-body"),a=e.querySelector(".flow-state"),i=e.querySelector(".flow-meta");let r="";const c=t=>{if(t&&t.approval)return e.classList.contains("pending")&&(e.classList.remove("pending"),a.textContent="needs approval"),void Ho(e,t.approval,".flow-body");if(t&&t.tool)return e.classList.contains("pending")&&(e.classList.remove("pending"),a.textContent="streaming…"),"run"===t.tool.phase?void qo(t.tool):void Ao(e,t.tool,"flow-tools",".flow-body");const n=t&&("string"==typeof t.delta?t.delta:t.content);n&&(e.classList.contains("pending")&&(e.classList.remove("pending"),a.textContent="streaming…"),r+=n,s.textContent=r,function(e){return e.parentElement}(e)&&function(e){const t=e.nextElementSibling;return!t||t.classList.contains("flow-add")}(e)&&e.scrollIntoView({block:"nearest",inline:"end"}))};try{const l=await t.chat({class:n.cls,system:`${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)";ko(s,"assistant",u),e.classList.remove("pending"),e.classList.add("done"),a.textContent="done";const m=[n.path.title];l&&l.model?m.push(l.model):n.model&&m.push(n.model);const p=turnAccounting(l&&l.usage,n.model,{costUsd:l&&"number"==typeof l.costUsd?l.costUsd:void 0}),f=displayTokens(p);null!=f&&m.push(`${f} tokens`),null!=p.cost&&m.push(fmtCost(p.cost,p.real));const h=_(n.parentSessionId,l&&l.usage,{model:n.model,costUsd:l&&"number"==typeof l.costUsd?l.costUsd:void 0,calls:l&&l.calls,turns:0,prompt:`Original request:\n${n.prompt}\n\n${n.path.hint}`,reply:u}),y=fmtRoll(h);y&&m.push(`session: ${y}`),i.textContent=m.join(" · ")}catch(t){const o=t&&t.message?t.message:String(t);e.classList.remove("pending"),e.classList.add("stopped"),a.textContent="stopped",s.textContent=r||`Path unavailable: ${o}`,i.textContent=n.path.title}finally{W.delete(o);const t=e.querySelector(".flow-abort");t&&t.remove()}}(s,{...o,path:e}),s}function xo(){return R||(R=bo("assistant",""),R.classList.remove("pending"),R)}function So(e,{cancellable:t}={}){if(l.send.disabled=e,l.prompt.disabled=e,e){R=bo("assistant",""),R.classList.add("pending");const e=document.createElement("span");e.className="typing-dots";for(let t=0;t<3;t++)e.appendChild(document.createElement("span"));R.querySelector(".body").appendChild(e);const n=document.createElement("span");if(n.className="typing-tokens",n.hidden=!0,R.appendChild(n),t){const e=document.createElement("button");e.type="button",e.className="cancel-btn",e.textContent="cancel",e.addEventListener("click",(()=>ne())),R.appendChild(e)}}else R&&(R.remove(),R=null)}const Eo=72,$o=new Set(["editFile","writeFile","Edit","Write","MultiEdit"]),Lo=new Map;function qo(e){if(!e||!$o.has(e.name)||null==e.id)return;const t=e.cwd,n=editPreview(e.name,e.args,{cwd:t,readFile:e=>function(e,t){try{const n="undefined"!=typeof window?window.aegis:null;if(n&&"function"==typeof n.readTextFile)return n.readTextFile(e,t)}catch{}}(e,t)});n&&Lo.set(e.id,n)}function Mo(e){const{name:t,args:n}=e||{},o=toolMark(e),s=n||{};if("task"===t){const e=s.subagent_type&&"general"!==s.subagent_type?s.subagent_type:"general";return`→ task ▸ ${s.description||"subagent"} (${e}) ${o}`}const a=s.file_path||s.path||s.command||s.pattern||s.query||s.description||"",i=String(a).replace(/\s+/g," ").trim(),r=i.length>Eo?`${i.slice(0,Eo-1)}…`:i;return`→ ${t}${r?` ${r}`:""} ${o}`}function Ao(t,n,o,s){if(!t)return;let a=t.querySelector(`.${o}`);if(!a){a=document.createElement("div"),a.className=o;const e=s?t.querySelector(s):null;e?t.insertBefore(a,e):t.appendChild(a)}const i=n&&null!=n.id?Lo.get(n.id):null;if(i){Lo.delete(n.id);const t=renderDiffBlock(i,document);if(t)return a.appendChild(t),function(t,n){if(!t||!n||null==n.id||!1===n.ok)return;if("writeFile"!==n.name&&"editFile"!==n.name)return;if(!e||"function"!=typeof e.undoMutation)return;const o=document.createElement("div");o.className="diff-undo-row";const s=document.createElement("span");s.className="diff-undo-link",s.textContent="⎿ undo this edit",s.setAttribute("role","button"),s.tabIndex=0;const a=async()=>{s.removeEventListener("click",a),s.tabIndex=-1,s.textContent="⎿ undoing…";try{const t=await e.undoMutation(O,n.id);s.textContent=t&&t.ok?"⎿ "+("deleted"===t.restored?"undone — file deleted (it was new)":"undone — content restored"):`⎿ undo failed — ${t&&t.error||"unknown error"}`,s.className=t&&t.ok?"diff-undo-link diff-undo-done":"diff-undo-link diff-undo-failed"}catch(e){s.textContent=`⎿ undo failed — ${e&&e.message||e}`,s.className="diff-undo-link diff-undo-failed"}};s.addEventListener("click",a),s.addEventListener("keydown",(e=>{!e||"Enter"!==e.key&&" "!==e.key||("function"==typeof e.preventDefault&&e.preventDefault(),a())})),o.appendChild(s),t.appendChild(o)}(a,n),a}const r=document.createElement("div");return r.textContent=Mo(n),a.appendChild(r),a}function No(e){return e.startsWith("@@")?"diff-hunk":e.startsWith("+++")||e.startsWith("---")?"diff-file":e.startsWith("+")?"diff-add":e.startsWith("-")?"diff-del":"diff-ctx"}function Ho(e,n,o){if(!e||!n)return;const s=document.createElement("div");s.className="approval-card",s.dataset.approvalId=n.id;const a=document.createElement("div");a.className="approval-title",a.textContent=`${n.tool} wants to run — review before it executes`,s.appendChild(a);const i=function(e,t){const n=t||{};return"exec"===e?n.description?`${n.command} — ${n.description}`:n.command||"":n.file_path||""}(n.tool,n.args);if(i){const e=document.createElement("div");e.className="approval-summary",e.textContent=i,s.appendChild(e)}if(n.diff){const e=document.createElement("pre");e.className="approval-diff";for(const t of n.diff.split("\n")){const n=document.createElement("div");n.className=No(t),n.textContent=t,e.appendChild(n)}s.appendChild(e)}const r=document.createElement("div");r.className="approval-actions";const c=(e,o,a)=>{const i=document.createElement("button");return i.type="button",i.className=`approval-btn ${o}`,i.textContent=e,i.addEventListener("click",(()=>(e=>{for(const e of r.querySelectorAll("button"))e.disabled=!0;s.classList.add("resolved");const o=document.createElement("div");o.className="approval-decision",o.textContent="deny"===e?"Denied":"session"===e?"Allowed for this session":"always"===e?"Always allowed":"Allowed once",s.appendChild(o),t.respondApproval(n.id,e)})(a))),i};if(r.appendChild(c("Allow once","allow","once")),r.appendChild(c("Allow for this session","allow-session","session")),n.canPersist){const e=c("Always allow this command","allow-always","always");e.title="Stores a rule in ~/.aegiscode/permissions.json, shared with the terminal face",r.appendChild(e)}r.appendChild(c("Deny","deny","deny")),s.appendChild(r);let l=e.querySelector(".approval-slot");if(!l){l=document.createElement("div"),l.className="approval-slot";const t=o?e.querySelector(o):null;t?e.insertBefore(l,t):e.appendChild(l)}return l.appendChild(s),s}function Bo(){try{if(globalThis.crypto&&"function"==typeof globalThis.crypto.randomUUID)return globalThis.crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}async function Io(){try{D=await t.listClasses()||[]}catch(e){D=[],l.modelHint.textContent=`listClasses failed: ${e&&e.message?e.message:e}`}l.classSelect.innerHTML="";for(const e of D){const t=document.createElement("option");t.value=e.class,t.textContent=e.configured?e.label:`${e.label} (not configured)`,l.classSelect.appendChild(t)}const e=localStorage.getItem(d);e&&D.some((t=>t.class===e))&&(l.classSelect.value=e),await Ro(l.classSelect.value)}async function Ro(e){if(l.autonomousToggleWrap&&(l.autonomousToggleWrap.hidden=e!==g),se(),ie(e),l.modelSelect.hidden=!1,l.modelSelect.disabled=!1,l.modelFree.hidden=!0,l.modelFree.value="",l.modelHint.textContent="",l.modelSelect.innerHTML="",P=new Map,"aegis"===e){const e=document.createElement("option");e.value=i,e.textContent=r,l.modelSelect.appendChild(e)}try{const n=await t.listModels(e),o=Array.isArray(n&&n.models)?n.models:[],s=Boolean(n&&n.needsKey),a=Boolean(n&&n.needsDaemon),i=!(n&&!1===n.listed),r=Boolean(n&&n.providersFailed),c=Array.isArray(n&&n.unmatchedProviders)?n.unmatchedProviders:[];l.modelFree.hidden=!("local"===e&&(a||!i));for(const e of o){P.set(e.id,e);const t=document.createElement("option");t.value=e.id,t.textContent=e.label||e.id,l.modelSelect.appendChild(t)}let d;if(re(),s)d=null;else if(a)d=`No local model server at ${n&&n.baseURL||"the configured address"} — start Ollama, or set Base URL below to llama.cpp / LM Studio, then Refresh.`;else if("local"!==e||i)if("byok"===e&&r)d="Provider catalog unreachable — your saved keys and declared models are unaffected. Refresh to try again."+(n&&n.providersError?` (${n.providersError})`:"");else if(o.length)if("byok"===e&&n&&n.needsAegisKey){const e=n&&n.fee||null;d=`${o.length} model${1===o.length?"":"s"} available — `+(e&&e.require_balance?"an AEGIS account key and a funded balance are required: the BYOK handling fee is billed there.":"an AEGIS account key is required: the BYOK handling fee is billed there.")}else d="byok"===e&&n&&n.needsProviderKey?`${o.length} model${1===o.length?"":"s"} available — add a provider key in Provider settings below to use one.`:`${o.length} model${1===o.length?"":"s"} available.`;else d="local"===e?"No models on this server yet — pull one first (ollama pull llama3.2).":"aegis"===e?"No models to pin — this class runs the pooled route on the server's own default. Use Bring your own key for a per-provider model.":"No models listed.";else d="That address answered but listed no models — not Ollama? Type the model tag in the box above and send.";"byok"===e&&!r&&c.length&&(d=`${d} Not shown: ${c.join(", ")} — declared in models.json, but not in the provider catalog. Check the provider name in Settings.`);const u=maxTokensCeiling(P.get(ae()));if(s){l.modelHint.textContent="Connect Aegis Cloud to load its models: paste your AEGIS API key in the Status card above (";const e=document.createElement("a");return e.href=w,e.target="_blank",e.rel="noreferrer noopener",e.textContent="free key at aegiscloud.org",l.modelHint.appendChild(e),void l.modelHint.appendChild(document.createTextNode("), then Save."))}l.modelHint.textContent=u<FLAT_CEILING?`${d} · max output: ${u.toLocaleString()}`:d}catch(e){P=new Map,l.modelHint.textContent=`listModels failed: ${e&&e.message?e.message:e}`,re()}}function To(){if(l.queueModelInput&&!l.queueModelInput.hidden){const e=l.queueModelInput.value.trim();if(e)return e}return l.queueModelSelect?l.queueModelSelect.value:""}async function Oo(e){if(l.queueModelSelect){if(function(e){const t=l.queueFanout&&l.queueFanout.closest("label");t&&(t.hidden="aegis"!==e)}(e),l.queueModelSelect.hidden=!1,l.queueModelSelect.disabled=!1,l.queueModelInput&&(l.queueModelInput.hidden=!0,l.queueModelInput.value=""),l.queueModelField&&(l.queueModelField.hidden=!0),l.queueModelHint&&(l.queueModelHint.textContent=""),l.queueModelSelect.innerHTML="","aegis"===e){const e=document.createElement("option");e.value="",e.textContent="server default (auto)",l.queueModelSelect.appendChild(e)}try{const n=await t.listModels(e),o=Array.isArray(n&&n.models)?n.models:[],s=Boolean(n&&n.needsKey),a=Boolean(n&&n.needsDaemon),i=!(n&&!1===n.listed);l.queueModelInput&&(l.queueModelInput.hidden=!("local"===e&&(a||!i))),l.queueModelField&&(l.queueModelField.hidden=!("local"===e&&(a||!i)));for(const e of o){const t=document.createElement("option");t.value=e.id,t.textContent=e.label||e.id,l.queueModelSelect.appendChild(t)}if(!l.queueModelHint)return;s?l.queueModelHint.textContent="Connect this class in the Model card above (API key / provider key), then Refresh.":a?l.queueModelHint.textContent=`No local model server at ${n&&n.baseURL||"the configured address"} — start it, then reopen this picker.`:"local"!==e||i?o.length?"byok"===e&&n&&n.needsProviderKey&&(l.queueModelHint.textContent="A provider key is required before a queued task on this model can run — add one in the Model card above."):l.queueModelHint.textContent="local"===e?"No models on this server yet — pull one first (ollama pull llama3.2).":"aegis"===e?"No models to pin — this runs the pooled route on the server's own default.":"No models listed.":l.queueModelHint.textContent="That address answered but listed no models — type the model tag above."}catch(e){l.queueModelHint&&(l.queueModelHint.textContent=`listModels failed: ${e&&e.message?e.message:e}`)}}}function Fo({provider:e,name:t,cfg:n,onSave:o,onRemove:s}){const a=document.createElement("div");a.className="setting-row",a.dataset.provider=e;const i=document.createElement("div");i.className="setting-name",i.textContent=t,a.appendChild(i);const r=document.createElement("input");r.type="password",r.className="setting-input",r.placeholder=n.configured?`key ${n.keyMask} (blank = keep)`:"API key",a.appendChild(r);const c=document.createElement("div");c.className="setting-status",c.textContent=n.configured?`configured (${n.keyMask})`:"no key",c.dataset.state=n.configured?"configured":"unset",a.appendChild(c);const l=document.createElement("div");l.className="setting-actions";const d=document.createElement("button");d.type="button",d.className="ghost-btn btn-primary btn-sm",d.textContent="Save",d.addEventListener("click",(()=>o(r.value))),l.appendChild(d);const u=document.createElement("button");return u.type="button",u.className="ghost-btn danger",u.textContent="Remove",u.disabled=!n.configured,u.addEventListener("click",s),l.appendChild(u),a.appendChild(l),a}async function Do(e){l.settingsHint.textContent="saving…";try{const n=String(null==e?"":e).trim()||b,o=await t.settings.set(C,{baseURL:n}),s=o&&o.baseURL||n;l.settingsHint.textContent=`saved: local model server at ${s}`,await Po(),await Ro(l.classSelect.value)}catch(e){l.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function Po(){l.settingsList.innerHTML="";const e=[];let n=[];try{n=await t.settings.get()||[]}catch{}Array.isArray(n)&&(n=n.filter((e=>e&&!v.has(e.provider))));{const e=n.find((e=>e&&e.provider===C))||{provider:C,baseURL:"",configured:!1,keyMask:null};l.settingsList.appendChild(function(e){const t=C,n=document.createElement("div");n.className="setting-row",n.dataset.provider=t;const o=document.createElement("div");o.className="setting-name",o.textContent="Local model server",n.appendChild(o);const s=document.createElement("input");s.type="text",s.className="setting-input",s.id="local-base-url",s.autocomplete="off",s.spellcheck=!1,s.placeholder=b,s.value=e.baseURL||"",s.addEventListener("keydown",(e=>{"Enter"===e.key&&Do(s.value)})),n.appendChild(s);const a=document.createElement("div");a.className="setting-status",a.textContent=e.baseURL?e.baseURL:`default (${b})`,a.dataset.state=e.baseURL?"configured":"unset",n.appendChild(a);const i=document.createElement("div");i.className="setting-actions";const r=document.createElement("button");r.type="button",r.className="ghost-btn btn-primary btn-sm",r.textContent="Save",r.addEventListener("click",(()=>Do(s.value))),i.appendChild(r);const c=document.createElement("button");return c.type="button",c.className="ghost-btn danger",c.textContent="Reset",c.disabled=!e.baseURL,c.addEventListener("click",(()=>Go(t))),i.appendChild(c),n.appendChild(i),n}(e))}try{const o=await t.listModels("byok"),s=Array.isArray(o&&o.providers)?o.providers:[];for(const t of s){if(!t||!t.id)continue;if(e.push({id:t.id,label:t.label||t.id}),t.id===k)continue;const o=`byok:${t.id}`,s=n.find((e=>e.provider===o))||{provider:o,baseURL:"",configured:!1,keyMask:null};l.settingsList.appendChild(Fo({provider:o,name:`BYOK: ${t.label||t.id}`,cfg:s,onSave:e=>jo(o,e),onRemove:()=>Go(o)}))}const a=o&&o.fee;if(a&&!a.disabled&&(Number(a.in_usd_per_1k)>0||Number(a.out_usd_per_1k)>0)){const e=document.createElement("div");e.className="setting-row",e.id="byok-fee-note";const t=document.createElement("div");t.className="setting-name";const n=e=>`${Number(e).toFixed(4)}`;t.textContent=`BYOK handling fee: ${n(a.in_usd_per_1k)} / 1k in, ${n(a.out_usd_per_1k)} / 1k out — billed to your AEGIS account on top of your own provider bill. This is the published rate, not a personal quote — Unlimited subscribers pay no handling fee at all, and neither do users on the free 1-month Unlimited trial.`,e.appendChild(t),l.settingsList.appendChild(e)}}catch{}try{await async function(e){if(!l.settingsList||!t.userModels)return;const n=await t.userModels.get();if(!n)return;const o=n&&n.map||{},s=(e||[]).map((e=>e&&e.id||"")).filter(Boolean),a=document.createElement("div");a.id="user-models-block";const i=document.createElement("div");i.className="setting-name",i.textContent="Your own models (BYOK)",a.appendChild(i);const r=document.createElement("div");r.className="setting-row",r.dataset.provider="byok:__user-model-add";const c=document.createElement("input");if(c.type="text",c.className="setting-input",c.id="user-model-provider",c.placeholder="provider (deepseek)",c.autocomplete="off",c.spellcheck=!1,s.length){const e=document.createElement("datalist");e.id="user-model-providers";for(const t of s){const n=document.createElement("option");n.value=t,e.appendChild(n)}r.appendChild(e),c.setAttribute("list","user-model-providers")}r.appendChild(c);const d=document.createElement("input");d.type="text",d.className="setting-input",d.id="user-model-id",d.placeholder="model id (deepseek-v4.2-preview)",d.autocomplete="off",d.spellcheck=!1,r.appendChild(d);const u=document.createElement("div");u.className="setting-actions";const m=document.createElement("button");m.type="button",m.className="ghost-btn",m.id="user-model-add",m.textContent="Add model",m.addEventListener("click",(async()=>{const e=c.value.trim(),n=d.value.trim();l.settingsHint.textContent="adding…";try{const o=await t.userModels.add(e,n);l.settingsHint.textContent=o&&!1===o.added?`${o.provider}:${o.model} was already declared.`:`added ${o.provider}:${o.model} — /models and the picker now offer it.`,await Po(),await Ro(l.classSelect.value)}catch(e){l.settingsHint.textContent=`${e&&e.message?e.message:e}`}})),u.appendChild(m);const p=document.createElement("button");p.type="button",p.className="ghost-btn",p.id="user-model-discover",p.textContent="List from provider",u.appendChild(p);const f=document.createElement("div");f.className="setting-status",f.id="user-model-discovered",f.hidden=!0,p.addEventListener("click",(async()=>{const e=c.value.trim();if(!e)return void(l.settingsHint.textContent="type a provider id first (the CLI's /byok lists them).");if("function"!=typeof t.userModels.discover)return void(l.settingsHint.textContent="this build cannot ask a provider — type the model id.");let n;l.settingsHint.textContent=`asking ${e}…`,f.hidden=!0,f.textContent="";try{n=await t.userModels.discover(e)}catch(e){return void(l.settingsHint.textContent=`${e&&e.message?e.message:e}`)}if(!n||!n.ok)return void(l.settingsHint.textContent=`${e}: ${n&&n.error||"no answer"}`);l.settingsHint.textContent=`${n.provider} serves ${n.count} chat model id(s) — pick one and Add model, or add them all.`;const o=document.createElement("select");o.className="setting-input",o.id="user-model-discovered-list";for(const e of n.ids){const t=document.createElement("option");t.value=e,t.textContent=n.declared&&n.declared.includes(e)?`${e} — declared`:e,o.appendChild(t)}if(o.addEventListener("change",(()=>{d.value=o.value})),n.ids.length){d.value=n.ids[0],f.appendChild(o);const e=document.createElement("button");e.type="button",e.className="ghost-btn",e.id="user-model-add-all",e.textContent=`Add all ${n.count}`,e.addEventListener("click",(async()=>{l.settingsHint.textContent=`adding ${n.count}…`;try{const e=await t.userModels.addAll(n.provider,n.ids);l.settingsHint.textContent=`added ${e.added} of ${n.ids.length}`+(e.already&&e.already.length?` (${e.already.length} were already declared)`:"")+(e.failed&&e.failed.length?` — ${e.failed.length} refused`:"")+".",await Po(),await Ro(l.classSelect.value)}catch(e){l.settingsHint.textContent=`${e&&e.message?e.message:e}`}})),f.appendChild(e)}else f.textContent="the vendor answered with no chat models — type an id above.";if(n.others&&n.others.length){const e=document.createElement("div");e.textContent=`${n.others.length} non-chat id(s) left out: ${n.others.slice(0,6).join(", ")}`,f.appendChild(e)}f.hidden=!1})),r.appendChild(u),r.appendChild(f);const h=document.createElement("div");h.className="setting-status",h.id="user-model-hint",h.textContent=n.file?`saved in ${n.file} — the CLI reads the same file (/model-add)`:"saved beside your AEGIS config — the CLI reads the same file (/model-add)",r.appendChild(h),a.appendChild(r);const y=Object.keys(o).sort();for(const e of y)for(const n of o[e]){const o=document.createElement("div");o.className="setting-row",o.dataset.provider=`byok:${e}`;const i=document.createElement("div");i.className="setting-name",i.textContent=`${e} — ${n}`,o.appendChild(i);const r=document.createElement("div");r.className="setting-status",r.textContent=s.length&&!s.includes(e)?"no provider row for this id — /byok lists the ones the relay takes":"offered in the picker on this machine",o.appendChild(r);const c=document.createElement("div");c.className="setting-actions";const d=document.createElement("button");d.type="button",d.className="ghost-btn danger",d.textContent="Remove",d.addEventListener("click",(async()=>{l.settingsHint.textContent="removing…";try{const o=await t.userModels.remove(e,n);l.settingsHint.textContent=o&&!1===o.removed?`${e}:${n} was not declared.`:`removed ${e}:${n}.`,await Po(),await Ro(l.classSelect.value)}catch(e){l.settingsHint.textContent=`${e&&e.message?e.message:e}`}})),c.appendChild(d),o.appendChild(c),a.appendChild(o)}const g=n&&n.invalid||[];for(const e of g){const t=document.createElement("div");t.className="setting-row";const n=document.createElement("div");n.className="setting-name",n.textContent=`${e.provider||"models.json"}: ${null==e.model?"":String(e.model)}`.trim(),t.appendChild(n);const o=document.createElement("div");o.className="setting-status",o.textContent=`skipped — ${e.reason}`,t.appendChild(o),a.appendChild(t)}l.settingsList.appendChild(a)}(e)}catch(e){l.settingsHint.textContent=`your own models: ${e&&e.message?e.message:e}`}try{await Uo()}catch(e){l.customStatus&&(l.customStatus.textContent=`custom provider: ${e&&e.message?e.message:e}`)}}async function Uo(){if(!l.customBaseUrl)return;let e=null,n=[];try{const n=await t.settings.get()||[],o=(Array.isArray(n)?n:[]).find((e=>e&&e.provider===`byok:${k}`));o&&(e={baseURL:o.baseURL||"",configured:Boolean(o.configured),keyMask:o.keyMask})}catch{}try{const e=await t.userModels.get(),o=e&&e.map||{};n=Array.isArray(o[k])?o[k]:[]}catch{}!function(e,t){if(!l.customBaseUrl)return;const n=e||{},o=Array.isArray(t)?t:[];if(!l.customBaseUrl.value&&n.baseURL&&(l.customBaseUrl.value=n.baseURL),l.customKey&&(l.customKey.placeholder=n.configured?`key ${n.keyMask||"••••"} (blank = keep)`:"sk-…",l.customKey.value=""),l.customRemove&&(l.customRemove.disabled=!n.configured&&!n.baseURL),!l.customStatus)return;const s=[];n.baseURL?s.push(`endpoint ${n.baseURL}`):s.push("no endpoint saved"),s.push(n.configured?`key ${n.keyMask||"saved"}`:"no key"),s.push(o.length?`model${1===o.length?"":"s"} ${o.join(", ")}`:"no model declared"),l.customStatus.textContent=s.join(" · ")}(e,n)}async function _o(){if(!l.customBaseUrl)return;const e=String(l.customBaseUrl.value||"").trim(),n=l.customKey?String(l.customKey.value||"").trim():"",o=l.customModel?String(l.customModel.value||"").trim():"",s=e=>{l.customStatus&&(l.customStatus.textContent=e)};if(!e)return void s("an address is required — aegis1 dials the endpoint you name, and refuses a custom call that names none.");if(!/^https:\/\//i.test(e))return void s("refused: only an https:// endpoint is dialed — aegis1 rejects a plain-http or scheme-less base URL for this provider.");if(!o)return void s("a model id is required — the `custom` provider pins no default, so nothing would be selectable in the picker.");s("saving…");const a=`byok:${k}`;try{const o={};o.baseURL=e,n&&(o.key=n),await t.settings.set(a,o)}catch(e){return void s(`endpoint not saved: ${e&&e.message?e.message:e}`)}try{await t.userModels.add(k,o)}catch(e){return s(`endpoint saved, model NOT declared: ${e&&e.message?e.message:e}`),await Uo(),void await Ro(l.classSelect.value).catch((()=>{}))}l.customModel&&(l.customModel.value=""),s(`saved ${e} with model ${o} — pick it under provider "byok", then the model.`),await Uo(),await Po(),await Ro(l.classSelect.value).catch((()=>{}))}async function Ko(){if(!l.customBaseUrl)return;const e=e=>{l.customStatus&&(l.customStatus.textContent=e)};e("removing…");let n=0;try{const e=await t.userModels.get(),o=e&&e.map||{},s=Array.isArray(o[k])?o[k]:[];for(const e of s)await t.userModels.remove(k,e),n+=1}catch{}try{await t.settings.remove(`byok:${k}`)}catch(t){return void e(`remove failed: ${t&&t.message?t.message:t}`)}l.customBaseUrl&&(l.customBaseUrl.value=""),e(`removed the custom endpoint${n?` and ${n} declared model(s)`:""}.`),await Uo(),await Po(),await Ro(l.classSelect.value).catch((()=>{}))}async function jo(e,n){l.settingsHint.textContent="saving…";try{const o={};n&&(o.key=n),await t.settings.set(e,o),l.settingsHint.textContent="saved.",await Po(),await Ro(l.classSelect.value)}catch(e){l.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function Go(e){l.settingsHint.textContent="removing…";try{await t.settings.remove(e),l.settingsHint.textContent="removed.",await Po(),await Ro(l.classSelect.value)}catch(e){l.settingsHint.textContent=`remove failed: ${e&&e.message?e.message:e}`}}const Vo=["sessions","memory"];let Qo="sessions";function Wo(e){const t=Vo.includes(e)?e:"sessions";Qo=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 zo=new Set,Yo=3;function Jo(e){const t=(Array.isArray(e&&e.messages)?e.messages:[]).find((e=>e&&"user"===e.role&&e.content));return t&&t.content?String(t.content):e&&"string"==typeof e.firstPrompt?e.firstPrompt:""}function Xo(e){const t=Jo(e);return Boolean(t)&&function(e,t){const n=String(null==e?"":e).replace(/\s+/g," ").trim(),o=String(null==t?"":t).replace(/\s+/g," ").trim();if(!n||!o)return!1;const s=o.slice(0,60);return n===s||60===s.length&&n.length>=52&&s.startsWith(n)}(e&&e.title,t)}function Zo(e){if(!e||!e.id||zo.has(e.id))return;if(!0===e.named&&!Xo(e))return;const t=Jo(e);if(!t)return;if(zo.add(e.id),"function"!=typeof n.nameSession)return;const o=l.classSelect?l.classSelect.value:"";n.nameSession({sessionId:e.id,prompt:t,class:o,model:ae()}).then((t=>{t&&(e.title=t,e.named=!0,ss())})).catch((()=>{}))}let es=[],ts=null;const ns="undefined"!=typeof window&&window.aegisLibrary||null;async function os(){l.sessionsHint.textContent="";let e=[];try{const t=await n.listSessions();e=t&&t.sessions||[]}catch(e){return l.sessionsList.innerHTML="",void(l.sessionsHint.textContent=`list failed: ${e&&e.message?e.message:e}`)}es=e;let t=Yo;for(const n of e){if(t<=0)break;!n||!0===n.named&&!Xo(n)||zo.has(n.id)||(t-=1,Zo(n))}ss()}function ss(){if(!l.sessionsList)return;const e=l.sessionsFilter?l.sessionsFilter.value:"",t=es,n=ns?ns.filterSessions(e,t):t;if(l.sessionsCount&&(l.sessionsCount.textContent=ns?ns.countLabel(n.length,t.length):""),l.sessionsList.innerHTML="",!t.length)return void l.sessionsList.appendChild(is("no conversations yet"));if(!n.length)return void l.sessionsList.appendChild(is(`nothing matches “${String(e).trim()}”`));const o=Date.now(),s=ns?ns.groupSessions(n,o):[{key:"all",label:"",sessions:n}],a=n.length>as?as:1/0;let i=0,r=0;for(const e of s)if(i>=a)r+=e.sessions.length;else{if(e.label){const t=document.createElement("li");t.className="library-group",t.setAttribute("role","presentation"),t.textContent=e.label,l.sessionsList.appendChild(t)}for(const t of e.sessions)i>=a?r+=1:(l.sessionsList.appendChild(rs(t,o)),i+=1)}if(r>0){const e=document.createElement("li");e.className="empty library-more",e.textContent=`${r} more — type in the filter to narrow`,l.sessionsList.appendChild(e)}}const as=200;function is(e){const t=document.createElement("li");return t.className="empty",t.textContent=e,t}function rs(t,o){const s=document.createElement("li");if(s.className="session-row",s.tabIndex=0,s.dataset.sessionId=t&&t.id||"",t&&t.id&&t.id===O&&s.classList.add("is-current"),ts&&t&&t.id===ts)return s.classList.add("is-renaming"),s.appendChild(function(e){const t=document.createElement("input");return t.type="text",t.className="session-rename",t.value=e&&e.title||"",t.setAttribute("aria-label","New name for this conversation"),t.addEventListener("click",(e=>e.stopPropagation())),t.addEventListener("keydown",(o=>{o.stopPropagation(),"Enter"===o.key?(o.preventDefault(),async function(e,t){const o=String(null==t?"":t).trim();if(ts=null,!o||o===(e&&e.title||""))return void ss();if("function"!=typeof n.rename)return l.sessionsHint.textContent="rename is unavailable in this build.",void ss();const s=es.find((t=>t&&t.id===e.id));s&&(s.title=o,s.named=!0),ss();try{await n.rename(e.id,o),l.sessionsHint.textContent=`renamed to “${o}”`}catch(e){l.sessionsHint.textContent=`rename failed: ${e&&e.message?e.message:e}`}await os()}(e,t.value)):"Escape"===o.key&&(o.preventDefault(),ts=null,ss())})),t.addEventListener("blur",(()=>{ts===(e&&e.id)&&(ts=null,ss())})),setTimeout((()=>{try{t.focus(),t.select()}catch{}}),0),t}(t)),s;const a=document.createElement("span");a.className="session-title",a.textContent=ns?ns.sessionTitle(t):t&&t.title||t&&t.id||"untitled",s.appendChild(a);const i=document.createElement("span");i.className="session-meta",i.textContent=ns?ns.sessionMeta(t,o):"",s.appendChild(i);const r=document.createElement("span");r.className="session-actions";for(const[o,s,a]of[["Rename","Rename this conversation",()=>function(e){e&&e.id&&(ts=e.id,ss())}(t)],["Export","Save this conversation as Markdown",()=>async function(t){if(t&&t.id)if("function"==typeof e.exportSession)try{const n=await e.exportSession(t.id,"markdown");n&&n.ok?l.sessionsHint.textContent=`exported to ${n.filePath}`:n&&n.canceled?l.sessionsHint.textContent="":l.sessionsHint.textContent=`export failed: ${n&&n.reason||"unknown error"}`}catch(e){l.sessionsHint.textContent=`export failed: ${e&&e.message?e.message:e}`}else l.sessionsHint.textContent="export is unavailable in this build."}(t)],["Delete","Delete this conversation",()=>async function(e){if(!e||!e.id)return;const t=ns?ns.sessionTitle(e):e.title||e.id;if("function"!=typeof confirm||confirm(`Delete “${t}”?\n\nThis removes the conversation from this device. It cannot be undone.`)){try{await n.delete(e.id)}catch(e){return void(l.sessionsHint.textContent=`delete failed: ${e&&e.message?e.message:e}`)}O===e.id&&fs(),l.sessionsHint.textContent=`deleted “${t}”`,await os()}}(t)]]){const e=document.createElement("button");e.type="button",e.className="session-action",e.textContent=o,e.title=s,e.setAttribute("aria-label",`${s}`),e.addEventListener("click",(e=>{e.stopPropagation(),a()})),r.appendChild(e)}return s.appendChild(r),s.addEventListener("click",(()=>ms(t.id))),s.addEventListener("keydown",(e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),ms(t.id))})),s}function cs(e){if(!l.syncStatus)return;if(!e)return void(l.syncStatus.textContent="");const t=[e.cloud?"cloud sync on":"cloud sync off (no key)",`${e.pending} pending`];e.lastSyncAt&&t.push(`last synced ${new Date(e.lastSyncAt).toLocaleTimeString()}`),e.retry&&e.retry.lastError&&t.push(`last sync attempt failed: ${e.retry.lastError}`),l.syncStatus.textContent=t.join(" · ")}async function ls(){try{cs(await n.status())}catch{cs(null)}}function ds(){"function"==typeof n.auto&&n.auto().then((e=>{e&&e.upgrade&&wt(l.sessionsHint,e.upgrade,"queued memory is waiting on the free-plan cap","See what Pro covers →"),e&&e.memoryFlushed&&_n().catch((()=>{}))})).catch((()=>{}))}async function us(){l.syncNow.disabled=!0,l.sessionsHint.textContent="syncing…";try{const e=await n.push(),t=await n.pull();e.upgrade||t.upgrade?wt(l.sessionsHint,e.upgrade||t.upgrade,"queued memory is waiting on the free-plan cap","See what Pro covers →"):e.ok||t.ok?l.sessionsHint.textContent=`synced (pushed ${e.pushed||0}, pulled ${t.merged||0})`:l.sessionsHint.textContent=`sync failed: ${e.reason||t.reason||"unknown error"}`}catch(e){l.sessionsHint.textContent=`sync failed: ${e&&e.message?e.message:e}`}finally{l.syncNow.disabled=!1,await ls(),await os()}}function ms(e,t){n.open(e).then((e=>{if(!e)return void(l.sessionsHint.textContent="session not found");l.messages.innerHTML="",t&&t.fromNav||xn({kind:"session",id:e.id});const n=Array.isArray(e.messages)?e.messages:[];n.length||eo();for(const t of n){const n="assistant"===t.role?"assistant":"system"===t.role?"system":"user";bo(n,t.content||t.text||"",void 0,"assistant"===n?e.id:void 0)}O=e.id,U.set(e.id,rollMessages(n)),K(e.id),F=replayHistory(n),l.sessionsHint.textContent=`opened ${e.id.slice(0,8)}…`})).catch((e=>{l.sessionsHint.textContent=`open failed: ${e&&e.message?e.message:e}`}))}function ps(t){const n=O;n?e.exportSession(n,t).then((e=>{e&&e.ok?l.sessionsHint.textContent=`exported to ${e.filePath}`:e&&e.canceled||(l.sessionsHint.textContent=`export failed: ${e&&e.reason||"unknown error"}`)})).catch((e=>{l.sessionsHint.textContent=`export failed: ${e&&e.message?e.message:e}`})):l.sessionsHint.textContent="no open session to export"}function fs(){z(),hn={query:"",matches:[],index:-1,texts:[]},l.findInput&&(l.findInput.value=""),Mn(),In(),O&&t.clearApprovals(O).catch((()=>{})),eo(),l.sessionsHint.textContent="",R=null,T=null,J=null,X=null,O=null,F=[],Q=0,K(null)}function hs(e){e&&("open"===e.action&&e.sessionId?ms(e.sessionId):"new"===e.action&&(fs(),e.prompt&&(l.prompt.value=e.prompt,l.prompt.focus())))}async function ys(){const e=l.prompt.value.trim(),o=Cs.length?Cs.map((e=>({kind:e.kind,path:e.path,name:e.name,size:e.size,mime:e.mime,dataUrl:e.dataUrl,text:e.text,truncated:e.truncated}))):void 0;if(!e&&!o||l.send.disabled)return;const s=l.classSelect.value,a=ae();l.prompt.value="";const i=(r=Cs,Array.isArray(r)&&r.length?r.map((e=>`Attachment: ${e.name||e.path}`)).join("\n"):"");var r;const c=i?e?`${e}\n${i}`:i:e,d=Cs.slice();Cs=[],ks=[],xs();const u=++Y;J=u,X=null,bo("user",e,void 0,void 0,void 0,d);const m=s===g&&oe(),p=ce(),f=budgetFor(a,void 0,p),h=m&&parseInt(l.autonomousWorkers.value,10)||void 0;O||(O=Bo());const y=O;T=y,vo();const v=replayHistory(F);F.push({role:"user",content:o&&!ws()?As(e,o):c}),So(!0,{cancellable:!0}),R&&K(y,{prompt:e,reply:"",reasoning:""}),ee({force:!0});try{await n.append(y,{role:"user",content:c})}catch{}let C="",k="",b=0;const w=[];let x=null;const S=(E=()=>{if(!R)return;if(R.classList.remove("pending"),k){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!==k&&(e.textContent=k)}const t=R.querySelector(".body");t&&t.textContent!==C&&(t.textContent=C);const n=C.length+k.length+4*b;liveMeterDue(x,n)&&(x=n,K(y,{prompt:e,reply:C,reasoning:k,measuredReasoningTokens:b})),ee()},Z?Z.paint(E):E);var E;const $=e=>{if(e&&"number"==typeof e.thinkingTokens&&e.thinkingTokens>0)return b+=e.thinkingTokens,void S();if(e&&"string"==typeof e.reasoning&&e.reasoning)return k+=e.reasoning,void S();if(e&&"string"==typeof e.note&&e.note){const t=xo();return t.classList.remove("pending"),function(e,t,n){if(!e||!t)return null;const o=document.createElement("div");o.className="turn-note",o.textContent=t;const s=n?e.querySelector(n):null;s?e.insertBefore(o,s):e.appendChild(o)}(t,e.note,".body"),void ee()}if(e&&e.approval){const t=xo();return t.classList.remove("pending"),Ho(t,e.approval,".body"),void ee({force:!0})}if(e&&e.rounds){const n=xo();return n.classList.remove("pending"),function(e,n,o){if(!e||!n||!n.id)return null;const s=Number(n.spent)||0,a=Number(n.size)||s,i=Number(n.extensions)||1,r=Number(n.max)||8,c=document.createElement("div");c.className="approval-card rounds-card",c.dataset.roundsAskId=n.id;const l=document.createElement("div");l.className="approval-title",l.textContent="Round limit reached — keep going?",c.appendChild(l);const d=document.createElement("div");d.className="approval-summary",d.textContent=`This turn has used all ${s} tool rounds allowed for it. ${a} more continue the SAME turn — no restart, no repeated work. Stopping holds everything done so far: your next message resumes it automatically. (${i} of ${r} extensions.)`,c.appendChild(d);const u=document.createElement("div");u.className="approval-actions";const m=(e,o,s)=>{const i=document.createElement("button");return i.type="button",i.className=`approval-btn ${o}`,i.textContent=e,i.addEventListener("click",(()=>(e=>{for(const e of u.querySelectorAll("button"))e.disabled=!0;c.classList.add("resolved");const o=document.createElement("div");o.className="approval-decision",o.textContent=e?`Continuing — ${a} more rounds`:"Stopped — the work is held",c.appendChild(o),t.respondRoundsAsk(n.id,e)})(s))),i};u.appendChild(m(`Keep going (${a} more rounds)`,"allow",!0)),u.appendChild(m("Stop here","deny",!1)),c.appendChild(u);let p=e.querySelector(".approval-slot");if(!p){p=document.createElement("div"),p.className="approval-slot";const t=o?e.querySelector(o):null;t?e.insertBefore(p,t):e.appendChild(p)}p.appendChild(c)}(n,e.rounds,".body"),void ee({force:!0})}if(e&&e.tool){if("run"===e.tool.phase)return void qo(e.tool);w.push(e.tool);const t=xo();return t.classList.remove("pending"),Ao(t,e.tool,"tool-activity",".body"),void ee()}const n=e&&("string"==typeof e.delta?e.delta:e.content);n&&(C+=n,S())};try{const i=await t.chat({class:s,prompt:e,model:a,maxTokens:f,sessionId:y,autonomous:m,effort:p,workers:h,messages:v,attachments:o,roundsAsk:!0},$);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||C||"(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)),m?d.push(`autonomous (${p}, ${h||"auto"}w)`):p&&d.push(`effort: ${p}`);const u=turnAccounting(i&&i.usage,a,{costUsd:i&&"number"==typeof i.costUsd?i.costUsd:void 0}),g=displayTokens(u);if(null!=g)d.push(`tokens: ${g}`);else{const t=estimatedBuckets(e,c,c===k?"":k);t&&t.output>0&&d.push(`~${t.output} tokens`)}const b=feeBillable(function(){const e="undefined"!=typeof state?state:null;return e&&e.entitlement?e.entitlement:null}());null!=u.cost&&b&&d.push(fmtCost(u.cost,u.real)),"byok"===s&&null!=u.cost&&b&&d.push("your provider bill (est.) + AEGIS handling fee");const x=_(y,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===k?"":k}),S=fmtRoll(x,{omitMoney:!b});S&&d.push(`session: ${S}`),i&&i.pooled_notice&&d.push(i.pooled_notice),bo("assistant",c,d.join(" · ")||void 0,y,w);try{await n.append(y,{role:"assistant",content:c,...j(i&&i.usage,a,u,{prompt:e,reply:c,reasoning:c===k?"":k,calls:i&&i.calls})}),await n.save({id:y,title:e.slice(0,60)}),"function"==typeof n.nameSession&&n.nameSession({sessionId:y,prompt:e,class:s,model:a}).then((e=>{e&&os().catch((()=>{}))})).catch((()=>{}))}catch{}ds(),function(){const e=l.exploreToggle;return Boolean(e&&e.checked)}()&&"(empty response)"!==c&&function(e){const t=document.createElement("div");t.className="chatflow";const n=document.createElement("div");n.className="flow-rail";const o=document.createElement("span");o.className="flow-rail-label",o.textContent="discovery lane";const s=document.createElement("span");s.className="flow-rail-hint",s.textContent="alternatives from the AI — scroll →",n.appendChild(o),n.appendChild(s);const a=document.createElement("div");a.className="flow-track";const i=document.createElement("button");i.type="button",i.className="ghost-btn flow-add",i.textContent="+ another path",i.addEventListener("click",(()=>{wo(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))wo(t,a,e)}({prompt:e,cls:s,model:a,maxTokens:f,parentSessionId:y})}catch(t){if(isCancellation(t,{userStopped:X===u})){const t=salvageTurn({streamedText:C,reasoningText:k}),o=t.text,s=t.reasoning,i=replayableContent(t.kind,o);F.push({role:"assistant",content:i});const r=turnAccounting(void 0,a,{}),c=_(y,void 0,{model:a,prompt:e,reply:o,reasoning:s}),l=["stopped by you"];"reasoning-only"===t.kind&&l.push("reasoning only");const d=displayTokens(r);if(null!=d)l.push(`tokens: ${d}`);else{const t=estimatedBuckets(e,o,s);t&&t.output>0&&l.push(`~${t.output} tokens`)}const u=fmtRoll(c);u&&l.push(`session: ${u}`),bo("assistant",o,l.join(" · "),y,w);try{await n.append(y,{role:"assistant",content:i,...j(void 0,a,r,{prompt:e,reply:o,reasoning:s})})}catch{}ds()}else bo("assistant",`Error: ${t&&t.message?t.message:t}`,"request failed")}finally{So(!1),J===u&&(J=null,T=null),os()}}let gs=!1;function vs(){const e=l.messages;e&&(gs=!0,e.scrollTo({top:e.scrollHeight,behavior:"smooth"}),l.scrollBottom&&(l.scrollBottom.hidden=!0))}let Cs=[],ks=[],bs=0;function ws(){return l.classSelect&&"pro"===l.classSelect.value}function xs(){const e=l.attachRow,t=l.attachNote;if(!e)return;e.textContent="";const n=Cs.length+ks.length;if(e.hidden=0===n,t&&(t.hidden=!0,t.textContent=""),n){for(const t of Cs){const n=document.createElement("span");if(n.className="attach-chip",n.title=t.path||"","image"===t.kind&&t.dataUrl){const e=document.createElement("img");e.className="attach-thumb",e.src=t.dataUrl,e.alt="",n.appendChild(e)}const o=document.createElement("span");o.className="attach-kind",o.textContent="image"===t.kind?"img":"text"===t.kind?"txt":t.kind,n.appendChild(o);const s=document.createElement("span");s.className="attach-name",s.textContent=`${t.name||t.path} · ${Es(t.size)}${t.truncated?" (truncated)":""}`,n.appendChild(s),n.appendChild(Ss((()=>{Cs=Cs.filter((e=>e!==t)),xs()}))),e.appendChild(n)}for(const t of ks){const n=document.createElement("span");n.className="attach-chip is-refused",n.title=t.reason||"";const o=document.createElement("span");o.className="attach-name",o.textContent=`${t.name||t.path} — ${t.reason||"not attached"}`,n.appendChild(o),n.appendChild(Ss((()=>{ks=ks.filter((e=>e!==t)),xs()}))),e.appendChild(n)}if(t&&ws()){const e=Cs.filter((e=>"image"===e.kind)).length;e&&(t.hidden=!1,t.textContent=1===e?"This provider runs text-only, so the picture travels as its file path.":`This provider runs text-only, so the ${e} pictures travel as file paths.`)}}}function Ss(e){const t=document.createElement("button");return t.type="button",t.className="attach-remove",t.title="Remove",t.setAttribute("aria-label","Remove attachment"),t.textContent="×",t.addEventListener("click",e),t}function Es(e){const t=Number(e)||0;return t<1024?`${t} B`:t<1048576?`${Math.round(t/1024)} KB`:`${(t/1048576).toFixed(1)} MB`}async function $s(t){const n=(t||"").split(/[\\/]/).pop()||t;if(Cs.length>=8)return ks.push({path:t,name:n,reason:"at most 8 files per message"}),void xs();let o;try{o=await e.attachments.ingest(t)}catch(e){o={ok:!1,reason:e&&e.message||"could not read file"}}if(!o||!0!==o.ok||!o.attachment)return ks.push({path:t,name:n,reason:o&&o.reason||"not attached"}),void xs();Cs.some((e=>e.path===o.attachment.path))||(Cs.push(o.attachment),xs())}const Ls=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function qs(e){if(e&&"string"==typeof e.mime&&e.mime)return e.mime;const t=e&&"string"==typeof e.dataUrl?e.dataUrl:"",n=/^data:([^;,]+)[;,]/.exec(t);return n?n[1].toLowerCase():""}const Ms='<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12.1 7.3 8.05 11.35a2.85 2.85 0 0 1-4.03-4.03l4.4-4.4a1.9 1.9 0 1 1 2.69 2.69l-4.4 4.4a.95.95 0 1 1-1.35-1.35L9.4 4.6"/></svg>';function As(e,t){const n=[],o="string"==typeof e?e:"";o.trim()&&n.push({type:"text",text:o});for(const e of t||[]){const t=qs(e);"image"===e.kind&&e.dataUrl&&Ls.has(t)?n.push({type:"image_url",image_url:{url:e.dataUrl}}):"image"===e.kind?n.push({type:"text",text:e.path?`[attached image, not inline (${t||"unknown image type"}): ${e.path}]`:`[attached image, not inline (${t||"unknown image type"})]`}):"text"===e.kind&&"string"==typeof e.text?n.push({type:"text",text:`--- ${e.name} ---\n${e.text}`}):e.path&&n.push({type:"text",text:`[attached file: ${e.path}]`})}return 1===n.length&&"text"===n[0].type?n[0].text:n.length?n:o}const Ns="aegis.onboardingSeen";async function Hs(){!function(){const t=document.getElementById("onboard-overlay");if(!t)return;let n=!1;try{n="1"===localStorage.getItem(Ns)}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(Ns,"1")}catch{}t.classList.add("is-leaving"),setTimeout((()=>{t.hidden=!0}),250)};s&&s.addEventListener("click",(async()=>{s.disabled=!0,a&&(a.disabled=!0),r("Opening a browser to sign in with Google…");try{const t=await e.driveSignIn();if(t&&t.ok)return r(t.username?`Signed in as ${t.username}`:"Signed in","ok"),void setTimeout(c,500);r(t&&t.error||"Sign-in did not complete.","err")}catch(e){r(e&&e.message||"Sign-in failed.","err")}s.disabled=!1,a&&(a.disabled=!1)})),a&&a.addEventListener("click",(()=>{c(),ao();const e=document.getElementById("api-key-input");e&&e.focus()})),i&&i.addEventListener("click",c)}();try{me(await e.status())}catch{me(null)}"on"===localStorage.getItem(m)&&(l.autonomousToggle.checked=!0),l.autonomousToggle.addEventListener("change",(()=>{localStorage.setItem(m,l.autonomousToggle.checked?"on":"off"),se()}));const n=localStorage.getItem(p)||localStorage.getItem("aegis.autonomousEffort"),i=Array.from(l.effortSelect.options).some((e=>e.value===n));n&&i?l.effortSelect.value=n:n&&localStorage.setItem(p,l.effortSelect.value),l.effortSelect.addEventListener("change",(()=>{localStorage.setItem(p,l.effortSelect.value),ie(l.classSelect.value)}));const r=localStorage.getItem(f);r&&(l.autonomousWorkers.value=r),l.autonomousWorkers.addEventListener("change",(()=>{localStorage.setItem(f,l.autonomousWorkers.value)})),se();const c=localStorage.getItem(h);l.exploreToggle.checked="on"===c,l.exploreToggle.addEventListener("change",(()=>{localStorage.setItem(h,l.exploreToggle.checked?"on":"off"),l.exploreToggle.checked||z()})),l.classSelect.addEventListener("change",(()=>{localStorage.setItem(d,l.classSelect.value),ie(l.classSelect.value),Ro(l.classSelect.value)})),l.modelSelect.addEventListener("change",(()=>{const e=P.get(l.modelSelect.value),t=maxTokensCeiling(e),n=l.modelHint.textContent.replace(/ · max output: [\d,]+$/,"");l.modelHint.textContent=t<FLAT_CEILING?`${n} · max output: ${t.toLocaleString()}`:n,ie(l.classSelect.value),"byok"===l.classSelect.value&&e&&e.provider&&!1===e.configured&&function(e){if(!l.settingsList||!e)return;const t=l.settingsList.querySelector(`.setting-row[data-provider="byok:${e}"] input[type="password"]`);if(ao(),lo(l.settingsList),t&&t.focus(),l.modelHint){const t=l.modelHint.textContent.replace(/ — no .* key saved; add it below\.$/,"");l.modelHint.textContent=`${t} — no ${e} key saved; add it below.`}}(e.provider)})),l.modelFree.addEventListener("input",(()=>{ie(l.classSelect.value)})),l.newChat.addEventListener("click",fs),l.railAutomations&&l.railAutomations.addEventListener("click",(async()=>{await Promise.all([Ze().catch((()=>{})),je().catch((()=>{}))]),io()})),l.automationsBack&&l.automationsBack.addEventListener("click",ro),l.railSettings&&l.railSettings.addEventListener("click",ao),l.settingsBack&&l.settingsBack.addEventListener("click",ro),l.settingsJump&&l.settingsJump.addEventListener("click",(e=>{const t=e.target.closest(".settings-jump-link");if(!t)return;const n=document.getElementById(t.dataset.jump);n&&oo(n)})),l.importSessionBtn&&l.importSessionBtn.addEventListener("click",Qt),l.openCliFace&&l.openCliFace.addEventListener("click",(async()=>{if(e.openCliFace)try{const t=await e.openCliFace();t&&t.ok?le(!0,`opened ${t.emulator||"a terminal"}`):le(!1,t&&t.reason||"could not open a terminal")}catch(e){le(!1,`terminal face failed: ${e&&e.message||e}`)}else le(!1,"terminal face unavailable in this build")})),l.importClose&&l.importClose.addEventListener("click",Gt),l.importBackdrop&&l.importBackdrop.addEventListener("click",Gt),l.importSessionsBtn&&l.importSessionsBtn.addEventListener("click",Wt),l.importMemoryBtn&&l.importMemoryBtn.addEventListener("click",(()=>async function(t){if(!e.memoryImport)return;const n=t&&t.hint||l.memoryHint;l.importMemoryBtn&&(l.importMemoryBtn.disabled=!0),n.textContent="scanning for other AI tool memory…";try{const t=await e.memoryImport({confirm:!1});if(!t||!t.totals||!t.totals.entries)return void(n.textContent=t&&t.summary?t.summary:"nothing found.");const o=(t.sources||[]).filter((e=>e.present&&e.count>0)).map((e=>`${e.label}: ${e.count}`)).join(" · ");n.textContent=`importing ${t.totals.entries} entries — ${o}`;const s=await e.memoryImport({confirm:!0,limit:1e3});if(s&&s.upgrade)return wt(n,s.upgrade,`import stopped after ${s.saved||0} entries`),void await _n();const a=s&&s.queued?` (${s.queued} queued offline)`:"";n.textContent=s&&s.ok?`imported ${s.saved} entries${a}.`:`import stopped: ${s&&s.reason||"unknown error"}`,await _n()}catch(e){n.textContent=`import failed: ${e&&e.message?e.message:e}`}finally{l.importMemoryBtn&&(l.importMemoryBtn.disabled=!1)}}({hint:l.importHint}))),e.onMenuNewChat&&e.onMenuNewChat(fs),e.onMenuSearch&&e.onMenuSearch((()=>Pt(""))),e.onMenuSearchMemory&&e.onMenuSearchMemory(Ut),
|
|
5
|
+
function Zt(){return!!l.creditsOverlay&&!l.creditsOverlay.hidden}function en(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 tn(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(en("Vendored third-party code",t.code)),Array.isArray(t.fonts)&&t.fonts.length&&l.creditsBody.appendChild(en("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 nn(){l.creditsOverlay&&(Ln({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 tn(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=""),tn(t)}())}function on(){l.creditsOverlay&&(l.creditsOverlay.hidden=!0,document.body.classList.remove("memory-open"))}function sn(){return!!l.shortcutsOverlay&&!l.shortcutsOverlay.hidden}function an(){l.shortcutsOverlay&&(Ln({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 rn(){l.shortcutsOverlay&&(l.shortcutsOverlay.hidden=!0,document.body.classList.remove("memory-open"))}let cn=[],ln=-1;function dn(){return{cliFace:void 0!==e&&e&&"function"==typeof e.openCliFace}}function un(){return globalThis.AegisPaletteFilter||null}function mn(){return!!l.paletteOverlay&&!l.paletteOverlay.hidden}function pn(e){if(!l.paletteList)return;const t=un(),n=function(){const e=globalThis.AegisCommands;return e&&Array.isArray(e.COMMANDS)?e.availableCommands(e.COMMANDS,dn()):[]}();cn=t?t.filterCommands(n,e):n.slice(),ln=t?t.initialIndex(cn):cn.length?0:-1,l.paletteList.replaceChildren();for(let e=0;e<cn.length;e+=1){const t=cn[e],n=document.createElement("li");n.className="palette-row"+(e===ln?" is-active":""),n.id=`palette-row-${e}`,n.setAttribute("role","option"),n.setAttribute("aria-selected",e===ln?"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(),ln=e,jn(t.action)})),l.paletteList.appendChild(n)}l.paletteEmpty&&(l.paletteEmpty.hidden=cn.length>0),fn()}function fn(){if(!l.paletteList)return;const e=l.paletteList.children;for(let t=0;t<e.length;t+=1){const n=t===ln;e[t].classList.toggle("is-active",n),e[t].setAttribute("aria-selected",n?"true":"false")}l.paletteInput&&(ln>=0?l.paletteInput.setAttribute("aria-activedescendant",`palette-row-${ln}`):l.paletteInput.removeAttribute("aria-activedescendant"));const t=e[ln];t&&"function"==typeof t.scrollIntoView&&t.scrollIntoView({block:"nearest"})}function hn(e){const t=un();t&&(ln=t.moveIndex(ln,cn.length,e),fn())}function yn(){l.paletteOverlay&&(l.paletteOverlay.hidden=!1,document.body.classList.add("memory-open"),l.paletteInput&&(l.paletteInput.value="",l.paletteInput.focus()),pn(""))}function gn(){l.paletteOverlay&&(l.paletteOverlay.hidden=!0,document.body.classList.remove("memory-open"),cn=[],ln=-1)}function vn(){if(!l.side)return;const e=l.side.classList.toggle("is-collapsed");l.side.setAttribute("aria-hidden",e?"true":"false")}let Cn={query:"",matches:[],index:-1,texts:[]},kn=AegisNavHistory.createHistory(),bn=!1;function wn(){return globalThis.AegisFindInConversation||null}function xn(){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<Cn.matches.length;e+=1){const o=Cn.matches[e],s=Cn.texts[o.textIndex];if(!s)continue;const a=document.createRange();a.setStart(s,o.start),a.setEnd(s,o.end),t.push(a),e===Cn.index&&n.push(a)}t.length&&e.set("find-match",new Highlight(...t)),n.length&&e.set("find-match-current",new Highlight(...n))}function Sn(e){const t=wn();if(!t)return;Cn.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=Cn.texts.map((e=>e.nodeValue||""));Cn.matches=t.findMatches(n,Cn.query,{caseSensitive:!1}),Cn.index=Cn.matches.length?0:-1,xn(),l.findCount&&(l.findCount.textContent=t.matchLabel(Cn.index,Cn.matches.length)),e&&En()}function En(){const e=Cn.matches[Cn.index];if(!e)return;const t=Cn.texts[e.textIndex];if(!t)return;const n=t.parentElement;n&&"function"==typeof n.scrollIntoView&&n.scrollIntoView({block:"center",behavior:"smooth"})}function $n(){return!!l.findBar&&!l.findBar.hidden}function Ln(e){bn||(kn=AegisNavHistory.pushEntry(kn,e),qn())}function qn(){e.setNavState&&e.setNavState({back:AegisNavHistory.canGoBack(kn),forward:AegisNavHistory.canGoForward(kn)}).catch((()=>{}))}function Mn(e){if(e){bn=!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?lo():"automations"===e.kind?uo():"session"===e.kind&&e.id?ys(e.id,{fromNav:!0}):"memory"===e.kind?Rt():"credits"===e.kind?nn():"shortcuts"===e.kind?an():"keys"===e.kind?bo():mo()}finally{bn=!1}}}function An(){const e=AegisNavHistory.back(kn);e?(kn=e.state,Mn(e.entry),qn()):l.sessionsHint.textContent="already at the start of the history"}function Nn(){const e=AegisNavHistory.forward(kn);e?(kn=e.state,Mn(e.entry),qn()):l.sessionsHint.textContent="already at the newest place"}function Hn(){l.findBar&&(l.findBar.hidden=!1,l.findInput&&(l.findInput.focus(),"function"==typeof l.findInput.select&&l.findInput.select()),Cn.query&&Sn(!0))}function Bn(){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 In={kind:"",rows:[],index:-1,span:null,query:""};function Rn(){return globalThis.AegisComposerTriggers||null}function Tn(){return!!l.composerMenu&&!l.composerMenu.hidden}const On=new Set(["exportJson","toggleSidebar","keys","credits","find"]);function Dn(){In={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 Fn(){if(!l.composerMenuList)return;l.composerMenuList.replaceChildren();const e=In.rows;for(let t=0;t<e.length;t+=1){const n=e[t],o=document.createElement("li");o.className="composer-menu-row"+(t===In.index?" is-active":""),o.id=`composer-row-${t}`,o.setAttribute("role","option"),o.setAttribute("aria-selected",t===In.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(),In.index=t,Un()})),l.composerMenuList.appendChild(o)}const t=l.composerMenuList.children[In.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"===In.kind?In.query?`nothing matches “${In.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 Pn(){const e=Rn(),t=l.prompt;if(!e||!t)return;const o=e.activeTrigger(t.value,t.selectionStart);if(!o)return void(Tn()&&Dn());const s={start:o.start,end:o.end};let a;if(In.kind=o.kind,In.span=s,In.query=o.query,"slash"===o.kind)a=e.rankRows(function(){const e=globalThis.AegisCommands;return e&&Array.isArray(e.COMMANDS)?e.availableCommands(e.COMMANDS,dn()).filter((e=>!On.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}In.rows=a,In.index=a.length?0:-1,Fn()}async function Un(){const e=In.rows[In.index],t=l.prompt;if(!e||!t)return void Dn();const n=In.span,o=In.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(),Dn(),void jn(e.action);if(Dn(),"openSessionRow"===e.action&&e.session)return t.value=(s.slice(0,a)+r).replace(/\s{2,}/g," ").trimStart(),void ys(e.session.id);if("stageMemory"===e.action&&e.memory){const n=e.memory,o=String(n.content||"");xs.some((e=>"text"===e.kind&&e.text===o))||(xs.push({kind:"text",name:n.scope?`memory: ${n.scope}`:"memory",path:"",size:o.length,mime:"text/plain",text:o,truncated:!1}),Ls());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 _n(e){const t=Rn();t&&In.rows.length&&(In.index=t.stepRow(In.rows.length,In.index,e),Fn())}function Kn(e){const t=wn();t&&Cn.matches.length&&(Cn.index=t.stepMatch(Cn.index,Cn.matches.length,e),xn(),l.findCount&&(l.findCount.textContent=t.matchLabel(Cn.index,Cn.matches.length)),En())}function jn(e){switch(gn(),e){case"newChat":return void vs();case"go-back":return void An();case"go-forward":return void Nn();case"search":return void jt("");case"find":return void Hn();case"settings":return void lo();case"customizations":return lo(),void ro(l.confirmMode);case"automations":return void Promise.all([ot().catch((()=>{})),We().catch((()=>{}))]).then((()=>uo()));case"cli":return void(l.openCliFace&&l.openCliFace.click());case"import":return void(l.importSessionBtn&&l.importSessionBtn.click());case"exportMarkdown":return void gs("markdown");case"exportJson":return void gs("json");case"memory":return void Rt();case"fingerprint":return void(ft&&"function"==typeof ft.open&&ft.open());case"shortcuts":return void an();case"keys":return void bo();case"credits":return void nn();case"toggleSidebar":return void vn();default:throw new Error(`palette: unknown action ${e}`)}}async function Gn(){const t=mt()&&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 Lt(o.upgrade,"free plan limit reached"),void await Vn();t.value="",l.memoryHint.textContent=o&&o.queued?"saved offline — syncs when AEGIS is reachable.":"saved.",await Vn()}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 Vn(){const e=l.memoryQuery?l.memoryQuery.value.trim():"";await qt(e),mt()&&await It(dt.query)}function Qn(){const e=kt();return void 0===e.keyConfigured&&delete e.keyConfigured,e}function Wn(){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(Qn(),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 zn="aegis.welcomeRowsDismissed";function Yn(){const e=window.aegisWelcomeRows;if(!e)return[];try{return e.parseDismissed(localStorage.getItem(zn))}catch{return[]}}function Jn(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":jt("");break;case"memory":Rt();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(zn,t.withDismissed(Yn(),e))}catch{}Xn()}}(e.id))),t.appendChild(s),t}function Xn(){const t=document.getElementById("welcome-rows"),n=window.aegisWelcomeRows;if(!t||!n)return;const o=n.pickRows(function(){const t=Qn();return ss.length&&(t.sessionCount=ss.length),void 0!==e&&e&&"function"==typeof e.openCliFace&&(t.cliAvailable=!0),t}(),Yn());if(t.innerHTML="",o.length){for(const e of o)t.appendChild(Jn(e));t.hidden=!1}else t.hidden=!0}const Zn="aegis.welcomeAiLine",eo=120,to=200;function no(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 oo(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 so(){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?"}(),Wn(),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!==no(e)?null:t.text:null}(n);if(o)return e.textContent=o,e.dataset.kind="ai",void(e.hidden=!1);const s=Qn(),a=l.classSelect&&l.classSelect.value?l.classSelect.value:"aegis",i=l.modelSelect&&l.modelSelect.value?l.modelSelect.value:"",r={class:a,prompt:oo(s),maxTokens:eo,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>to){const e=n.slice(0,to),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:no(n),text:u}))}catch{}}}();const n=document.getElementById("welcome-byok");n&&n.addEventListener("click",ho);const o=document.getElementById("welcome-cloud");o&&o.addEventListener("click",yo);const s=document.getElementById("welcome-dismiss");s&&s.addEventListener("click",vo),ao(),Xn()}function ao(){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,io("welcome-cloud",!n),io("welcome-cloud-note",!n),io("welcome-byok",!o),io("welcome-byok-note",!o)}function io(e,t){const n=document.getElementById(e);n&&(n.hidden=t)}function ro(e){if(!e)return;const t=e.closest("label")||e;let n=t.parentElement;for(;n;){const e=getComputedStyle(n).overflowY;if("auto"===e||"scroll"===e)break;n=n.parentElement}if(n){const e=n.querySelector(":scope > .settings-view-header"),o=e?e.offsetHeight:0,s=()=>t.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-o,a=()=>n.scrollTo({top:Math.max(0,s()),behavior:"smooth"});a();const i=Date.now()+3e3;let r=s();const c=()=>{const e=s();Math.abs(e-r)>=1&&(r=e,a()),Date.now()<i&&requestAnimationFrame(c)};requestAnimationFrame(c)}else try{t.scrollIntoView({block:"start",behavior:"smooth"})}catch{t.scrollIntoView()}t.classList.add("flash"),setTimeout((()=>t.classList.remove("flash")),1200)}let co=!1;function lo(){l.settingsView&&(l.settingsView.hidden=!1,l.settingsView.scrollTop=0),l.automationsView&&(l.automationsView.hidden=!0),l.chatCanvas&&(l.chatCanvas.hidden=!0),po(l.railSettings),Ln({kind:"settings"}),function(){if(co)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),co=!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 uo(){l.automationsView&&(l.automationsView.hidden=!1,l.automationsView.scrollTop=0),l.settingsView&&(l.settingsView.hidden=!0),l.chatCanvas&&(l.chatCanvas.hidden=!0),po(l.railAutomations),Ln({kind:"automations"})}function mo(){l.settingsView&&(l.settingsView.hidden=!0),l.automationsView&&(l.automationsView.hidden=!0),l.chatCanvas&&(l.chatCanvas.hidden=!1),po(null),Ln({kind:"conversations"})}function po(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 fo(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 ho(){if(go("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"))),lo(),fo(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 fo(l.apiKeyInput);const e=l.settingsList?l.settingsList.querySelector('.setting-row input[type="password"]'):null;e&&e.focus()}function yo(){go("cloud"),lo(),fo(l.apiKeyInput),l.apiKeyInput&&l.apiKeyInput.focus()}function go(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 vo(){try{localStorage.setItem(y,"on")}catch{}const e=document.getElementById("welcome-connect");e&&(e.hidden=!0)}const Co="aegis.keysPopupDismissed";function ko(){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 bo(){l.keysOverlay&&(ko(),l.keysOverlay.hidden&&(Ln({kind:"keys"}),l.keysOverlay.hidden=!1,document.body.classList.add("keys-open")))}function wo(){l.keysOverlay&&(l.keysOverlay.hidden=!0,document.body.classList.remove("keys-open"))}function xo(){try{localStorage.setItem(Co,"on")}catch{}wo()}function So(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 Eo(e,t,n,o,s,a){!function(){const e=document.getElementById("chat-welcome");e&&e.remove()}();const i=document.createElement("div");i.className=`msg ${e}`;const r=document.createElement("div");if(r.className="body",So(r,e,t),"user"===e&&Array.isArray(a)&&a.length){const e=document.createElement("div");e.className="msg-attachments";for(const t of a){const n=document.createElement("span");n.className="msg-attachment",n.innerHTML=Bs;const o=document.createElement("span");o.textContent=t.name||t.path||"",n.appendChild(o),e.appendChild(n)}i.appendChild(e)}if(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=Bo(t),e.appendChild(n)}i.appendChild(e)}if(i.appendChild(r),n){const e=document.createElement("div");e.className="meta",e.textContent=n,i.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))),i.appendChild(e)}return l.messages.appendChild(i),ee(),i}function $o(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 To(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 Ho(t.tool):void Io(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)";So(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 Lo(){return R||(R=Eo("assistant",""),R.classList.remove("pending"),R)}function qo(e,{cancellable:t}={}){if(l.send.disabled=e,l.prompt.disabled=e,e){R=Eo("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 Mo=72,Ao=new Set(["editFile","writeFile","Edit","Write","MultiEdit"]),No=new Map;function Ho(e){if(!e||!Ao.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&&No.set(e.id,n)}function Bo(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>Mo?`${i.slice(0,Mo-1)}…`:i;return`→ ${t}${r?` ${r}`:""} ${o}`}function Io(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?No.get(n.id):null;if(i){No.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=Bo(n),a.appendChild(r),a}function Ro(e){return e.startsWith("@@")?"diff-hunk":e.startsWith("+++")||e.startsWith("---")?"diff-file":e.startsWith("+")?"diff-add":e.startsWith("-")?"diff-del":"diff-ctx"}function To(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=Ro(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 Oo(){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 Do(){try{F=await t.listClasses()||[]}catch(e){F=[],l.modelHint.textContent=`listClasses failed: ${e&&e.message?e.message:e}`}l.classSelect.innerHTML="";for(const e of F){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&&F.some((t=>t.class===e))&&(l.classSelect.value=e),await Fo(l.classSelect.value)}async function Fo(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 Po(){if(l.queueModelInput&&!l.queueModelInput.hidden){const e=l.queueModelInput.value.trim();if(e)return e}return l.queueModelSelect?l.queueModelSelect.value:""}async function Uo(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 _o({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 Ko(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 jo(),await Fo(l.classSelect.value)}catch(e){l.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function jo(){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&&Ko(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",(()=>Ko(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",(()=>zo(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(_o({provider:o,name:`BYOK: ${t.label||t.id}`,cfg:s,onSave:e=>Wo(o,e),onRemove:()=>zo(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 jo(),await Fo(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 jo(),await Fo(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 jo(),await Fo(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 Go()}catch(e){l.customStatus&&(l.customStatus.textContent=`custom provider: ${e&&e.message?e.message:e}`)}}async function Go(){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 Vo(){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 Go(),void await Fo(l.classSelect.value).catch((()=>{}))}l.customModel&&(l.customModel.value=""),s(`saved ${e} with model ${o} — pick it under provider "byok", then the model.`),await Go(),await jo(),await Fo(l.classSelect.value).catch((()=>{}))}async function Qo(){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 Go(),await jo(),await Fo(l.classSelect.value).catch((()=>{}))}async function Wo(e,n){l.settingsHint.textContent="saving…";try{const o={};n&&(o.key=n),await t.settings.set(e,o),l.settingsHint.textContent="saved.",await jo(),await Fo(l.classSelect.value)}catch(e){l.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function zo(e){l.settingsHint.textContent="removing…";try{await t.settings.remove(e),l.settingsHint.textContent="removed.",await jo(),await Fo(l.classSelect.value)}catch(e){l.settingsHint.textContent=`remove failed: ${e&&e.message?e.message:e}`}}const Yo=["sessions","memory"];let Jo="sessions";function Xo(e){const t=Yo.includes(e)?e:"sessions";Jo=t;for(const e of Yo){const n="sessions"===e?l.paneSessions:l.paneMemory,o="sessions"===e?l.tabSessions:l.tabMemory,s=e===t;n&&(n.hidden=!s),o&&(o.setAttribute("aria-selected",s?"true":"false"),o.classList.toggle("is-active",s))}}const Zo=new Set,es=3;function ts(e){const t=(Array.isArray(e&&e.messages)?e.messages:[]).find((e=>e&&"user"===e.role&&e.content));return t&&t.content?String(t.content):e&&"string"==typeof e.firstPrompt?e.firstPrompt:""}function ns(e){const t=ts(e);return Boolean(t)&&function(e,t){const n=String(null==e?"":e).replace(/\s+/g," ").trim(),o=String(null==t?"":t).replace(/\s+/g," ").trim();if(!n||!o)return!1;const s=o.slice(0,60);return n===s||60===s.length&&n.length>=52&&s.startsWith(n)}(e&&e.title,t)}function os(e){if(!e||!e.id||Zo.has(e.id))return;if(!0===e.named&&!ns(e))return;const t=ts(e);if(!t)return;if(Zo.add(e.id),"function"!=typeof n.nameSession)return;const o=l.classSelect?l.classSelect.value:"";n.nameSession({sessionId:e.id,prompt:t,class:o,model:ae()}).then((t=>{t&&(e.title=t,e.named=!0,cs())})).catch((()=>{}))}let ss=[],as=null;const is="undefined"!=typeof window&&window.aegisLibrary||null;async function rs(){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}`)}ss=e;let t=es;for(const n of e){if(t<=0)break;!n||!0===n.named&&!ns(n)||Zo.has(n.id)||(t-=1,os(n))}cs()}function cs(){if(!l.sessionsList)return;const e=l.sessionsFilter?l.sessionsFilter.value:"",t=ss,n=is?is.filterSessions(e,t):t;if(l.sessionsCount&&(l.sessionsCount.textContent=is?is.countLabel(n.length,t.length):""),l.sessionsList.innerHTML="",!t.length)return void l.sessionsList.appendChild(ds("no conversations yet"));if(!n.length)return void l.sessionsList.appendChild(ds(`nothing matches “${String(e).trim()}”`));const o=Date.now(),s=is?is.groupSessions(n,o):[{key:"all",label:"",sessions:n}],a=n.length>ls?ls:1/0;let i=0,r=0;for(const e of s)if(i>=a)r+=e.sessions.length;else{if(e.label){const t=document.createElement("li");t.className="library-group",t.setAttribute("role","presentation"),t.textContent=e.label,l.sessionsList.appendChild(t)}for(const t of e.sessions)i>=a?r+=1:(l.sessionsList.appendChild(us(t,o)),i+=1)}if(r>0){const e=document.createElement("li");e.className="empty library-more",e.textContent=`${r} more — type in the filter to narrow`,l.sessionsList.appendChild(e)}}const ls=200;function ds(e){const t=document.createElement("li");return t.className="empty",t.textContent=e,t}function us(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"),as&&t&&t.id===as)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(as=null,!o||o===(e&&e.title||""))return void cs();if("function"!=typeof n.rename)return l.sessionsHint.textContent="rename is unavailable in this build.",void cs();const s=ss.find((t=>t&&t.id===e.id));s&&(s.title=o,s.named=!0),cs();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 rs()}(e,t.value)):"Escape"===o.key&&(o.preventDefault(),as=null,cs())})),t.addEventListener("blur",(()=>{as===(e&&e.id)&&(as=null,cs())})),setTimeout((()=>{try{t.focus(),t.select()}catch{}}),0),t}(t)),s;const a=document.createElement("span");a.className="session-title",a.textContent=is?is.sessionTitle(t):t&&t.title||t&&t.id||"untitled",s.appendChild(a);const i=document.createElement("span");i.className="session-meta",i.textContent=is?is.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&&(as=e.id,cs())}(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=is?is.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&&vs(),l.sessionsHint.textContent=`deleted “${t}”`,await rs()}}(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",(()=>ys(t.id))),s.addEventListener("keydown",(e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),ys(t.id))})),s}function ms(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 ps(){try{ms(await n.status())}catch{ms(null)}}function fs(){"function"==typeof n.auto&&n.auto().then((e=>{e&&e.upgrade&&$t(l.sessionsHint,e.upgrade,"queued memory is waiting on the free-plan cap","See what Pro covers →"),e&&e.memoryFlushed&&Vn().catch((()=>{}))})).catch((()=>{}))}async function hs(){l.syncNow.disabled=!0,l.sessionsHint.textContent="syncing…";try{const e=await n.push(),t=await n.pull();e.upgrade||t.upgrade?$t(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 ps(),await rs()}}function ys(e,t){n.open(e).then((e=>{if(!e)return void(l.sessionsHint.textContent="session not found");l.messages.innerHTML="",t&&t.fromNav||Ln({kind:"session",id:e.id});const n=Array.isArray(e.messages)?e.messages:[];n.length||so();for(const t of n){const n="assistant"===t.role?"assistant":"system"===t.role?"system":"user";Eo(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),D=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 gs(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 vs(){z(),Cn={query:"",matches:[],index:-1,texts:[]},l.findInput&&(l.findInput.value=""),Bn(),Dn(),O&&t.clearApprovals(O).catch((()=>{})),so(),l.sessionsHint.textContent="",R=null,T=null,J=null,X=null,O=null,D=[],Q=0,K(null)}function Cs(e){e&&("open"===e.action&&e.sessionId?ys(e.sessionId):"new"===e.action&&(vs(),e.prompt&&(l.prompt.value=e.prompt,l.prompt.focus())))}async function ks(){const e=l.prompt.value.trim(),o=xs.length?xs.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=xs,Array.isArray(r)&&r.length?r.map((e=>`Attachment: ${e.name||e.path}`)).join("\n"):"");var r;const c=i?e?`${e}\n${i}`:i:e,d=xs.slice();xs=[],Ss=[],Ls();const u=++Y;J=u,X=null,Eo("user",e,void 0,void 0,void 0,d);const m=s===g&&oe(),p=ce(),f=budgetFor(a,void 0,p),h=m&&parseInt(l.autonomousWorkers.value,10)||void 0;O||(O=Oo());const y=O;T=y,wo();const v=replayHistory(D);D.push({role:"user",content:o&&!$s()?Is(e,o):c}),qo(!0,{cancellable:!0}),R&&K(y,{prompt:e,reply:"",reasoning:""}),ee({force:!0});try{await n.append(y,{role:"user",content:c})}catch{}let C="",k="",b=0;const w=[];let x=null;const S=(E=()=>{if(!R)return;if(R.classList.remove("pending"),k){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!==k&&(e.textContent=k)}const t=R.querySelector(".body");t&&t.textContent!==C&&(t.textContent=C);const n=C.length+k.length+4*b;liveMeterDue(x,n)&&(x=n,K(y,{prompt:e,reply:C,reasoning:k,measuredReasoningTokens:b})),ee()},Z?Z.paint(E):E);var E;const $=e=>{if(e&&"number"==typeof e.thinkingTokens&&e.thinkingTokens>0)return b+=e.thinkingTokens,void S();if(e&&"string"==typeof e.reasoning&&e.reasoning)return k+=e.reasoning,void S();if(e&&"string"==typeof e.note&&e.note){const t=Lo();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=Lo();return t.classList.remove("pending"),To(t,e.approval,".body"),void ee({force:!0})}if(e&&e.rounds){const n=Lo();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 Ho(e.tool);w.push(e.tool);const t=Lo();return t.classList.remove("pending"),Io(t,e.tool,"tool-activity",".body"),void ee()}const n=e&&("string"==typeof e.delta?e.delta:e.content);n&&(C+=n,S())};try{const i=await t.chat({class:s,prompt:e,model:a,maxTokens:f,sessionId:y,autonomous:m,effort:p,workers:h,messages:v,attachments:o,roundsAsk:!0},$);if(i&&i.aborted){const e=new Error(i.message||"This operation was aborted");throw e.name="AbortError",e.code="ABORT_ERR",e}if(i&&i.providerFailed){const e=new Error(i.message||"the provider request failed");throw i.status&&(e.status=i.status),i.code&&(e.code=i.code),e}const r=i&&i.choices&&i.choices[0]||{},c=r.message&&r.message.content||C||"(empty response)";isPlaceholderContent(c)||D.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=F.find((t=>t.class===e));return t?t.label:e}(s)),m?d.push(`autonomous (${p}, ${h||"auto"}w)`):p&&d.push(`effort: ${p}`);const u=turnAccounting(i&&i.usage,a,{costUsd:i&&"number"==typeof i.costUsd?i.costUsd:void 0}),g=displayTokens(u);if(null!=g)d.push(`tokens: ${g}`);else{const t=estimatedBuckets(e,c,c===k?"":k);t&&t.output>0&&d.push(`~${t.output} tokens`)}const b=feeBillable(function(){const e="undefined"!=typeof state?state:null;return e&&e.entitlement?e.entitlement:null}());null!=u.cost&&b&&d.push(fmtCost(u.cost,u.real)),"byok"===s&&null!=u.cost&&b&&d.push("your provider bill (est.) + AEGIS handling fee");const x=_(y,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===k?"":k}),S=fmtRoll(x,{omitMoney:!b});S&&d.push(`session: ${S}`),i&&i.pooled_notice&&d.push(i.pooled_notice),Eo("assistant",c,d.join(" · ")||void 0,y,w);try{await n.append(y,{role:"assistant",content:c,...j(i&&i.usage,a,u,{prompt:e,reply:c,reasoning:c===k?"":k,calls:i&&i.calls})}),await n.save({id:y,title:e.slice(0,60),seed:!0}),"function"==typeof n.nameSession&&n.nameSession({sessionId:y,prompt:e,class:s,model:a}).then((e=>{e&&rs().catch((()=>{}))})).catch((()=>{}))}catch{}fs(),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",(()=>{$o(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))$o(t,a,e)}({prompt:e,cls:s,model:a,maxTokens:f,parentSessionId:y})}catch(t){if(isCancellation(t,{userStopped:X===u})){const t=salvageTurn({streamedText:C,reasoningText:k}),o=t.text,s=t.reasoning,i=replayableContent(t.kind,o);D.push({role:"assistant",content:i});const r=turnAccounting(void 0,a,{}),c=_(y,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}`),Eo("assistant",o,l.join(" · "),y,w);try{await n.append(y,{role:"assistant",content:i,...j(void 0,a,r,{prompt:e,reply:o,reasoning:s})})}catch{}fs()}else Eo("assistant",`Error: ${t&&t.message?t.message:t}`,"request failed")}finally{qo(!1),J===u&&(J=null,T=null),rs()}}let bs=!1;function ws(){const e=l.messages;e&&(bs=!0,e.scrollTo({top:e.scrollHeight,behavior:"smooth"}),l.scrollBottom&&(l.scrollBottom.hidden=!0))}let xs=[],Ss=[],Es=0;function $s(){return l.classSelect&&"pro"===l.classSelect.value}function Ls(){const e=l.attachRow,t=l.attachNote;if(!e)return;e.textContent="";const n=xs.length+Ss.length;if(e.hidden=0===n,t&&(t.hidden=!0,t.textContent=""),n){for(const t of xs){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} · ${Ms(t.size)}${t.truncated?" (truncated)":""}`,n.appendChild(s),n.appendChild(qs((()=>{xs=xs.filter((e=>e!==t)),Ls()}))),e.appendChild(n)}for(const t of Ss){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(qs((()=>{Ss=Ss.filter((e=>e!==t)),Ls()}))),e.appendChild(n)}if(t&&$s()){const e=xs.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 qs(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 Ms(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 As(t){const n=(t||"").split(/[\\/]/).pop()||t;if(xs.length>=8)return Ss.push({path:t,name:n,reason:"at most 8 files per message"}),void Ls();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 Ss.push({path:t,name:n,reason:o&&o.reason||"not attached"}),void Ls();xs.some((e=>e.path===o.attachment.path))||(xs.push(o.attachment),Ls())}const Ns=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Hs(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():""}const Bs='<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12.1 7.3 8.05 11.35a2.85 2.85 0 0 1-4.03-4.03l4.4-4.4a1.9 1.9 0 1 1 2.69 2.69l-4.4 4.4a.95.95 0 1 1-1.35-1.35L9.4 4.6"/></svg>';function Is(e,t){const n=[],o="string"==typeof e?e:"";o.trim()&&n.push({type:"text",text:o});for(const e of t||[]){const t=Hs(e);"image"===e.kind&&e.dataUrl&&Ns.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 Rs="aegis.onboardingSeen";async function Ts(){!function(){const t=document.getElementById("onboard-overlay");if(!t)return;let n=!1;try{n="1"===localStorage.getItem(Rs)}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(Rs,"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"),Ae(t.username),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(),lo();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),Fo(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(lo(),fo(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",vs),l.railAutomations&&l.railAutomations.addEventListener("click",(async()=>{await Promise.all([ot().catch((()=>{})),We().catch((()=>{}))]),uo()})),l.automationsBack&&l.automationsBack.addEventListener("click",mo),l.railSettings&&l.railSettings.addEventListener("click",lo),l.settingsBack&&l.settingsBack.addEventListener("click",mo),l.settingsJump&&l.settingsJump.addEventListener("click",(e=>{const t=e.target.closest(".settings-jump-link");if(!t)return;const n=document.getElementById(t.dataset.jump);n&&ro(n)})),l.importSessionBtn&&l.importSessionBtn.addEventListener("click",Jt),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",zt),l.importBackdrop&&l.importBackdrop.addEventListener("click",zt),l.importSessionsBtn&&l.importSessionsBtn.addEventListener("click",Xt),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 $t(n,s.upgrade,`import stopped after ${s.saved||0} entries`),void await Vn();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 Vn()}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(vs),e.onMenuSearch&&e.onMenuSearch((()=>jt(""))),e.onMenuSearchMemory&&e.onMenuSearchMemory(Gt),
|
|
6
6
|
// Help > Credits & licence… — the AGPL, the program notice and every vendored
|
|
7
|
-
e.onMenuCredits&&e.onMenuCredits(Xt),e.onMenuPalette&&e.onMenuPalette(mn),e.onMenuToggleSidebar&&e.onMenuToggleSidebar(fn),e.onMenuFind&&e.onMenuFind(qn),e.onMenuGoBack&&e.onMenuGoBack($n),e.onMenuGoForward&&e.onMenuGoForward(Ln),l.findInput&&(l.findInput.addEventListener("input",(()=>{hn.query=l.findInput.value,kn(!0)})),l.findInput.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),Dn(e.shiftKey?-1:1))}))),l.findNext&&l.findNext.addEventListener("click",(()=>Dn(1))),l.findPrev&&l.findPrev.addEventListener("click",(()=>Dn(-1))),l.findClose&&l.findClose.addEventListener("click",Mn),l.paletteInput&&(l.paletteInput.addEventListener("input",(()=>ln(l.paletteInput.value))),l.paletteInput.addEventListener("keydown",(e=>{if("ArrowDown"===e.key)return e.preventDefault(),void un(1);if("ArrowUp"===e.key)return e.preventDefault(),void un(-1);if("Enter"===e.key){const t=on[sn];if(!t)return;e.preventDefault(),Pn(t.action)}}))),l.paletteBackdrop&&l.paletteBackdrop.addEventListener("click",pn),e.onMenuFingerprint&&e.onMenuFingerprint((()=>{dt&&"function"==typeof dt.open&&dt.open()})),e.onMenuGoogleDrive&&e.onMenuGoogleDrive((()=>{dt&&"function"==typeof dt.open&&dt.open({focus:"drive"})})),e.onMenuExportMarkdown&&e.onMenuExportMarkdown((()=>ps("markdown"))),e.onMenuExportJson&&e.onMenuExportJson((()=>ps("json"))),e.onDeepLink&&e.onDeepLink(hs),e.onQuickLauncherPush&&e.onQuickLauncherPush(nt),l.sessionsRefresh.addEventListener("click",os),l.sessionsFilter&&(l.sessionsFilter.addEventListener("input",(()=>ss())),l.sessionsFilter.addEventListener("keydown",(e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),l.sessionsFilter.value="",ss())}))),l.syncNow.addEventListener("click",us),l.sessionsExport.addEventListener("click",(()=>ps("markdown"))),l.apiKeySave.addEventListener("click",we),l.apiKeyVerify.addEventListener("click",xe),l.apiKeyInput.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),we())})),l.settingsGoogleSignin.addEventListener("click",(async()=>{try{const t=await e.driveSignIn();t&&(l.apiKeyInput.value=t.token||"",we())}catch(e){setApiKeyHint(`Sign-in failed: ${e.message}`,"error")}})),l.customSave&&l.customSave.addEventListener("click",_o),l.customRemove&&l.customRemove.addEventListener("click",Ko);for(const e of[l.customBaseUrl,l.customKey,l.customModel])e&&e.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),_o())}));l.upgradePlan.addEventListener("click",(()=>ke("upgrade"))),l.topupBtn.addEventListener("click",(()=>ke("topup"))),attachScrollLift({panes:document.querySelectorAll(".messages, .side, .memory-scroll"),target:document.body,requestFrame:e=>window.requestAnimationFrame(e),onSync:({panes:e})=>function(e){const t=l.scrollBottom;if(!t)return;const n=e.find((e=>e&&e.classList&&e.classList.contains("messages")));if(!n)return;const o=n.scrollHeight-n.scrollTop-n.clientHeight;if(gs){if(!(o<=24))return void(t.hidden=!0);gs=!1}t.hidden=o<=24}(e)}),l.scrollBottom&&l.scrollBottom.addEventListener("click",vs),async function(){if(e.getFontScale)try{const t=await e.getFontScale();qe(t&&"number"==typeof t.scale?t.scale:1)}catch{qe(1)}}(),async function(){if(e.getAccent)try{const t=await e.getAccent();Me(t&&t.name?t.name:"default")}catch{Me("default")}}(),l.quickLauncherSave.addEventListener("click",Ee),l.quickLauncherShortcut.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),Ee())})),l.fontScale&&l.fontScale.addEventListener("change",(()=>async function(t){if(e.getFontScale)try{const n=await e.setFontScale(t);qe(n&&"number"==typeof n.scale?n.scale:t)}catch(e){l.fontScaleHint&&(l.fontScaleHint.textContent=`save failed: ${e&&e.message?e.message:e}`)}}(Number(l.fontScale.value)))),l.accentSelect&&l.accentSelect.addEventListener("change",(()=>async function(t){if(e.setAccent)try{const n=await e.setAccent(t);Me(n&&n.name?n.name:t)}catch(e){l.accentHint&&(l.accentHint.textContent=`save failed: ${e&&e.message?e.message:e}`)}}(l.accentSelect.value))),l.confirmMode&&l.confirmMode.addEventListener("change",(()=>Ae(l.confirmMode.checked))),l.planMode&&l.planMode.addEventListener("change",(()=>async function(t){if(l.planMode){l.planMode.disabled=!0;try{Ne(await e.setPermissionMode(t))}catch(e){l.planMode.checked=!t,l.planModeHint&&(l.planModeHint.textContent=`save failed: ${e&&e.message?e.message:e}`)}finally{l.planMode.disabled=!1}}}(l.planMode.checked))),l.permRulesForm&&l.permRulesForm.addEventListener("submit",(t=>{t.preventDefault(),async function(t,n){if(!e.permRulesAdd)return;const o=String(null==n?"":n).trim();if(o){l.permRulesAdd&&(l.permRulesAdd.disabled=!0);try{const n=await e.permRulesAdd(t,o);if(n&&!0===n.ok){Be(n),l.permRulesInput&&(l.permRulesInput.value="");const e=!1===n.added?"already stored":"stored";l.permRulesStatus&&(l.permRulesStatus.textContent=n.warning?`${e}: ${o} — ${n.warning}`:`${e}: ${o}`)}else l.permRulesStatus&&(l.permRulesStatus.textContent=`not stored: ${n&&n.reason||"the store refused it"}`)}catch(e){l.permRulesStatus&&(l.permRulesStatus.textContent=`add failed: ${e&&e.message?e.message:e}`)}finally{l.permRulesAdd&&(l.permRulesAdd.disabled=!1)}}else l.permRulesStatus&&(l.permRulesStatus.textContent="type a rule first")}(l.permRulesListSelect?l.permRulesListSelect.value:"allow",l.permRulesInput&&l.permRulesInput.value)})),l.sandboxMode&&l.sandboxMode.addEventListener("change",(()=>{const e=l.sandboxNetwork&&l.sandboxNetwork.checked?"open":"restricted";Fe(l.sandboxMode.value,e)})),l.sandboxNetwork&&l.sandboxNetwork.addEventListener("change",(()=>{Fe(l.sandboxMode?l.sandboxMode.value:"workspace-write",l.sandboxNetwork.checked?"open":"restricted")})),l.autoMode&&l.autoMode.addEventListener("click",(()=>{l.confirmMode&&Ae(!l.confirmMode.checked)})),l.composer.addEventListener("submit",(e=>{e.preventDefault(),ys()})),l.prompt&&(window.addEventListener("dragenter",(e=>{if(!e.dataTransfer)return;const t=Array.from(e.dataTransfer.types||[]);(t.includes("Files")||t.includes("text/plain")||t.includes("text/uri-list"))&&(bs+=1,document.body.classList.add("is-dropping"))})),window.addEventListener("dragleave",(()=>{bs=Math.max(0,bs-1),0===bs&&document.body.classList.remove("is-dropping")})),window.addEventListener("dragover",(e=>{e.dataTransfer&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")})),window.addEventListener("drop",(t=>{bs=0,document.body.classList.remove("is-dropping"),async function(t){const n=t.dataTransfer;if(!n)return;const o=Array.from(n.files||[]);if(o.length){t.preventDefault();for(const t of o){const n=e.attachments.pathFor(t);n?await $s(n):(ks.push({name:t.name||"file",reason:"no path available"}),xs())}return}const s=(n.getData("text/uri-list")||n.getData("text/plain")||"").split(/\r?\n/).map((e=>{const t=e.trim();if(!t)return"";const n=t.replace(/^file:\/\//,"");if(n===t)return t;try{return decodeURIComponent(n).trim()}catch{return n.trim()}})).filter(Boolean).join("\n");s&&(t.preventDefault(),function(e){const t=l.prompt;if(!t)return;const n="number"==typeof t.selectionStart?t.selectionStart:t.value.length,o="number"==typeof t.selectionEnd?t.selectionEnd:t.value.length,s=t.value.slice(0,n),a=t.value.slice(o),i=s&&!/\s$/.test(s)?" ":"";t.value=`${s}${i}${e}${a}`;const r=(s+i+e).length;try{t.setSelectionRange(r,r)}catch{}t.focus()}(s))}(t).catch((()=>{}))})),document.addEventListener("dragover",(e=>e.preventDefault())),document.addEventListener("drop",(e=>e.preventDefault())),l.classSelect&&l.classSelect.addEventListener("change",xs),xs()),l.prompt.addEventListener("keydown",(e=>{if(Hn()){if("ArrowDown"===e.key)return e.preventDefault(),void Fn(1);if("ArrowUp"===e.key)return e.preventDefault(),void Fn(-1);if(("Enter"===e.key||"Tab"===e.key)&&An.rows.length)return e.preventDefault(),void On()}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),l.composer.requestSubmit())})),l.prompt.addEventListener("input",(()=>{Tn().catch((()=>{}))})),l.prompt.addEventListener("click",(()=>{Hn()&&Tn().catch((()=>{}))})),l.tabSessions&&l.tabSessions.addEventListener("click",(()=>Wo("sessions"))),l.tabMemory&&l.tabMemory.addEventListener("click",(()=>Wo("memory"))),l.memorySearchForm.addEventListener("submit",(e=>{e.preventDefault(),St(l.memoryQuery.value.trim())})),l.memorySaveBtn.addEventListener("click",Un),l.sessionClose&&l.sessionClose.addEventListener("click",_t),l.sessionBackdrop&&l.sessionBackdrop.addEventListener("click",_t),l.sessionClear&&l.sessionClear.addEventListener("click",(()=>{l.sessionQuery&&(l.sessionQuery.value=""),It="",l.sessionHint&&(l.sessionHint.textContent=""),Dt(""),l.sessionQuery&&l.sessionQuery.focus()})),l.sessionFilters&&l.sessionFilters.addEventListener("submit",(e=>{e.preventDefault(),Dt(l.sessionQuery?l.sessionQuery.value:"")})),l.sessionQuery&&l.sessionQuery.addEventListener("input",(()=>{Dt(l.sessionQuery.value)})),l.creditsClose&&l.creditsClose.addEventListener("click",Zt),l.creditsBackdrop&&l.creditsBackdrop.addEventListener("click",Zt),l.shortcutsClose&&l.shortcutsClose.addEventListener("click",nn),l.shortcutsBackdrop&&l.shortcutsBackdrop.addEventListener("click",nn),l.memoryOpen&&l.memoryOpen.addEventListener("click",Nt),l.memoryClose&&l.memoryClose.addEventListener("click",Ht),l.memoryBackdrop&&l.memoryBackdrop.addEventListener("click",Ht),l.memoryOverlaySave&&l.memoryOverlaySave.addEventListener("click",Un),l.memoryFilters&&l.memoryFilters.addEventListener("submit",(e=>{e.preventDefault(),it.query=l.memoryOverlayQuery.value.trim(),At(it.query)})),l.memoryFiltersClear&&l.memoryFiltersClear.addEventListener("click",(()=>{l.memoryOverlayQuery.value="",it.query="",it.source="",it.role="",Mt()})),l.keysClose&&l.keysClose.addEventListener("click",vo),l.keysBackdrop&&l.keysBackdrop.addEventListener("click",vo),l.keysDismiss&&l.keysDismiss.addEventListener("click",Co),l.keysGotoAegis&&l.keysGotoAegis.addEventListener("click",(()=>{vo(),ao(),lo(l.apiKeyInput),l.apiKeyInput&&l.apiKeyInput.focus(),l.apiKeyHint&&(l.apiKeyHint.textContent=`Missing: ${function(){const e=[];return!0!==de&&e.push("the AEGIS key"),!0!==ue&&e.push("your provider (BYOK) key"),e.join(" and ")}()}. This is the AEGIS account key — the same one the CLI reads from ~/.aegiscode/.env, so pasting it here configures both.`)})),l.keysGotoByok&&l.keysGotoByok.addEventListener("click",(()=>{vo(),uo()})),s&&(l.queueEnqueue&&l.queueEnqueue.addEventListener("click",We),l.queueDrain&&l.queueDrain.addEventListener("click",(()=>ze("one"))),l.queueProceed&&l.queueProceed.addEventListener("click",(()=>ze("all"))),l.queueStop&&l.queueStop.addEventListener("click",Ye),"function"==typeof s.onProgress&&s.onProgress(tt),"function"==typeof s.onChanged&&s.onChanged((()=>{!function(){if(s)if(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),Oo(l.queueClassSelect.value)})),await je(),await async function(){if(!l.queueClassSelect)return;let e=[];try{e=await t.listClasses()||[]}catch(t){e=[],l.queueModelHint&&(l.queueModelHint.textContent=`listClasses failed: ${t&&t.message?t.message:t}`)}l.queueClassSelect.innerHTML="";for(const t of e){const e=document.createElement("option");e.value=t.class,e.textContent=t.configured?t.label:`${t.label} (not configured)`,l.queueClassSelect.appendChild(e)}const n=localStorage.getItem(u);n&&e.some((e=>e.class===n))&&(l.queueClassSelect.value=n),await Oo(l.queueClassSelect.value)}()),a&&(l.queueAuto&&l.queueAuto.addEventListener("change",(()=>et(l.queueAuto.checked))),l.queueAutoInterval&&l.queueAutoInterval.addEventListener("change",(()=>{l.queueAuto&&l.queueAuto.checked&&et(!0)})),await Ze()),Z=createTranscriptView({messages:l.messages,requestFrame:e=>requestAnimationFrame(e)}),Z.attachScrollVeto();let y=null;window.__aegisSmoke=Object.freeze({isScrolledUp:()=>Z.isScrolledUp(),metrics:()=>Z.metrics(),escapeDecision:()=>y&&"function"==typeof y.lastDecision?y.lastDecision():null,stopOutcome:()=>te}),y=bindEscapeInterrupt({doc:document,isOverlayOpen:rt,onOverlayEscape:()=>{if(Rt())_t();else if(jt())Gt();else if(zt())Zt();else if(en())nn();else if(cn())pn();else if(wn())Mn();else if(Hn())In();else if(lt())vo();else{if(dt&&"function"==typeof dt.close)try{return void dt.close()}catch(e){}Ht()}},hasPendingTurn:()=>!!T,stopTurn:ne}),l.accountBanner&&e.onAccountStatus&&(e.onAccountStatus(ge),e.accountStatus().then(ge).catch((e=>console.warn("account status unavailable",e))),l.accountRetryBtn.addEventListener("click",(()=>ve(l.accountRetryBtn))),l.keysAccountRetry&&l.keysAccountRetry.addEventListener("click",(()=>ve(l.keysAccountRetry)))),l.updateBanner&&e.onUpdateStatus&&(e.onUpdateStatus(he),e.updateStatus().then(he).catch((()=>{})),l.updateDownloadBtn.addEventListener("click",(()=>{l.updateDownloadBtn.disabled=!0,Promise.resolve(e.downloadUpdate()).then((e=>{e&&e.status&&he(e)})).catch((()=>{})).finally((()=>{l.updateDownloadBtn.disabled=!1}))})),l.updateRestartBtn.addEventListener("click",(()=>{e.quitAndInstallUpdate()})),l.updateRetryBtn&&e.checkForUpdates&&l.updateRetryBtn.addEventListener("click",(()=>{l.updateRetryBtn.disabled=!0,Promise.resolve(e.checkForUpdates()).then(he).catch((()=>{})).finally((()=>{l.updateRetryBtn.disabled=!1}))})),l.updateLaterBtn.addEventListener("click",(()=>{fe=pe&&pe.status,l.updateBanner.hidden=!0}))),l.messages.querySelector(".msg, .chatflow")||eo(),xn({kind:"conversations"}),await Io(),await Po(),await async function(){if(o)try{Se(await o.status())}catch(e){l.quickLauncherHint.textContent=`status failed: ${e&&e.message?e.message:e}`}}(),await async function(){if(l.confirmMode&&e.getConfirmMode)try{$e(await e.getConfirmMode())}catch(e){l.confirmModeHint.textContent=`status failed: ${e&&e.message?e.message:e}`}}(),await async function(){if(l.planMode&&e.getPermissionMode)try{Ne(await e.getPermissionMode())}catch(e){l.planModeHint&&(l.planModeHint.textContent=`status failed: ${e&&e.message?e.message:e}`)}}(),await async function(){if(l.permRulesList&&e.permRulesList)try{Be(await e.permRulesList())}catch(e){Be({ok:!1,reason:e&&e.message||String(e)})}}(),await Oe(),await os(),await ls(),Ce(),Wo("sessions"),l.memoryQuietFloor&&(l.memoryQuietFloor.textContent=String(st)),St("");try{!function(){if(window.aegisProviderToolbar&&l.ptList)if(ut=window.aegisProviderToolbar.mount({list:l.ptList,count:l.ptCount,search:l.ptSearch,hint:l.ptHint,onSelect:ft}),l.ptRefresh&&l.ptRefresh.addEventListener("click",(()=>{pt(!0)})),"function"==typeof IntersectionObserver&&l.ptList.closest("section")){const e=new IntersectionObserver((t=>{t.some((e=>e.isIntersecting))&&(e.disconnect(),pt(!1))}));e.observe(l.ptList.closest("section"))}else pt(!1)}()}catch(e){l.ptHint&&(l.ptHint.textContent=`provider list unavailable: ${e&&e.message||e}`)}if(l.companionDismiss&&l.companionDismiss.addEventListener("click",(()=>{localStorage.setItem(ht,JSON.stringify({day:window.aegisCompanion?window.aegisCompanion.dayKey(new Date):"",id:l.companionCard.dataset.messageId||""})),l.companionCard.hidden=!0})),gt(),window.aegisFingerprint)try{dt=window.aegisFingerprint.mount({api:e,getSessionId:()=>O}),dt.refresh().catch((()=>{}))}catch(e){const t=l.fpCardStatus;t&&(t.textContent=`authorship panel unavailable: ${e&&e.message||e}`)}}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",Hs):Hs()}();
|
|
7
|
+
e.onMenuCredits&&e.onMenuCredits(nn),e.onMenuPalette&&e.onMenuPalette(yn),e.onMenuToggleSidebar&&e.onMenuToggleSidebar(vn),e.onMenuFind&&e.onMenuFind(Hn),e.onMenuGoBack&&e.onMenuGoBack(An),e.onMenuGoForward&&e.onMenuGoForward(Nn),l.findInput&&(l.findInput.addEventListener("input",(()=>{Cn.query=l.findInput.value,Sn(!0)})),l.findInput.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),Kn(e.shiftKey?-1:1))}))),l.findNext&&l.findNext.addEventListener("click",(()=>Kn(1))),l.findPrev&&l.findPrev.addEventListener("click",(()=>Kn(-1))),l.findClose&&l.findClose.addEventListener("click",Bn),l.paletteInput&&(l.paletteInput.addEventListener("input",(()=>pn(l.paletteInput.value))),l.paletteInput.addEventListener("keydown",(e=>{if("ArrowDown"===e.key)return e.preventDefault(),void hn(1);if("ArrowUp"===e.key)return e.preventDefault(),void hn(-1);if("Enter"===e.key){const t=cn[ln];if(!t)return;e.preventDefault(),jn(t.action)}}))),l.paletteBackdrop&&l.paletteBackdrop.addEventListener("click",gn),e.onMenuFingerprint&&e.onMenuFingerprint((()=>{ft&&"function"==typeof ft.open&&ft.open()})),e.onMenuGoogleDrive&&e.onMenuGoogleDrive((()=>{ft&&"function"==typeof ft.open&&ft.open({focus:"drive"})})),e.onMenuExportMarkdown&&e.onMenuExportMarkdown((()=>gs("markdown"))),e.onMenuExportJson&&e.onMenuExportJson((()=>gs("json"))),e.onDeepLink&&e.onDeepLink(Cs),e.onQuickLauncherPush&&e.onQuickLauncherPush(it),l.sessionsRefresh.addEventListener("click",rs),l.sessionsFilter&&(l.sessionsFilter.addEventListener("input",(()=>cs())),l.sessionsFilter.addEventListener("keydown",(e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),l.sessionsFilter.value="",cs())}))),l.syncNow.addEventListener("click",hs),l.sessionsExport.addEventListener("click",(()=>gs("markdown"))),l.apiKeySave.addEventListener("click",we),l.apiKeyVerify.addEventListener("click",xe),l.apiKeyInput.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),we())})),l.settingsGoogleSignin.addEventListener("click",(async()=>{try{const t=await e.driveSignIn();t&&(l.apiKeyInput.value=t.token||"",we(),Ae(t.username))}catch(e){setApiKeyHint(`Sign-in failed: ${e.message}`,"error")}})),l.customSave&&l.customSave.addEventListener("click",Vo),l.customRemove&&l.customRemove.addEventListener("click",Qo);for(const e of[l.customBaseUrl,l.customKey,l.customModel])e&&e.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),Vo())}));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(bs){if(!(o<=24))return void(t.hidden=!0);bs=!1}t.hidden=o<=24}(e)}),l.scrollBottom&&l.scrollBottom.addEventListener("click",ws),async function(){if(e.getFontScale)try{const t=await e.getFontScale();He(t&&"number"==typeof t.scale?t.scale:1)}catch{He(1)}}(),async function(){if(e.getAccent)try{const t=await e.getAccent();Be(t&&t.name?t.name:"default")}catch{Be("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);He(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);Be(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",(()=>Ie(l.confirmMode.checked))),l.devMode&&l.devMode.addEventListener("change",(()=>async function(t){if(l.devMode){l.devMode.disabled=!0;try{Ne(await e.setDevMode(t))}catch(e){l.devMode.checked=!t,l.devModeHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{l.devMode.disabled=!1}}}(l.devMode.checked))),l.planMode&&l.planMode.addEventListener("change",(()=>async function(t){if(l.planMode){l.planMode.disabled=!0;try{Re(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){Oe(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";_e(l.sandboxMode.value,e)})),l.sandboxNetwork&&l.sandboxNetwork.addEventListener("change",(()=>{_e(l.sandboxMode?l.sandboxMode.value:"workspace-write",l.sandboxNetwork.checked?"open":"restricted")})),l.autoMode&&l.autoMode.addEventListener("click",(()=>{l.confirmMode&&Ie(!l.confirmMode.checked)})),l.composer.addEventListener("submit",(e=>{e.preventDefault(),ks()})),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"))&&(Es+=1,document.body.classList.add("is-dropping"))})),window.addEventListener("dragleave",(()=>{Es=Math.max(0,Es-1),0===Es&&document.body.classList.remove("is-dropping")})),window.addEventListener("dragover",(e=>{e.dataTransfer&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")})),window.addEventListener("drop",(t=>{Es=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 As(n):(Ss.push({name:t.name||"file",reason:"no path available"}),Ls())}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",Ls),Ls()),l.prompt.addEventListener("keydown",(e=>{if(Tn()){if("ArrowDown"===e.key)return e.preventDefault(),void _n(1);if("ArrowUp"===e.key)return e.preventDefault(),void _n(-1);if(("Enter"===e.key||"Tab"===e.key)&&In.rows.length)return e.preventDefault(),void Un()}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),l.composer.requestSubmit())})),l.prompt.addEventListener("input",(()=>{Pn().catch((()=>{}))})),l.prompt.addEventListener("click",(()=>{Tn()&&Pn().catch((()=>{}))})),l.tabSessions&&l.tabSessions.addEventListener("click",(()=>Xo("sessions"))),l.tabMemory&&l.tabMemory.addEventListener("click",(()=>Xo("memory"))),l.memorySearchForm.addEventListener("submit",(e=>{e.preventDefault(),qt(l.memoryQuery.value.trim())})),l.memorySaveBtn.addEventListener("click",Gn),l.sessionClose&&l.sessionClose.addEventListener("click",Vt),l.sessionBackdrop&&l.sessionBackdrop.addEventListener("click",Vt),l.sessionClear&&l.sessionClear.addEventListener("click",(()=>{l.sessionQuery&&(l.sessionQuery.value=""),Dt="",l.sessionHint&&(l.sessionHint.textContent=""),Kt(""),l.sessionQuery&&l.sessionQuery.focus()})),l.sessionFilters&&l.sessionFilters.addEventListener("submit",(e=>{e.preventDefault(),Kt(l.sessionQuery?l.sessionQuery.value:"")})),l.sessionQuery&&l.sessionQuery.addEventListener("input",(()=>{Kt(l.sessionQuery.value)})),l.creditsClose&&l.creditsClose.addEventListener("click",on),l.creditsBackdrop&&l.creditsBackdrop.addEventListener("click",on),l.shortcutsClose&&l.shortcutsClose.addEventListener("click",rn),l.shortcutsBackdrop&&l.shortcutsBackdrop.addEventListener("click",rn),l.memoryOpen&&l.memoryOpen.addEventListener("click",Rt),l.memoryClose&&l.memoryClose.addEventListener("click",Tt),l.memoryBackdrop&&l.memoryBackdrop.addEventListener("click",Tt),l.memoryOverlaySave&&l.memoryOverlaySave.addEventListener("click",Gn),l.memoryFilters&&l.memoryFilters.addEventListener("submit",(e=>{e.preventDefault(),dt.query=l.memoryOverlayQuery.value.trim(),It(dt.query)})),l.memoryFiltersClear&&l.memoryFiltersClear.addEventListener("click",(()=>{l.memoryOverlayQuery.value="",dt.query="",dt.source="",dt.role="",Bt()})),l.keysClose&&l.keysClose.addEventListener("click",wo),l.keysBackdrop&&l.keysBackdrop.addEventListener("click",wo),l.keysDismiss&&l.keysDismiss.addEventListener("click",xo),l.keysGotoAegis&&l.keysGotoAegis.addEventListener("click",(()=>{wo(),lo(),fo(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",(()=>{wo(),ho()})),s&&(l.queueEnqueue&&l.queueEnqueue.addEventListener("click",Xe),l.queueDrain&&l.queueDrain.addEventListener("click",(()=>Ze("one"))),l.queueProceed&&l.queueProceed.addEventListener("click",(()=>Ze("all"))),l.queueStop&&l.queueStop.addEventListener("click",et),"function"==typeof s.onProgress&&s.onProgress(at),"function"==typeof s.onChanged&&s.onChanged((()=>{!function(){if(s)if(Ye){if(null!=ze)return;ze=setTimeout(Je,60)}else null!=ze&&clearTimeout(ze),ze=setTimeout(Je,60)}()})),l.queueClassSelect&&l.queueClassSelect.addEventListener("change",(()=>{localStorage.setItem(u,l.queueClassSelect.value),Uo(l.queueClassSelect.value)})),await We(),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 Uo(l.queueClassSelect.value)}()),a&&(l.queueAuto&&l.queueAuto.addEventListener("change",(()=>st(l.queueAuto.checked))),l.queueAutoInterval&&l.queueAutoInterval.addEventListener("change",(()=>{l.queueAuto&&l.queueAuto.checked&&st(!0)})),await ot()),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:ut,onOverlayEscape:()=>{if(Ft())Vt();else if(Wt())zt();else if(Zt())on();else if(sn())rn();else if(mn())gn();else if($n())Bn();else if(Tn())Dn();else if(pt())wo();else{if(ft&&"function"==typeof ft.close)try{return void ft.close()}catch(e){}Tt()}},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")||so(),Ln({kind:"conversations"}),await Do(),await jo(),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.developerCard&&e.getAccountUsername)try{const t=await e.getAccountUsername();Me(t&&t.username)}catch{}}(),await async function(){if(l.devMode&&e.getDevMode)try{Ne(await e.getDevMode())}catch(e){l.devModeHint.textContent=`status failed: ${e&&e.message?e.message:e}`}}(),await async function(){if(l.planMode&&e.getPermissionMode)try{Re(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{Oe(await e.permRulesList())}catch(e){Oe({ok:!1,reason:e&&e.message||String(e)})}}(),await Ue(),await rs(),await ps(),Ce(),Xo("sessions"),l.memoryQuietFloor&&(l.memoryQuietFloor.textContent=String(ct)),qt("");try{!function(){if(window.aegisProviderToolbar&&l.ptList)if(ht=window.aegisProviderToolbar.mount({list:l.ptList,count:l.ptCount,search:l.ptSearch,hint:l.ptHint,onSelect:vt}),l.ptRefresh&&l.ptRefresh.addEventListener("click",(()=>{gt(!0)})),"function"==typeof IntersectionObserver&&l.ptList.closest("section")){const e=new IntersectionObserver((t=>{t.some((e=>e.isIntersecting))&&(e.disconnect(),gt(!1))}));e.observe(l.ptList.closest("section"))}else gt(!1)}()}catch(e){l.ptHint&&(l.ptHint.textContent=`provider list unavailable: ${e&&e.message||e}`)}if(l.companionDismiss&&l.companionDismiss.addEventListener("click",(()=>{localStorage.setItem(Ct,JSON.stringify({day:window.aegisCompanion?window.aegisCompanion.dayKey(new Date):"",id:l.companionCard.dataset.messageId||""})),l.companionCard.hidden=!0})),bt(),window.aegisFingerprint)try{ft=window.aegisFingerprint.mount({api:e,getSessionId:()=>O}),ft.refresh().catch((()=>{}))}catch(e){const t=l.fpCardStatus;t&&(t.textContent=`authorship panel unavailable: ${e&&e.message||e}`)}}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",Ts):Ts()}();
|