aegis-desktop 1.0.25 → 1.0.27
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/package.json +1 -1
- package/renderer/app.js +1 -1
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "aegis-desktop",
|
|
3
3
|
"productName": "AEGIS Desktop",
|
|
4
4
|
"desktopName": "aegis-desktop",
|
|
5
|
-
"version": "1.0.
|
|
5
|
+
"version": "1.0.27",
|
|
6
6
|
"description": "Thin Electron host for AEGIS — a local chat UI over the shared client/aegis.js transport. Ships transport + UI only; engine logic stays server-side.",
|
|
7
7
|
"author": {
|
|
8
8
|
"name": "AEGIS Code",
|
package/renderer/app.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";!function(){const e=window.aegis,t=window.models,n=window.sync,o=window.quickLauncher,s=window.queue,a=window.auto;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 i={updateBanner:"update-banner",updateBannerText:"update-banner-text",updateDownloadBtn:"update-download-btn",updateRestartBtn:"update-restart-btn",updateRetryBtn:"update-retry-btn",updateLaterBtn:"update-later-btn",accountBanner:"account-banner",accountBannerText:"account-banner-text",accountRetryBtn:"account-retry-btn",keysAccount:"keys-account",keysAccountRetry:"keys-account-retry",connDot:"conn-dot",connText:"conn-text",app:"st-app",client:"st-client",base:"st-base",key:"st-key",plan:"st-plan",balance:"st-balance",upgradePlan:"upgrade-plan",topupBtn:"topup-btn",topupAmount:"topup-amount",billingHint:"billing-hint",apiKeyInput:"api-key-input",apiKeySave:"api-key-save",apiKeyVerify:"api-key-verify",apiKeyHint:"api-key-hint",classSelect:"class-select",modelSelect:"model-select",providerMark:"provider-mark",ptSearch:"pt-search",ptRefresh:"pt-refresh",ptList:"pt-list",ptCount:"pt-count",ptHint:"pt-hint",companionCard:"companion-card",companionText:"companion-text",companionDismiss:"companion-dismiss",modelFree:"model-input",budgetHint:"budget-hint",autonomousToggle:"autonomous-toggle",autonomousToggleWrap:"autonomous-toggle-wrap",autonomousControls:"autonomous-controls",effortSelect:"effort-select",autonomousWorkers:"autonomous-workers",modelHint:"model-hint",settingsList:"settings-list",settingsHint:"settings-hint",customBaseUrl:"custom-base-url",customKey:"custom-key",customModel:"custom-model",customSave:"custom-save",customRemove:"custom-remove",customStatus:"custom-status",quickLauncherEnabled:"quick-launcher-enabled",quickLauncherShortcut:"quick-launcher-shortcut",quickLauncherSave:"quick-launcher-save",quickLauncherHint:"quick-launcher-hint",confirmMode:"confirm-mode-toggle",confirmModeHint:"confirm-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",syncNow:"sync-now",syncStatus:"sync-status",sessionMeter:"session-meter",newChat:"new-chat",memorySearchForm:"memory-search-form",memoryQuery:"memory-query",memoryResults:"memory-results",memoryEntry:"memory-entry",memorySaveBtn:"memory-save-btn",memoryImportBtn:"memory-import-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",fpCardStatus:"fp-card-status",fpOpen:"fp-open",fpOverlay:"fp-overlay",messages:"messages",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",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"},r={};for(const[e,t]of Object.entries(i))Object.defineProperty(r,e,{get:()=>document.getElementById(t),enumerable:!0,configurable:!0});const l="aegis.class",c="aegis.queueClass",d="aegis.autonomous",u="aegis.effort",m="aegis.autonomousWorkers",p="aegis.explore",y="aegis.welcomeConnectDismissed",h="aegis",f=new Set(["__aegis","aegis"]),g="local",v="custom",k="http://localhost:11434",C="https://aegiscloud.org/key?s=desktop&c=key_prompt",b="The autonomous queue keeps running after you close the laptop.",w="https://aegiscloud.org",x=/^[a-z0-9][a-z0-9_-]{0,63}$/;function S(e,t){const n=new URL(`${w}/go/${e}`);n.searchParams.set("s","desktop");const o=null==t?"":String(t).trim().toLowerCase();return x.test(o)&&n.searchParams.set("c",o),n.toString()}function E(e){return S("upgrade",e)}function $(e){return S("topup",e)}const q={welcome_cloud:"welcome",queue_cap:"queue",memory_quota:"memory",status_card:"status",topup_bank:"topup"},L="upgrade_prompt_rendered",A="upgrade_prompt_clicked";let M=!1;function N(e,t){try{const n=q[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(!M){M=!0;try{console.debug("telemetry: prompt event failed (suppressed)",e)}catch{}}}}function H(e,t,n,o){const s=document.createElement("a");return s.href=function(e,t){const n="topup_bank"===t?$(t):E(t);if(!e)return n;let o;try{o=new URL(e,w)}catch{return e}return o.origin!==w||o.searchParams.get("s")||o.searchParams.get("utm_source")?e:/topup/.test(o.pathname)?$(t):n}(t,n),s.target="_blank",s.rel="noreferrer noopener",s.textContent=o,s.addEventListener("click",(()=>N(A,n))),e.appendChild(s),!1===e.isConnected||e.hidden||N(L,n),s}let I=null,B=null,T=null,R=[],U=[],O=new Map;const D=new Map;function F(e,t,n={}){const o=e||"",s=rollTurn(function(e){const t=e||"";return D.has(t)||D.set(t,emptyRoll()),D.get(t)}(o),t,n);return D.set(o,s),P(o),s}function P(e,t){const n=r.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(!I)return null;let e=I.querySelector(".typing-tokens");return e||(e=document.createElement("span"),e.className="typing-tokens",e.hidden=!0,I.appendChild(e)),e}():null;if(s&&(s.textContent=o,s.hidden=!o),!n)return;if(T!==e)return void(n.hidden=!0);let a=D.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 _(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 K="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.",j=[{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 G=0;const W=new Set;function Q(){for(const e of W)try{t.cancel(e)}catch{}W.clear()}let V=0,Y=null,z=null,J=null;function X(e){return!!J&&J.follow(e)}let Z=null;function ee(){if(!B)return!1;if(!stopAppliesTo(Y,z))return!1;z=Y;const e=B;Z={sessionId:e,at:Date.now(),state:"requested"};try{const n=t.cancel(e);n&&"function"==typeof n.then&&n.then((t=>{Z={sessionId:e,at:Date.now(),state:"settled",accepted:!t||!1!==t.ok,result:void 0===t?null:t}}),(t=>{Z={sessionId:e,at:Date.now(),state:"rejected",accepted:!1,error:t&&t.message||String(t)}}))}catch(t){Z={sessionId:e,at:Date.now(),state:"threw",accepted:!1,error:t&&t.message||String(t)}}if(I){const e=I.querySelector(".cancel-btn");e&&(e.disabled=!0,e.textContent="stopping…")}return!0}function te(){const e=r.autonomousToggle;return Boolean(e&&e.checked)}function ne(){if(!r.autonomousControls)return;const e=r.autonomousToggleWrap&&!r.autonomousToggleWrap.hidden;r.autonomousControls.hidden=!(e&&te())}function oe(){if(r.modelFree&&!r.modelFree.hidden){const e=r.modelFree.value.trim();if(e)return e}return r.modelSelect.value}function se(e,t){const n=void 0===t?oe():t;r.budgetHint&&(r.budgetHint.textContent=function(e,t){const n=ie(),o=n,s=n;return e===h?`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)),ae()}function ae(){r.providerMark&&window.aegisProviderMark&&window.aegisProviderMark.paint(r.providerMark,oe())}function ie(){const e=r.effortSelect&&r.effortSelect.value;return"low"===e||"medium"===e||"max"===e?e:"high"}function re(e,t){r.connDot.classList.toggle("ok",Boolean(e)),r.connText.textContent=t}let le=null,ce=!1;function de(e){if(!e)return le=null,ce=!1,void re(!1,"IPC unavailable");le=Boolean(e.keyConfigured),ce=Boolean(e.providerConfigured),r.app.textContent=e.appVersion?`v${e.appVersion}`:"–",r.client.textContent=e.clientVersion||"–",r.base.textContent=e.apiBase||"–",r.key.textContent=e.keyConfigured?e.keyMask:"not set",re(e.keyConfigured,e.keyConfigured?"key configured":"no API key"),Lt(),bt(),function(){const e=document.getElementById("keys-overlay");if(!e)return;let t=!1;try{t="on"===localStorage.getItem(Tt)}catch{}t||null===le?e.hidden=!0:(Rt(),Boolean(B)?Ut():!0!==le||!0!==ce?r.keysOverlay&&(Rt(),r.keysOverlay.hidden&&(r.keysOverlay.hidden=!1,document.body.classList.add("keys-open"))):Ut())}()}let ue=null,me=null;function pe(e){if(!r.updateBanner)return;ue=e;try{tt()}catch{}const t=e&&e.status;if(!t||"idle"===t||"disabled"===t||"checking"===t||"up-to-date"===t||"unavailable"===t||t===me)return void(r.updateBanner.hidden=!0);let n="",o=!1,s=!1,a=!1;const i=e.version?`v${e.version} `:"";if("available"===t)n=e.command?e.commandIsSentence?`Update ${i}available. ${e.command}`:`Update ${i}available — run: ${e.command}`:`Update ${i}available.`,o=!!e.canDownload,o&&(n=`Update ${i}available.`);else if("downloading"===t)n=`Downloading update${"number"==typeof e.progress?` (${Math.round(e.progress)}%)`:""}…`;else if("downloaded"===t)n=`Update ${i}downloaded — restart to install.`,s=!0;else{if("error"!==t)return void(r.updateBanner.hidden=!0);n=`Update check failed: ${e.error||"unknown error"}`,e.transient&&(n+=" — will retry automatically."),a=!0}r.updateBannerText.textContent=n,r.updateDownloadBtn.hidden=!o,r.updateRestartBtn.hidden=!s,r.updateRetryBtn&&(r.updateRetryBtn.hidden=!a),r.updateBanner.hidden=!1}let ye=null;function he(e){ye=e&&"no-key"===e.status?e.reason:null,Rt(),r.accountBanner&&(ye?(r.accountBannerText.textContent=`No AEGIS account key on this machine: ${ye}.`,r.accountBanner.hidden=!1):r.accountBanner.hidden=!0)}function fe(t){t.disabled=!0,e.registerAccount().then((e=>{if(he(e),!e)return ke()})).catch((e=>he({status:"no-key",reason:String(e&&e.message||e)}))).finally((()=>{t.disabled=!1}))}async function ge(){try{const t=await e.verifyApiKey();t&&t.ok?r.plan.textContent=t.valid?t.plan||"active":"invalid key":r.plan.textContent="unavailable"}catch{r.plan.textContent="unavailable"}try{const t=await e.tokenBankBalance();r.balance.textContent=t&&null!=t.balance_eur?`€${t.balance_eur}`:"–"}catch{r.balance.textContent="unavailable"}}async function ve(t){const n=Math.round(Number(r.topupAmount&&r.topupAmount.value)||10),o="topup"===t?r.topupBtn:r.upgradePlan;if(o&&(o.disabled=!0),"topup"===t&&!1===le)return o&&(o.disabled=!1),void(r.billingHint.textContent="add your AEGIS API key above — a top-up is credited to your account");r.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?(r.billingHint.textContent=`free plan cap reached — ${n} lifts it. `,void H(r.billingHint,e.upgrade.url,"topup"===t?"topup_bank":"status_card","See plans →")):void(e.setupRequired?r.billingHint.textContent="checkout is not configured on the server yet (no Stripe price id)":r.billingHint.textContent=`${n} failed: ${e.reason||"the server returned no checkout URL"}`);r.billingHint.textContent=`add your AEGIS API key above — a ${n} needs an account`}(o||{},t);r.billingHint.textContent="opening checkout…";const s=await e.openExternal(o.url);if(s&&!1===s.ok)return void(r.billingHint.textContent=`could not open the checkout page: ${s.reason||"unknown reason"}`);r.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){r.billingHint.textContent=`billing failed: ${e&&e.message?e.message:e}`}finally{o&&(o.disabled=!1)}}async function ke(){try{de(await e.status())}catch{de(null)}await tn(),await ge()}async function Ce(){const t=r.apiKeyInput.value.trim();r.apiKeySave.disabled=!0,r.apiKeyVerify.disabled=!0,r.apiKeyHint.textContent="saving…";try{const n=await e.setApiKey(t);if(!n||!n.ok)throw new Error(n&&n.error||"save failed");r.apiKeyInput.value="",r.apiKeyHint.textContent=t?`saved (${n.keyMask?n.keyMask:"configured"})`:"key cleared",await ke()}catch(e){r.apiKeyHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{r.apiKeySave.disabled=!1,r.apiKeyVerify.disabled=!1}}async function be(){r.apiKeyVerify.disabled=!0,r.apiKeyHint.textContent="verifying…";try{const t=await e.verifyApiKey();if(!t||!t.ok)throw new Error(t&&t.error||"verify failed");r.apiKeyHint.textContent=t.valid?`valid (${t.plan||"active"})`:"invalid key"}catch(e){r.apiKeyHint.textContent=`verify failed: ${e&&e.message?e.message:e}`}finally{r.apiKeyVerify.disabled=!1}}function we(e){if(!e)return;r.quickLauncherEnabled.checked=Boolean(e.enabled),r.quickLauncherShortcut.value=e.shortcut||"",r.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),r.quickLauncherHint.textContent=t.join(" · ")}async function xe(){if(o){r.quickLauncherSave.disabled=!0,r.quickLauncherHint.textContent="saving…";try{we(await o.setConfig({enabled:r.quickLauncherEnabled.checked,shortcut:r.quickLauncherShortcut.value.trim()}))}catch(e){r.quickLauncherHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{r.quickLauncherSave.disabled=!1}}}function Se(e){if(!r.confirmMode||!e)return;const t=!1!==e.enabled;r.confirmMode.checked=t,r.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.",Ee(t)}function Ee(e){if(!r.autoMode)return;const t=!e;r.autoMode.setAttribute("aria-pressed",t?"true":"false"),r.autoMode.classList.toggle("is-auto",t),r.autoModeLabel&&(r.autoModeLabel.textContent=t?"auto mode":"ask before tools"),r.autoModeHint&&(r.autoModeHint.textContent=t?"on — tools run without asking. Click to require approval.":"off — click for auto mode, or use Settings → Tool approvals.")}async function $e(t){if(r.confirmMode){r.confirmMode.disabled=!0,r.autoMode&&(r.autoMode.disabled=!0);try{Se(await e.setConfirmMode(t))}catch(e){r.confirmMode.checked=!t,r.confirmModeHint.textContent=`save failed: ${e&&e.message?e.message:e}`,Ee(r.confirmMode.checked)}finally{r.confirmMode.disabled=!1,r.autoMode&&(r.autoMode.disabled=!1)}}}let qe="",Le=!1;function Ae(e){qe=e||"",r.queueHint&&(r.queueHint.textContent=qe)}function Me(e){const t=document.createElement("li");t.className="session-row",t.dataset.status=e.status;const n=document.createElement("span");n.className="session-title";const o=String(e.task||"").replace(/\s+/g," ").trim();var s;n.textContent=`#${e.id} ${s=e.status,"done"===s?"✓":"error"===s?"✗":"running"===s?"…":"·"} ${o.length>90?`${o.slice(0,89)}…`:o}`,t.appendChild(n);const a=document.createElement("span");if(a.className="session-meta",a.textContent=function(e){const t=[e.status];if(e.model&&t.push(e.model),t.push(!1===e.singlePass||!0===e.autonomous?"fan-out":"single pass"),"error"===e.status)t.push(e.error?String(e.error):"failed — no reason recorded");else if("done"===e.status){const n=(e.result&&e.result.output?String(e.result.output):"").replace(/\s+/g," ").trim();n&&t.push(n.length>140?`${n.slice(0,139)}…`:n);const o=e.result&&Array.isArray(e.result.files)?e.result.files:[];o.length&&t.push(`touched ${o.length} file${1===o.length?"":"s"}`)}else"running"===e.status?t.push(e.startedAt?`started ${nt(e.startedAt)}`:"working"):(e.attempts&&t.push(`${e.attempts} attempt${1===e.attempts?"":"s"}`),e.created&&t.push(nt(e.created)));return t.join(" · ")}(e),t.appendChild(a),"done"===e.status||"error"===e.status){const n=document.createElement("button");n.type="button",n.className="ghost-btn",n.textContent="Retry",n.title="Put this task back in line and run it again",n.addEventListener("click",(()=>Re("retry",e.id))),t.appendChild(n)}if("running"!==e.status){const n=document.createElement("button");n.type="button",n.className="ghost-btn",n.textContent="Remove",n.addEventListener("click",(()=>Re("remove",e.id))),t.appendChild(n)}return t}function Ne(e){if(!r.queueList||!e||"object"!=typeof e)return;Le=Boolean(e.draining),r.queueCwd&&!r.queueCwd.value&&(r.queueCwd.value=e.defaultCwd||""),r.queueEnqueue&&(r.queueEnqueue.disabled=Le),r.queueDrain&&(r.queueDrain.disabled=Le),r.queueProceed&&(r.queueProceed.disabled=Le),r.queueStop&&(r.queueStop.hidden=!Le);const t=Array.isArray(e.items)?e.items:[];if(r.queueList.innerHTML="",t.length)for(const e of t)r.queueList.appendChild(Me(e));else{const e=document.createElement("li");e.className="empty",e.textContent="queue is empty",r.queueList.appendChild(e)}const n=[];e.running?n.push(`running #${e.running.id}`):Le&&n.push("draining…"),n.push(`${e.pending||0} pending`),e.defaultModel&&n.push(`Aegis Cloud · ${e.defaultModel}`),Le&&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(r.queueFanout&&(r.queueFanout.disabled=!o,o||(r.queueFanout.checked=!1)),r.queueBoundary&&(r.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||"":""),r.queueUpgrade&&(r.queueUpgrade.innerHTML="",n&&!o)){const e="balance"===t.wall;H(r.queueUpgrade,t.upgradeUrl,t.campaign,e?"Top up your balance ↗":"See what Pro covers ↗")}}(e),r.queueHint&&(r.queueHint.textContent=[qe,n.join(" · ")].filter(Boolean).join(" · "))}async function He(){if(!s||!r.queueList)return null;try{const e=await s.list();return Ne(e),e}catch(e){return Ae(`queue list failed: ${e&&e.message?e.message:e}`),null}}async function Ie(){if(!s||!r.queueTask)return;const e=r.queueTask.value.trim();if(e){r.queueEnqueue&&(r.queueEnqueue.disabled=!0),Ae("queueing…");try{const t=await s.enqueue({task:e,cwd:r.queueCwd?r.queueCwd.value.trim():"",class:r.queueClassSelect?r.queueClassSelect.value:void 0,model:on(),commit:!!r.queueCommit&&r.queueCommit.checked});t&&t.ok?(r.queueTask.value="",Ae(`queued #${t.item.id}`)):Ae(t&&t.reason||"enqueue failed"),Ne(t)}catch(e){Ae(`enqueue failed: ${e&&e.message?e.message:e}`)}finally{r.queueEnqueue&&(r.queueEnqueue.disabled=Le)}}else Ae("type a task first")}async function Be(e){if(s){Le=!0,Ae("one"===e?"running one task…":"draining the queue…"),r.queueDrain&&(r.queueDrain.disabled=!0),r.queueProceed&&(r.queueProceed.disabled=!0),r.queueEnqueue&&(r.queueEnqueue.disabled=!0),r.queueStop&&(r.queueStop.hidden=!1);try{const t=await("one"===e?s.drain():s.proceed());Ae(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)),Ne(t)}catch(e){Le=!1,r.queueDrain&&(r.queueDrain.disabled=!1),r.queueProceed&&(r.queueProceed.disabled=!1),r.queueEnqueue&&(r.queueEnqueue.disabled=!1),r.queueStop&&(r.queueStop.hidden=!0),Ae(`drain failed: ${e&&e.message?e.message:e}`)}}}async function Te(){if(s){r.queueStop&&(r.queueStop.disabled=!0),Ae("stopping…");try{const e=await s.stop(),t=e&&e.cancelled&&e.cancelled.ok;qe=t?"stopped the running task":"stop requested",Ne(e)}catch(e){Ae(`stop failed: ${e&&e.message?e.message:e}`)}finally{r.queueStop&&(r.queueStop.disabled=!1)}}}async function Re(e,t){if(s){Ae(`${e} #${t}…`);try{const n=await s[e](t);n&&!1===n.ok?Ae(n.reason||`${e} failed`):Ae(`${"retry"===e?"re-queued":"removed"} #${t}`),Ne(n)}catch(t){Ae(`${e} failed: ${t&&t.message?t.message:t}`)}}}function Ue(e){e&&"object"==typeof e&&e.drain&&function(e){if(!r.queueAuto||!e||"object"!=typeof e)return;const t=!0===e.enabled;if(r.queueAuto.checked=t,r.queueAutoInterval){r.queueAutoInterval.disabled=!t;const n=Number(e.intervalMs);Number.isFinite(n)&&(r.queueAutoInterval.value=String(n))}if(r.queueAutoLabel&&(r.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"),!r.queueAutoHint)return;if(!t)return void(r.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"),r.queueAutoHint.textContent=n.join(" · ")}(e.drain)}async function Oe(e){if(!a||"function"!=typeof a.setDrain)return;const t={enabled:Boolean(e)};r.queueAutoInterval&&r.queueAutoInterval.value&&(t.intervalMs=Number(r.queueAutoInterval.value));try{const e=await a.setDrain(t);e&&!1===e.ok&&r.queueAutoHint&&(r.queueAutoHint.textContent=e.error||"could not save that"),Ue(e)}catch(e){r.queueAutoHint&&(r.queueAutoHint.textContent=`could not save that: ${e&&e.message?e.message:e}`)}}function De(e){if(!e||"object"!=typeof e)return;const t=null==e.taskId?"":`#${e.taskId} `;if("start"===e.type)Ae(`${t}running${e.model?` on ${e.model}`:""}…`);else if("tool"===e.type&&e.tool)Ae(`${t}${zt(e.tool)}`);else if("finish"===e.type)Ae(`${t}${e.ok?"done":"failed"} — refreshing`),He();else if("recovered"===e.type){const t=Array.isArray(e.ids)?e.ids:[];Ae(`recovered ${t.length} stalled task${1===t.length?"":"s"}`)}else"locked"===e.type?Ae("another drain is already running"):"queued"===e.type&&Ae(`queued phase ${e.phase}`)}function Fe(e){const t=e&&e.prompt,o=e&&e.response;if(!t||!o)return;T||(T=en());const s=T,a=e&&e.model||"",i=e&&e.class||"",r=i||a?[i?i.toUpperCase():"",a].filter(Boolean).join(" · "):void 0;Ft("user",t),Ft("assistant",o,r,s),R.push({role:"user",content:t}),R.push({role:"assistant",content:o}),n.append(s,{role:"user",content:t}).catch((()=>{})),n.append(s,{role:"assistant",content:o}).catch((()=>{}))}const Pe=10,_e=6,Ke=50,je={entries:[],query:"",source:"",role:"",error:"",upgrade:null,loading:!1};function Ge(){if(We())return!0;if(Qe())return!0;if(Ve&&"function"==typeof Ve.isOpen)try{return!!Ve.isOpen()}catch(e){return!1}return!1}function We(){return!!r.memoryOverlay&&!r.memoryOverlay.hidden}function Qe(){return!!r.keysOverlay&&!r.keysOverlay.hidden}let Ve=null,Ye=null,ze=!1;async function Je(e){if(!Ye)return;if(ze&&!e)return;r.ptHint&&(r.ptHint.textContent="listing providers…");const n=await async function(){let e=[];try{e=await t.listClasses()||[]}catch(e){return r.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}();ze=!0,Ye.set(n)}function Xe(e){e&&e.class&&Array.from(r.classSelect.options).some((t=>t.value===e.class))&&(r.classSelect.value=e.class,localStorage.setItem(l,e.class),se(e.class),nn(e.class).then((()=>{e.model&&Array.from(r.modelSelect.options).some((t=>t.value===e.model))&&(r.modelSelect.value=e.model,r.modelSelect.dispatchEvent(new Event("change")))})))}const Ze="aegis.companion.dismissed";function et(){const e={keyConfigured:null===le?void 0:le};return Array.isArray(je.entries)&&je.entries.length&&(e.memoryCount=je.entries.length),ue&&"downloaded"===ue.status&&ue.version&&(e.updatePending=String(ue.version)),U.length&&r.modelSelect&&r.modelSelect.options.length>1&&(e.modelCount=r.modelSelect.options.length),e}function tt(){if(!window.aegisCompanion||!r.companionCard||!r.companionText)return;const e=new Date;let t=null;try{t=JSON.parse(localStorage.getItem(Ze)||"null")}catch{t=null}if(window.aegisCompanion.dismissedToday(t,e))return void(r.companionCard.hidden=!0);const n=window.aegisCompanion.pickMessage(et(),e);n&&n.text?(r.companionText.textContent=n.text,r.companionCard.dataset.kind=n.kind,r.companionCard.dataset.messageId=n.id,r.companionCard.hidden=!1):r.companionCard.hidden=!0}function nt(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 ot(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(ot):[];return o&&o.upgrade?{entries:a,error:"",upgrade:o.upgrade}:{entries:a,error:"",upgrade:null}}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||E("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}}}function at(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 it(e,t,n,o,s){if(!e)return;const a=null!=t.used?at(t.used):"?",i=null!=t.limit?at(t.limit):"?";e.textContent=`${n||"sync limit reached"} — ${a} of ${i} tokens synced. Nothing was lost. ${b} `,H(e,t.url,s||"memory_quota",o||"See what Pro covers →")}function rt(e,t){it(r.memoryHint,e,t)}function lt(e,t,n,o=!1){r.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)>=_e))}(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;r.tabMemory&&(r.tabMemory.hidden=!(t||n||o)),r.memoryBox&&(r.memoryBox.hidden=!n),r.memoryQuiet&&(r.memoryQuiet.hidden=!o),r.tabMemory&&r.tabMemory.hidden&&"memory"===hn&&fn("sessions")}({hasAny:s.length>0,hasBox:a,quietNotice:i}),a){if(n){const e=document.createElement("li");return e.className="empty mem-side-upgrade",r.memoryResults.appendChild(e),void H(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 r.memoryResults.appendChild(e)}if(!s.length){const e=document.createElement("li");return e.className="empty",e.textContent="no memory entries",void r.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),r.memoryResults.appendChild(t)}}}async function ct(e){r.memoryHint.textContent="searching…";const t=await st(e,Pe);lt(t.entries,t.error,t.upgrade,""===e),t.upgrade?rt(t.upgrade,"cloud memory needs an active plan"):r.memoryHint.textContent=t.error||""}function dt(e,t){const n=document.createElement("span");return n.className="mem-chip"+(t?` ${t}`:""),n.textContent=e,n}function ut(e){const t=document.createElement("li");t.className="mem-card";const n=document.createElement("div");n.className="mem-card-head",n.appendChild(dt(e.source,"src")),e.role&&n.appendChild(dt(e.role,"role")),null!=e.importance&&n.appendChild(dt(`imp ${e.importance}`,"imp")),e.sentiment&&n.appendChild(dt(e.sentiment,"sent")),e.summary&&n.appendChild(dt("summary","flag"));const o=document.createElement("span");o.className="mem-card-meta";const s=[],a=nt(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(dt(t,"pill"));t.appendChild(e)}return i.addEventListener("click",(()=>{window.getSelection&&String(window.getSelection())||t.classList.toggle("expanded")})),t}function mt(e){const t=new Map;for(const n of je.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 pt(){if(!We())return;const e=je.entries.length;if(r.memoryList.innerHTML="",function(){if(r.memoryChips.innerHTML="",je.upgrade||je.error)return;const e=[["source","source",mt("source")],["role","role",mt("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"+(je[t]===n?" on":""),o.textContent=`${n} ${s}`,o.addEventListener("click",(()=>{je[t]=je[t]===n?"":n,pt()})),e.appendChild(o)}r.memoryChips.appendChild(e)}}(),je.loading)return void(r.memoryCount.textContent="loading…");if(je.upgrade){r.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!=je.upgrade.used?at(je.upgrade.used):"?",s=null!=je.upgrade.limit?at(je.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. `+b,e.appendChild(t),e.appendChild(n),r.memoryList.appendChild(e),void H(e,je.upgrade.url,"memory_quota","Open subscribe page ↗")}if(je.error){r.memoryCount.textContent="";const e=document.createElement("li");return e.className="mem-empty",e.textContent=je.error,void r.memoryList.appendChild(e)}if(!e){r.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 r.memoryList.appendChild(e)}const t=je.query.trim().toLowerCase(),n=je.entries.filter((e=>(!je.source||e.source===je.source)&&(!je.role||e.role===je.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(je.entries.map((e=>e.source))).size;if(r.memoryCount.textContent=`${n.length} of ${e} shown · ${o} source${1===o?"":"s"}`+(e>=Ke?` · newest ${Ke}`:""),!n.length){const e=document.createElement("li");return e.className="mem-empty",e.textContent="Nothing matches those filters.",void r.memoryList.appendChild(e)}for(const e of n)r.memoryList.appendChild(ut(e))}async function yt(e){je.loading=!0,je.error="",je.upgrade=null,pt();const t=await st(e,Ke);je.entries=t.entries,je.error=t.error,je.upgrade=t.upgrade,je.loading=!1,pt()}function ht(){r.memoryOverlay&&(r.memoryOverlay.hidden=!1,document.body.classList.add("memory-open"),r.memoryOverlayQuery.value=r.memoryQuery?r.memoryQuery.value.trim():"",je.query=r.memoryOverlayQuery.value,je.source="",je.role="",pt(),yt(je.query),r.memoryOverlayQuery&&r.memoryOverlayQuery.focus())}function ft(){r.memoryOverlay&&(r.memoryOverlay.hidden=!0,document.body.classList.remove("memory-open"),r.memoryOpen&&r.memoryOpen.focus())}async function gt(){if(e.memoryImport){r.memoryImportBtn.disabled=!0,r.memoryHint.textContent="scanning for other AI tool memory…";try{const t=await e.memoryImport({confirm:!1});if(!t||!t.totals||!t.totals.entries)return void(r.memoryHint.textContent=t&&t.summary?t.summary:"nothing found.");const n=(t.sources||[]).filter((e=>e.present&&e.count>0)).map((e=>`${e.label}: ${e.count}`)).join(" · ");r.memoryHint.textContent=`importing ${t.totals.entries} entries — ${n}`;const o=await e.memoryImport({confirm:!0,limit:1e3});if(o&&o.upgrade)return rt(o.upgrade,`import stopped after ${o.saved||0} entries`),void await kt();const s=o&&o.queued?` (${o.queued} queued offline)`:"";r.memoryHint.textContent=o&&o.ok?`imported ${o.saved} entries${s}.`:`import stopped: ${o&&o.reason||"unknown error"}`,await kt()}catch(e){r.memoryHint.textContent=`import failed: ${e&&e.message?e.message:e}`}finally{r.memoryImportBtn.disabled=!1}}}async function vt(){const t=We()&&r.memoryOverlayEntry?r.memoryOverlayEntry:r.memoryEntry;if(!t)return;const n=t.value.trim();if(n){r.memorySaveBtn.disabled=!0,r.memoryOverlaySave&&(r.memoryOverlaySave.disabled=!0),r.memoryHint.textContent="saving…";try{const o=await e.memorySave({text:n,source:"aegis-desktop"});if(o&&o.upgrade)return rt(o.upgrade,"free plan limit reached"),void await kt();t.value="",r.memoryHint.textContent=o&&o.queued?"saved offline — syncs when AEGIS is reachable.":"saved.",await kt()}catch(e){r.memoryHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{r.memorySaveBtn.disabled=!1,r.memoryOverlaySave&&(r.memoryOverlaySave.disabled=!1)}}}async function kt(){const e=r.memoryQuery?r.memoryQuery.value.trim():"";await ct(e),We()&&await yt(je.query)}function Ct(){const e=et();return void 0===e.keyConfigured&&delete e.keyConfigured,e}function bt(){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(Ct(),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 wt="aegis.welcomeAiLine",xt=120,St=200;function Et(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 $t(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 qt(){const e=document.getElementById("welcome-template");if(!e)return;r.messages.innerHTML="",r.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?"}(),bt(),async function(){const e=document.getElementById("welcome-personal");if(!e)return;if(void 0===t||!t||"function"!=typeof t.chat)return;if(!(!0===le||r.modelSelect&&r.modelSelect.options&&r.modelSelect.options.length>1))return;const n=new Date,o=function(e){let t=null;try{t=JSON.parse(localStorage.getItem(wt)||"null")}catch{t=null}return t&&"string"==typeof t.text&&t.text?t.day!==Et(e)?null:t.text:null}(n);if(o)return e.textContent=o,e.dataset.kind="ai",void(e.hidden=!1);const s=Ct(),a=r.classSelect&&r.classSelect.value?r.classSelect.value:"aegis",i=r.modelSelect&&r.modelSelect.value?r.modelSelect.value:"",l={class:a,prompt:$t(s),maxTokens:xt,tools:!1,singlePass:!0,effort:"low",bestEffort:!0};i&&(l.model=i);let c=null;try{c=await t.chat(l)}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>St){const e=n.slice(0,St),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(wt,JSON.stringify({day:Et(n),text:u}))}catch{}}}();const n=document.getElementById("welcome-byok");n&&n.addEventListener("click",Nt);const o=document.getElementById("welcome-cloud");o&&o.addEventListener("click",Ht);const s=document.getElementById("welcome-dismiss");s&&s.addEventListener("click",Bt),Lt()}function Lt(){const e=document.getElementById("welcome-connect");if(!e)return;let t=!1;try{t="on"===localStorage.getItem(y)}catch{}const n=!0!==le,o=!0!==ce;e.hidden=t||!n&&!o,At("welcome-cloud",!n),At("welcome-cloud-note",!n),At("welcome-byok",!o),At("welcome-byok-note",!o)}function At(e,t){const n=document.getElementById(e);n&&(n.hidden=t)}function Mt(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 Nt(){if(It("byok"),Array.from(r.classSelect.options).some((e=>"byok"===e.value))&&"byok"!==r.classSelect.value&&(r.classSelect.value="byok",r.classSelect.dispatchEvent(new Event("change"))),Mt(r.settingsList),!1===le&&r.apiKeyHint&&(r.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===le&&r.apiKeyInput)return r.apiKeyInput.focus(),void Mt(r.apiKeyInput);const e=r.settingsList?r.settingsList.querySelector('.setting-row input[type="password"]'):null;e&&e.focus()}function Ht(){It("cloud"),Mt(r.apiKeyInput),r.apiKeyInput&&r.apiKeyInput.focus()}function It(e){const t=r.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: ${b} Paste your AEGIS key, then Save. Free key at `));const n=document.createElement("a");n.href=C,n.target="_blank",n.rel="noreferrer noopener",n.textContent="aegiscloud.org",t.appendChild(n),t.appendChild(document.createTextNode("."))}function Bt(){try{localStorage.setItem(y,"on")}catch{}const e=document.getElementById("welcome-connect");e&&(e.hidden=!0)}const Tt="aegis.keysPopupDismissed";function Rt(){const e=!0===le,t=!0===ce;r.keysAegisState&&(r.keysAegisState.textContent=e?"set":"not set"),r.keysByokState&&(r.keysByokState.textContent=t?"set":"not set"),r.keysRowAegis&&r.keysRowAegis.classList.toggle("set",e),r.keysRowByok&&r.keysRowByok.classList.toggle("set",t),r.keysCount&&(r.keysCount.textContent=(e?1:0)+(t?1:0)+" / 2"),r.keysAccount&&(r.keysAccount.hidden=!ye,r.keysAccount.textContent=ye?`The AEGIS account key could not be set up: ${ye}.`:""),r.keysAccountRetry&&(r.keysAccountRetry.hidden=!ye),r.keysHint&&(r.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 Desktop and the aegiscode CLI run.`)}function Ut(){r.keysOverlay&&(r.keysOverlay.hidden=!0,document.body.classList.remove("keys-open"))}function Ot(){try{localStorage.setItem(Tt,"on")}catch{}Ut()}function Dt(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 Ft(e,t,n,o,s){!function(){const e=document.getElementById("chat-welcome");e&&e.remove()}();const a=document.createElement("div");a.className=`msg ${e}`;const i=document.createElement("div");if(i.className="body",Dt(i,e,t),Array.isArray(s)&&s.length){const e=document.createElement("div");e.className="tool-activity";for(const t of s){const n=document.createElement("div");n.textContent=zt(t),e.appendChild(n)}a.appendChild(e)}if(a.appendChild(i),n){const e=document.createElement("div");e.className="meta",e.textContent=n,a.appendChild(e)}if("assistant"===e&&o){const e=document.createElement("button");e.type="button",e.className="copy-btn",e.textContent="copy",e.addEventListener("click",(()=>async function(e,t){try{await navigator.clipboard.writeText(e),t&&(t.textContent="copied!")}catch(e){t&&(t.textContent="copy failed")}finally{t&&setTimeout((()=>{t.textContent="copy"}),1500)}}(t,e))),a.appendChild(e)}return r.messages.appendChild(a),X(),a}function Pt(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 l=document.createElement("span");l.className="flow-state",l.textContent="queued",a.appendChild(i),a.appendChild(r),a.appendChild(l);const c=document.createElement("div");c.className="flow-body",c.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),l.textContent="stopped",s.classList.remove("pending"),s.classList.add("stopped"),u.remove()})),s.appendChild(a),s.appendChild(c),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${++G}`;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 l=t=>{if(t&&t.approval)return e.classList.contains("pending")&&(e.classList.remove("pending"),a.textContent="needs approval"),void Zt(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 Yt(t.tool):void Jt(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 c=await t.chat({class:n.cls,system:`${K}\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},l),d=c&&c.choices&&c.choices[0]||{};if(c&&c.bestEffortFailed)throw new Error(c.message||"the provider did not answer");if(c&&c.aborted){const e=new Error(c.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)";Dt(s,"assistant",u),e.classList.remove("pending"),e.classList.add("done"),a.textContent="done";const m=[n.path.title];c&&c.model?m.push(c.model):n.model&&m.push(n.model);const p=turnAccounting(c&&c.usage,n.model,{costUsd:c&&"number"==typeof c.costUsd?c.costUsd:void 0}),y=displayTokens(p);null!=y&&m.push(`${y} tokens`),null!=p.cost&&m.push(fmtCost(p.cost,p.real));const h=F(n.parentSessionId,c&&c.usage,{model:n.model,costUsd:c&&"number"==typeof c.costUsd?c.costUsd:void 0,calls:c&&c.calls,turns:0,prompt:`Original request:\n${n.prompt}\n\n${n.path.hint}`,reply:u}),f=fmtRoll(h);f&&m.push(`session: ${f}`),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 _t(){return I||(I=Ft("assistant",""),I.classList.remove("pending"),I)}function Kt(e,{cancellable:t}={}){if(r.send.disabled=e,r.prompt.disabled=e,e){I=Ft("assistant",""),I.classList.add("pending");const e=document.createElement("span");e.className="typing-dots";for(let t=0;t<3;t++)e.appendChild(document.createElement("span"));I.querySelector(".body").appendChild(e);const n=document.createElement("span");if(n.className="typing-tokens",n.hidden=!0,I.appendChild(n),t){const e=document.createElement("button");e.type="button",e.className="cancel-btn",e.textContent="cancel",e.addEventListener("click",(()=>ee())),I.appendChild(e)}}else I&&(I.remove(),I=null)}const jt=72,Gt=new Set(["editFile","writeFile","Edit","Write","MultiEdit"]),Wt=new Set(["writeFile","Write"]),Qt=new Map,Vt=new Map;function Yt(e){if(!e||!Gt.has(e.name)||null==e.id)return;if(Wt.has(e.name)&&e.args){const t=e.args.content;if(t&&"string"==typeof t){const n=e.args.file_path||e.args.path;if(n){const o=window.extractPreview(n,t);if(o)return void Vt.set(e.id,o)}}}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&&Qt.set(e.id,n)}function zt(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>jt?`${i.slice(0,jt-1)}…`:i;return`→ ${t}${r?` ${r}`:""} ${o}`}function Jt(e,t,n,o){if(!e)return;let s=e.querySelector(`.${n}`);if(!s){s=document.createElement("div"),s.className=n;const t=o?e.querySelector(o):null;t?e.insertBefore(s,t):e.appendChild(s)}const a=t&&null!=t.id?Vt.get(t.id):null;if(a){Vt.delete(t.id);const e=window.renderFilePreviewCard(a,(e=>{console.log("View full file:",e.file)}));if(e)return s.appendChild(e),s}const i=t&&null!=t.id?Qt.get(t.id):null;if(i){Qt.delete(t.id);const e=renderDiffBlock(i,document);if(e)return s.appendChild(e),s}const r=document.createElement("div");return r.textContent=zt(t),s.appendChild(r),s}function Xt(e){return e.startsWith("@@")?"diff-hunk":e.startsWith("+++")||e.startsWith("---")?"diff-file":e.startsWith("+")?"diff-add":e.startsWith("-")?"diff-del":"diff-ctx"}function Zt(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=Xt(t),n.textContent=t,e.appendChild(n)}s.appendChild(e)}const r=document.createElement("div");r.className="approval-actions";const l=(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":"Allowed once",s.appendChild(o),t.respondApproval(n.id,e)})(a))),i};r.appendChild(l("Allow once","allow","once")),r.appendChild(l("Allow for this session","allow-session","session")),r.appendChild(l("Deny","deny","deny")),s.appendChild(r);let c=e.querySelector(".approval-slot");if(!c){c=document.createElement("div"),c.className="approval-slot";const t=o?e.querySelector(o):null;t?e.insertBefore(c,t):e.appendChild(c)}return c.appendChild(s),s}function en(){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 tn(){try{U=await t.listClasses()||[]}catch(e){U=[],r.modelHint.textContent=`listClasses failed: ${e&&e.message?e.message:e}`}r.classSelect.innerHTML="";for(const e of U){const t=document.createElement("option");t.value=e.class,t.textContent=e.configured?e.label:`${e.label} (not configured)`,r.classSelect.appendChild(t)}const e=localStorage.getItem(l);e&&U.some((t=>t.class===e))&&(r.classSelect.value=e),await nn(r.classSelect.value)}async function nn(e){if(r.autonomousToggleWrap&&(r.autonomousToggleWrap.hidden=e!==h),ne(),se(e),r.modelSelect.hidden=!1,r.modelSelect.disabled=!1,r.modelFree.hidden=!0,r.modelFree.value="",r.modelHint.textContent="",r.modelSelect.innerHTML="",O=new Map,"aegis"===e){const e=document.createElement("option");e.value="",e.textContent="server default (auto)",r.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),l=Boolean(n&&n.providersFailed),c=Array.isArray(n&&n.unmatchedProviders)?n.unmatchedProviders:[];r.modelFree.hidden=!("local"===e&&(a||!i));for(const e of o){O.set(e.id,e);const t=document.createElement("option");t.value=e.id,t.textContent=e.label||e.id,r.modelSelect.appendChild(t)}let d;if(ae(),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&&l)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&&!l&&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(O.get(oe()));if(s){r.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=C,e.target="_blank",e.rel="noreferrer noopener",e.textContent="free key at aegiscloud.org",r.modelHint.appendChild(e),void r.modelHint.appendChild(document.createTextNode("), then Save."))}r.modelHint.textContent=u<FLAT_CEILING?`${d} · max output: ${u.toLocaleString()}`:d}catch(e){O=new Map,r.modelHint.textContent=`listModels failed: ${e&&e.message?e.message:e}`,ae()}}function on(){if(r.queueModelInput&&!r.queueModelInput.hidden){const e=r.queueModelInput.value.trim();if(e)return e}return r.queueModelSelect?r.queueModelSelect.value:""}async function sn(e){if(r.queueModelSelect){if(function(e){const t=r.queueFanout&&r.queueFanout.closest("label");t&&(t.hidden="aegis"!==e)}(e),r.queueModelSelect.hidden=!1,r.queueModelSelect.disabled=!1,r.queueModelInput&&(r.queueModelInput.hidden=!0,r.queueModelInput.value=""),r.queueModelHint&&(r.queueModelHint.textContent=""),r.queueModelSelect.innerHTML="","aegis"===e){const e=document.createElement("option");e.value="",e.textContent="server default (auto)",r.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);r.queueModelInput&&(r.queueModelInput.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,r.queueModelSelect.appendChild(t)}if(!r.queueModelHint)return;s?r.queueModelHint.textContent="Connect this class in the Model card above (API key / provider key), then Refresh.":a?r.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&&(r.queueModelHint.textContent="A provider key is required before a queued task on this model can run — add one in the Model card above."):r.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.":r.queueModelHint.textContent="That address answered but listed no models — type the model tag above."}catch(e){r.queueModelHint&&(r.queueModelHint.textContent=`listModels failed: ${e&&e.message?e.message:e}`)}}}function an({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 l=document.createElement("div");l.className="setting-status",l.textContent=n.configured?`configured (${n.keyMask})`:"no key",a.appendChild(l);const c=document.createElement("div");c.className="setting-actions";const d=document.createElement("button");d.type="button",d.className="ghost-btn",d.textContent="Save",d.addEventListener("click",(()=>o(r.value))),c.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),c.appendChild(u),a.appendChild(c),a}async function rn(e){r.settingsHint.textContent="saving…";try{const n=String(null==e?"":e).trim()||k,o=await t.settings.set(g,{baseURL:n}),s=o&&o.baseURL||n;r.settingsHint.textContent=`saved: local model server at ${s}`,await ln(),await nn(r.classSelect.value)}catch(e){r.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function ln(){r.settingsList.innerHTML="";const e=[];let n=[];try{n=await t.settings.get()||[]}catch{}Array.isArray(n)&&(n=n.filter((e=>e&&!f.has(e.provider))));{const e=n.find((e=>e&&e.provider===g))||{provider:g,baseURL:"",configured:!1,keyMask:null};r.settingsList.appendChild(function(e){const t=g,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=k,s.value=e.baseURL||"",s.addEventListener("keydown",(e=>{"Enter"===e.key&&rn(s.value)})),n.appendChild(s);const a=document.createElement("div");a.className="setting-status",a.textContent=e.baseURL?e.baseURL:`default (${k})`,n.appendChild(a);const i=document.createElement("div");i.className="setting-actions";const r=document.createElement("button");r.type="button",r.className="ghost-btn",r.textContent="Save",r.addEventListener("click",(()=>rn(s.value))),i.appendChild(r);const l=document.createElement("button");return l.type="button",l.className="ghost-btn danger",l.textContent="Reset",l.disabled=!e.baseURL,l.addEventListener("click",(()=>pn(t))),i.appendChild(l),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===v)continue;const o=`byok:${t.id}`,s=n.find((e=>e.provider===o))||{provider:o,baseURL:"",configured:!1,keyMask:null};r.settingsList.appendChild(an({provider:o,name:`BYOK: ${t.label||t.id}`,cfg:s,onSave:e=>mn(o,e),onRemove:()=>pn(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),r.settingsList.appendChild(e)}}catch{}try{await async function(e){if(!r.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 l=document.createElement("div");l.className="setting-row",l.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)}l.appendChild(e),c.setAttribute("list","user-model-providers")}l.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,l.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();r.settingsHint.textContent="adding…";try{const o=await t.userModels.add(e,n);r.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 ln(),await nn(r.classSelect.value)}catch(e){r.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 y=document.createElement("div");y.className="setting-status",y.id="user-model-discovered",y.hidden=!0,p.addEventListener("click",(async()=>{const e=c.value.trim();if(!e)return void(r.settingsHint.textContent="type a provider id first (the CLI's /byok lists them).");if("function"!=typeof t.userModels.discover)return void(r.settingsHint.textContent="this build cannot ask a provider — type the model id.");let n;r.settingsHint.textContent=`asking ${e}…`,y.hidden=!0,y.textContent="";try{n=await t.userModels.discover(e)}catch(e){return void(r.settingsHint.textContent=`${e&&e.message?e.message:e}`)}if(!n||!n.ok)return void(r.settingsHint.textContent=`${e}: ${n&&n.error||"no answer"}`);r.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],y.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()=>{r.settingsHint.textContent=`adding ${n.count}…`;try{const e=await t.userModels.addAll(n.provider,n.ids);r.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 ln(),await nn(r.classSelect.value)}catch(e){r.settingsHint.textContent=`${e&&e.message?e.message:e}`}})),y.appendChild(e)}else y.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(", ")}`,y.appendChild(e)}y.hidden=!1})),l.appendChild(u),l.appendChild(y);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)",l.appendChild(h),a.appendChild(l);const f=Object.keys(o).sort();for(const e of f)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 l=document.createElement("div");l.className="setting-status",l.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(l);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()=>{r.settingsHint.textContent="removing…";try{const o=await t.userModels.remove(e,n);r.settingsHint.textContent=o&&!1===o.removed?`${e}:${n} was not declared.`:`removed ${e}:${n}.`,await ln(),await nn(r.classSelect.value)}catch(e){r.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)}r.settingsList.appendChild(a)}(e)}catch(e){r.settingsHint.textContent=`your own models: ${e&&e.message?e.message:e}`}try{await cn()}catch(e){r.customStatus&&(r.customStatus.textContent=`custom provider: ${e&&e.message?e.message:e}`)}}async function cn(){if(!r.customBaseUrl)return;let e=null,n=[];try{const n=await t.settings.get()||[],o=(Array.isArray(n)?n:[]).find((e=>e&&e.provider===`byok:${v}`));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[v])?o[v]:[]}catch{}!function(e,t){if(!r.customBaseUrl)return;const n=e||{},o=Array.isArray(t)?t:[];if(!r.customBaseUrl.value&&n.baseURL&&(r.customBaseUrl.value=n.baseURL),r.customKey&&(r.customKey.placeholder=n.configured?`key ${n.keyMask||"••••"} (blank = keep)`:"sk-…",r.customKey.value=""),r.customRemove&&(r.customRemove.disabled=!n.configured&&!n.baseURL),!r.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"),r.customStatus.textContent=s.join(" · ")}(e,n)}async function dn(){if(!r.customBaseUrl)return;const e=String(r.customBaseUrl.value||"").trim(),n=r.customKey?String(r.customKey.value||"").trim():"",o=r.customModel?String(r.customModel.value||"").trim():"",s=e=>{r.customStatus&&(r.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:${v}`;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(v,o)}catch(e){return s(`endpoint saved, model NOT declared: ${e&&e.message?e.message:e}`),await cn(),void await nn(r.classSelect.value).catch((()=>{}))}r.customModel&&(r.customModel.value=""),s(`saved ${e} with model ${o} — pick it under provider "byok", then the model.`),await cn(),await ln(),await nn(r.classSelect.value).catch((()=>{}))}async function un(){if(!r.customBaseUrl)return;const e=e=>{r.customStatus&&(r.customStatus.textContent=e)};e("removing…");let n=0;try{const e=await t.userModels.get(),o=e&&e.map||{},s=Array.isArray(o[v])?o[v]:[];for(const e of s)await t.userModels.remove(v,e),n+=1}catch{}try{await t.settings.remove(`byok:${v}`)}catch(t){return void e(`remove failed: ${t&&t.message?t.message:t}`)}r.customBaseUrl&&(r.customBaseUrl.value=""),e(`removed the custom endpoint${n?` and ${n} declared model(s)`:""}.`),await cn(),await ln(),await nn(r.classSelect.value).catch((()=>{}))}async function mn(e,n){r.settingsHint.textContent="saving…";try{const o={};n&&(o.key=n),await t.settings.set(e,o),r.settingsHint.textContent="saved.",await ln(),await nn(r.classSelect.value)}catch(e){r.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function pn(e){r.settingsHint.textContent="removing…";try{await t.settings.remove(e),r.settingsHint.textContent="removed.",await ln(),await nn(r.classSelect.value)}catch(e){r.settingsHint.textContent=`remove failed: ${e&&e.message?e.message:e}`}}const yn=["sessions","memory"];let hn="sessions";function fn(e){const t=yn.includes(e)?e:"sessions";hn=t;for(const e of yn){const n="sessions"===e?r.paneSessions:r.paneMemory,o="sessions"===e?r.tabSessions:r.tabMemory,s=e===t;n&&(n.hidden=!s),o&&(o.setAttribute("aria-selected",s?"true":"false"),o.classList.toggle("is-active",s))}}async function gn(){r.sessionsList.innerHTML="",r.sessionsHint.textContent="";let e=[];try{const t=await n.listSessions();e=t&&t.sessions||[]}catch(e){return void(r.sessionsHint.textContent=`list failed: ${e&&e.message?e.message:e}`)}if(!e.length){const e=document.createElement("li");return e.className="empty",e.textContent="no sessions yet",void r.sessionsList.appendChild(e)}for(const t of e){const e=document.createElement("li");e.className="session-row",e.tabIndex=0;const n=document.createElement("span");n.className="session-title",n.textContent=t&&t.title||t&&t.id||"untitled",e.appendChild(n);const o=document.createElement("span");o.className="session-meta";const s=t&&Array.isArray(t.messages)&&t.messages.length||0,a=t&&t.updatedAt?new Date(t.updatedAt).toLocaleTimeString():"";o.textContent=`${s} msg${1===s?"":"s"}${a?" · "+a:""}`,e.appendChild(o),e.addEventListener("click",(()=>wn(t.id))),r.sessionsList.appendChild(e)}}function vn(e){if(!r.syncStatus)return;if(!e)return void(r.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}`),r.syncStatus.textContent=t.join(" · ")}async function kn(){try{vn(await n.status())}catch{vn(null)}}function Cn(){"function"==typeof n.auto&&n.auto().then((e=>{e&&e.upgrade&&it(r.sessionsHint,e.upgrade,"queued memory is waiting on the free-plan cap","See what Pro covers →")})).catch((()=>{}))}async function bn(){r.syncNow.disabled=!0,r.sessionsHint.textContent="syncing…";try{const e=await n.push(),t=await n.pull();e.upgrade||t.upgrade?it(r.sessionsHint,e.upgrade||t.upgrade,"queued memory is waiting on the free-plan cap","See what Pro covers →"):e.ok||t.ok?r.sessionsHint.textContent=`synced (pushed ${e.pushed||0}, pulled ${t.merged||0})`:r.sessionsHint.textContent=`sync failed: ${e.reason||t.reason||"unknown error"}`}catch(e){r.sessionsHint.textContent=`sync failed: ${e&&e.message?e.message:e}`}finally{r.syncNow.disabled=!1,await kn(),await gn()}}function wn(e){n.open(e).then((e=>{if(!e)return void(r.sessionsHint.textContent="session not found");r.messages.innerHTML="";const t=Array.isArray(e.messages)?e.messages:[];t.length||qt();for(const n of t){const t="assistant"===n.role?"assistant":"system"===n.role?"system":"user";Ft(t,n.content||n.text||"",void 0,"assistant"===t?e.id:void 0)}T=e.id,D.set(e.id,rollMessages(t)),P(e.id),R=replayHistory(t),r.sessionsHint.textContent=`opened ${e.id.slice(0,8)}…`})).catch((e=>{r.sessionsHint.textContent=`open failed: ${e&&e.message?e.message:e}`}))}function xn(t){const n=T;n?e.exportSession(n,t).then((e=>{e&&e.ok?r.sessionsHint.textContent=`exported to ${e.filePath}`:e&&e.canceled||(r.sessionsHint.textContent=`export failed: ${e&&e.reason||"unknown error"}`)})).catch((e=>{r.sessionsHint.textContent=`export failed: ${e&&e.message?e.message:e}`})):r.sessionsHint.textContent="no open session to export"}function Sn(){Q(),T&&t.clearApprovals(T).catch((()=>{})),qt(),r.sessionsHint.textContent="",I=null,B=null,Y=null,z=null,T=null,R=[],G=0,P(null)}function En(e){e&&("open"===e.action&&e.sessionId?wn(e.sessionId):"new"===e.action&&(Sn(),e.prompt&&(r.prompt.value=e.prompt,r.prompt.focus())))}async function $n(){const e=r.prompt.value.trim(),o=qn.length?qn.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||r.send.disabled)return;const s=r.classSelect.value,a=oe();r.prompt.value="";const i=(l=qn,Array.isArray(l)&&l.length?l.map((e=>`📎 ${e.name||e.path}`)).join("\n"):"");var l;const c=i?e?`${e}\n${i}`:i:e;qn=[],Ln=[],Nn();const d=++V;Y=d,z=null,Ft("user",c);const u=s===h&&te(),m=ie(),p=budgetFor(a,void 0,m),y=u&&parseInt(r.autonomousWorkers.value,10)||void 0;T||(T=en());const f=T;B=f,Ut();const g=replayHistory(R);R.push({role:"user",content:o&&!Mn()?Un(e,o):c}),Kt(!0,{cancellable:!0}),I&&P(f,{prompt:e,reply:"",reasoning:""}),X({force:!0});try{await n.append(f,{role:"user",content:c})}catch{}let v="",k="",C=0;const b=[];let w=null;const x=(S=()=>{if(!I)return;if(I.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}(I);e.textContent!==k&&(e.textContent=k)}const t=I.querySelector(".body");t&&t.textContent!==v&&(t.textContent=v);const n=v.length+k.length+4*C;liveMeterDue(w,n)&&(w=n,P(f,{prompt:e,reply:v,reasoning:k,measuredReasoningTokens:C})),X()},J?J.paint(S):S);var S;const E=e=>{if(e&&"number"==typeof e.thinkingTokens&&e.thinkingTokens>0)return C+=e.thinkingTokens,void x();if(e&&"string"==typeof e.reasoning&&e.reasoning)return k+=e.reasoning,void x();if(e&&"string"==typeof e.note&&e.note){const t=_t();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 X()}if(e&&e.approval){const t=_t();return t.classList.remove("pending"),Zt(t,e.approval,".body"),void X({force:!0})}if(e&&e.rounds){const n=_t();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,l=document.createElement("div");l.className="approval-card rounds-card",l.dataset.roundsAskId=n.id;const c=document.createElement("div");c.className="approval-title",c.textContent="Round limit reached — keep going?",l.appendChild(c);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.)`,l.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;l.classList.add("resolved");const o=document.createElement("div");o.className="approval-decision",o.textContent=e?`Continuing — ${a} more rounds`:"Stopped — the work is held",l.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)),l.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(l)}(n,e.rounds,".body"),void X({force:!0})}if(e&&e.tool){if("run"===e.tool.phase)return void Yt(e.tool);b.push(e.tool);const t=_t();return t.classList.remove("pending"),Jt(t,e.tool,"tool-activity",".body"),void X()}const n=e&&("string"==typeof e.delta?e.delta:e.content);n&&(v+=n,x())};try{const i=await t.chat({class:s,prompt:e,model:a,maxTokens:p,sessionId:f,autonomous:u,effort:m,workers:y,messages:g,attachments:o,roundsAsk:!0},E);if(i&&i.aborted){const e=new Error(i.message||"This operation was aborted");throw e.name="AbortError",e.code="ABORT_ERR",e}const l=i&&i.choices&&i.choices[0]||{},c=l.message&&l.message.content||v||"(empty response)";isPlaceholderContent(c)||R.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=U.find((t=>t.class===e));return t?t.label:e}(s)),u?d.push(`autonomous (${m}, ${y||"auto"}w)`):m&&d.push(`effort: ${m}`);const h=turnAccounting(i&&i.usage,a,{costUsd:i&&"number"==typeof i.costUsd?i.costUsd:void 0}),C=displayTokens(h);if(null!=C)d.push(`tokens: ${C}`);else{const t=estimatedBuckets(e,c,c===k?"":k);t&&t.output>0&&d.push(`~${t.output} tokens`)}const w=feeBillable(function(){const e="undefined"!=typeof state?state:null;return e&&e.entitlement?e.entitlement:null}());null!=h.cost&&w&&d.push(fmtCost(h.cost,h.real)),"byok"===s&&null!=h.cost&&w&&d.push("your provider bill (est.) + AEGIS handling fee");const x=F(f,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:!w});S&&d.push(`session: ${S}`),Ft("assistant",c,d.join(" · ")||void 0,f,b);try{await n.append(f,{role:"assistant",content:c,..._(i&&i.usage,a,h,{prompt:e,reply:c,reasoning:c===k?"":k,calls:i&&i.calls})}),await n.save({id:f,title:e.slice(0,60)}),"function"==typeof n.nameSession&&n.nameSession({sessionId:f,prompt:e,class:s,model:a}).then((e=>{e&&gn().catch((()=>{}))})).catch((()=>{}))}catch{}Cn(),function(){const e=r.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",(()=>{Pt(j[G%j.length],a,e)})),a.appendChild(i),t.appendChild(n),t.appendChild(a),r.messages.appendChild(t);for(const t of j.slice(0,2))Pt(t,a,e)}({prompt:e,cls:s,model:a,maxTokens:p,parentSessionId:f})}catch(t){if(isCancellation(t,{userStopped:z===d})){const t=salvageTurn({streamedText:v,reasoningText:k}),o=t.text,s=t.reasoning,i=replayableContent(t.kind,o);R.push({role:"assistant",content:i});const r=turnAccounting(void 0,a,{}),l=F(f,void 0,{model:a,prompt:e,reply:o,reasoning:s}),c=["stopped by you"];"reasoning-only"===t.kind&&c.push("reasoning only");const d=displayTokens(r);if(null!=d)c.push(`tokens: ${d}`);else{const t=estimatedBuckets(e,o,s);t&&t.output>0&&c.push(`~${t.output} tokens`)}const u=fmtRoll(l);u&&c.push(`session: ${u}`),Ft("assistant",o,c.join(" · "),f,b);try{await n.append(f,{role:"assistant",content:i,..._(void 0,a,r,{prompt:e,reply:o,reasoning:s})})}catch{}Cn()}else Ft("assistant",`Error: ${t&&t.message?t.message:t}`,"request failed")}finally{Kt(!1),Y===d&&(Y=null,B=null),gn()}}let qn=[],Ln=[],An=0;function Mn(){return r.classSelect&&"pro"===r.classSelect.value}function Nn(){const e=r.attachRow,t=r.attachNote;if(!e)return;e.textContent="";const n=qn.length+Ln.length;if(e.hidden=0===n,t&&(t.hidden=!0,t.textContent=""),n){for(const t of qn){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} · ${In(t.size)}${t.truncated?" (truncated)":""}`,n.appendChild(s),n.appendChild(Hn((()=>{qn=qn.filter((e=>e!==t)),Nn()}))),e.appendChild(n)}for(const t of Ln){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(Hn((()=>{Ln=Ln.filter((e=>e!==t)),Nn()}))),e.appendChild(n)}if(t&&Mn()){const e=qn.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 Hn(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 In(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 Bn(t){const n=(t||"").split(/[\\/]/).pop()||t;if(qn.length>=8)return Ln.push({path:t,name:n,reason:"at most 8 files per message"}),void Nn();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 Ln.push({path:t,name:n,reason:o&&o.reason||"not attached"}),void Nn();qn.some((e=>e.path===o.attachment.path))||(qn.push(o.attachment),Nn())}const Tn=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Rn(e){if(e&&"string"==typeof e.mime&&e.mime)return e.mime;const t=e&&"string"==typeof e.dataUrl?e.dataUrl:"",n=/^data:([^;,]+)[;,]/.exec(t);return n?n[1].toLowerCase():""}function Un(e,t){const n=[],o="string"==typeof e?e:"";o.trim()&&n.push({type:"text",text:o});for(const e of t||[]){const t=Rn(e);"image"===e.kind&&e.dataUrl&&Tn.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}async function On(){try{de(await e.status())}catch{de(null)}"on"===localStorage.getItem(d)&&(r.autonomousToggle.checked=!0),r.autonomousToggle.addEventListener("change",(()=>{localStorage.setItem(d,r.autonomousToggle.checked?"on":"off"),ne()}));const n=localStorage.getItem(u)||localStorage.getItem("aegis.autonomousEffort"),i=Array.from(r.effortSelect.options).some((e=>e.value===n));n&&i?r.effortSelect.value=n:n&&localStorage.setItem(u,r.effortSelect.value),r.effortSelect.addEventListener("change",(()=>{localStorage.setItem(u,r.effortSelect.value),se(r.classSelect.value)}));const y=localStorage.getItem(m);y&&(r.autonomousWorkers.value=y),r.autonomousWorkers.addEventListener("change",(()=>{localStorage.setItem(m,r.autonomousWorkers.value)})),ne();const h=localStorage.getItem(p);r.exploreToggle.checked="on"===h,r.exploreToggle.addEventListener("change",(()=>{localStorage.setItem(p,r.exploreToggle.checked?"on":"off"),r.exploreToggle.checked||Q()})),r.classSelect.addEventListener("change",(()=>{localStorage.setItem(l,r.classSelect.value),se(r.classSelect.value),nn(r.classSelect.value)})),r.modelSelect.addEventListener("change",(()=>{const e=O.get(r.modelSelect.value),t=maxTokensCeiling(e),n=r.modelHint.textContent.replace(/ · max output: [\d,]+$/,"");r.modelHint.textContent=t<FLAT_CEILING?`${n} · max output: ${t.toLocaleString()}`:n,se(r.classSelect.value),"byok"===r.classSelect.value&&e&&e.provider&&!1===e.configured&&function(e){if(!r.settingsList||!e)return;const t=r.settingsList.querySelector(`.setting-row[data-provider="byok:${e}"] input[type="password"]`);if(Mt(r.settingsList),t&&t.focus(),r.modelHint){const t=r.modelHint.textContent.replace(/ — no .* key saved; add it below\.$/,"");r.modelHint.textContent=`${t} — no ${e} key saved; add it below.`}}(e.provider)})),r.modelFree.addEventListener("input",(()=>{se(r.classSelect.value)})),r.newChat.addEventListener("click",Sn),e.onMenuNewChat&&e.onMenuNewChat(Sn),e.onMenuSearch&&e.onMenuSearch(ht),e.onMenuFingerprint&&e.onMenuFingerprint((()=>{Ve&&"function"==typeof Ve.open&&Ve.open()})),e.onMenuGoogleDrive&&e.onMenuGoogleDrive((()=>{Ve&&"function"==typeof Ve.open&&Ve.open({focus:"drive"})})),e.onMenuExportMarkdown&&e.onMenuExportMarkdown((()=>xn("markdown"))),e.onMenuExportJson&&e.onMenuExportJson((()=>xn("json"))),e.onDeepLink&&e.onDeepLink(En),e.onQuickLauncherPush&&e.onQuickLauncherPush(Fe),r.sessionsRefresh.addEventListener("click",gn),r.syncNow.addEventListener("click",bn),r.sessionsExport.addEventListener("click",(()=>xn("markdown"))),r.apiKeySave.addEventListener("click",Ce),r.apiKeyVerify.addEventListener("click",be),r.apiKeyInput.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),Ce())})),r.customSave&&r.customSave.addEventListener("click",dn),r.customRemove&&r.customRemove.addEventListener("click",un);for(const e of[r.customBaseUrl,r.customKey,r.customModel])e&&e.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),dn())}));r.upgradePlan.addEventListener("click",(()=>ve("upgrade"))),r.topupBtn.addEventListener("click",(()=>ve("topup"))),attachScrollLift({panes:document.querySelectorAll(".messages, .side, .memory-scroll"),target:document.body,requestFrame:e=>window.requestAnimationFrame(e)}),r.quickLauncherSave.addEventListener("click",xe),r.quickLauncherShortcut.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),xe())})),r.confirmMode&&r.confirmMode.addEventListener("change",(()=>$e(r.confirmMode.checked))),r.autoMode&&r.autoMode.addEventListener("click",(()=>{r.confirmMode&&$e(!r.confirmMode.checked)})),r.composer.addEventListener("submit",(e=>{e.preventDefault(),$n()})),r.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"))&&(An+=1,document.body.classList.add("is-dropping"))})),window.addEventListener("dragleave",(()=>{An=Math.max(0,An-1),0===An&&document.body.classList.remove("is-dropping")})),window.addEventListener("dragover",(e=>{e.dataTransfer&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")})),window.addEventListener("drop",(t=>{An=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 Bn(n):(Ln.push({name:t.name||"file",reason:"no path available"}),Nn())}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=r.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 l=(s+i+e).length;try{t.setSelectionRange(l,l)}catch{}t.focus()}(s))}(t).catch((()=>{}))})),document.addEventListener("dragover",(e=>e.preventDefault())),document.addEventListener("drop",(e=>e.preventDefault())),r.classSelect&&r.classSelect.addEventListener("change",Nn),Nn()),r.prompt.addEventListener("keydown",(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),r.composer.requestSubmit())})),r.tabSessions&&r.tabSessions.addEventListener("click",(()=>fn("sessions"))),r.tabMemory&&r.tabMemory.addEventListener("click",(()=>fn("memory"))),r.memorySearchForm.addEventListener("submit",(e=>{e.preventDefault(),ct(r.memoryQuery.value.trim())})),r.memorySaveBtn.addEventListener("click",vt),r.memoryImportBtn.addEventListener("click",gt),r.memoryOpen&&r.memoryOpen.addEventListener("click",ht),r.memoryClose&&r.memoryClose.addEventListener("click",ft),r.memoryBackdrop&&r.memoryBackdrop.addEventListener("click",ft),r.memoryOverlaySave&&r.memoryOverlaySave.addEventListener("click",vt),r.memoryFilters&&r.memoryFilters.addEventListener("submit",(e=>{e.preventDefault(),je.query=r.memoryOverlayQuery.value.trim(),yt(je.query)})),r.memoryFiltersClear&&r.memoryFiltersClear.addEventListener("click",(()=>{r.memoryOverlayQuery.value="",je.query="",je.source="",je.role="",pt()})),r.keysClose&&r.keysClose.addEventListener("click",Ut),r.keysBackdrop&&r.keysBackdrop.addEventListener("click",Ut),r.keysDismiss&&r.keysDismiss.addEventListener("click",Ot),r.keysGotoAegis&&r.keysGotoAegis.addEventListener("click",(()=>{Ut(),Mt(r.apiKeyInput),r.apiKeyInput&&r.apiKeyInput.focus(),r.apiKeyHint&&(r.apiKeyHint.textContent=`Missing: ${function(){const e=[];return!0!==le&&e.push("the AEGIS key"),!0!==ce&&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.`)})),r.keysGotoByok&&r.keysGotoByok.addEventListener("click",(()=>{Ut(),Nt()})),s&&(r.queueEnqueue&&r.queueEnqueue.addEventListener("click",Ie),r.queueDrain&&r.queueDrain.addEventListener("click",(()=>Be("one"))),r.queueProceed&&r.queueProceed.addEventListener("click",(()=>Be("all"))),r.queueStop&&r.queueStop.addEventListener("click",Te),"function"==typeof s.onProgress&&s.onProgress(De),r.queueClassSelect&&r.queueClassSelect.addEventListener("change",(()=>{localStorage.setItem(c,r.queueClassSelect.value),sn(r.queueClassSelect.value)})),await He(),await async function(){if(!r.queueClassSelect)return;let e=[];try{e=await t.listClasses()||[]}catch(t){e=[],r.queueModelHint&&(r.queueModelHint.textContent=`listClasses failed: ${t&&t.message?t.message:t}`)}r.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)`,r.queueClassSelect.appendChild(e)}const n=localStorage.getItem(c);n&&e.some((e=>e.class===n))&&(r.queueClassSelect.value=n),await sn(r.queueClassSelect.value)}()),a&&(r.queueAuto&&r.queueAuto.addEventListener("change",(()=>Oe(r.queueAuto.checked))),r.queueAutoInterval&&r.queueAutoInterval.addEventListener("change",(()=>{r.queueAuto&&r.queueAuto.checked&&Oe(!0)})),await async function(){if(!a||"function"!=typeof a.status)return null;try{const e=await a.status();return Ue(e),e}catch(e){return r.queueAutoHint&&(r.queueAutoHint.textContent=`automation status unavailable: ${e&&e.message?e.message:e}`),null}}()),J=createTranscriptView({messages:r.messages,requestFrame:e=>requestAnimationFrame(e)}),J.attachScrollVeto();let f=null;window.__aegisSmoke=Object.freeze({isScrolledUp:()=>J.isScrolledUp(),metrics:()=>J.metrics(),escapeDecision:()=>f&&"function"==typeof f.lastDecision?f.lastDecision():null,stopOutcome:()=>Z}),f=bindEscapeInterrupt({doc:document,isOverlayOpen:Ge,onOverlayEscape:()=>{if(Qe())Ut();else{if(Ve&&"function"==typeof Ve.close)try{return void Ve.close()}catch(e){}ft()}},hasPendingTurn:()=>!!B,stopTurn:ee}),r.accountBanner&&e.onAccountStatus&&(e.onAccountStatus(he),e.accountStatus().then(he).catch((e=>console.warn("account status unavailable",e))),r.accountRetryBtn.addEventListener("click",(()=>fe(r.accountRetryBtn))),r.keysAccountRetry&&r.keysAccountRetry.addEventListener("click",(()=>fe(r.keysAccountRetry)))),r.updateBanner&&e.onUpdateStatus&&(e.onUpdateStatus(pe),e.updateStatus().then(pe).catch((()=>{})),r.updateDownloadBtn.addEventListener("click",(()=>{r.updateDownloadBtn.disabled=!0,Promise.resolve(e.downloadUpdate()).then((e=>{e&&e.status&&pe(e)})).catch((()=>{})).finally((()=>{r.updateDownloadBtn.disabled=!1}))})),r.updateRestartBtn.addEventListener("click",(()=>{e.quitAndInstallUpdate()})),r.updateRetryBtn&&e.checkForUpdates&&r.updateRetryBtn.addEventListener("click",(()=>{r.updateRetryBtn.disabled=!0,Promise.resolve(e.checkForUpdates()).then(pe).catch((()=>{})).finally((()=>{r.updateRetryBtn.disabled=!1}))})),r.updateLaterBtn.addEventListener("click",(()=>{me=ue&&ue.status,r.updateBanner.hidden=!0}))),r.messages.querySelector(".msg, .chatflow")||qt(),await tn(),await ln(),await async function(){if(o)try{we(await o.status())}catch(e){r.quickLauncherHint.textContent=`status failed: ${e&&e.message?e.message:e}`}}(),await async function(){if(r.confirmMode&&e.getConfirmMode)try{Se(await e.getConfirmMode())}catch(e){r.confirmModeHint.textContent=`status failed: ${e&&e.message?e.message:e}`}}(),await gn(),await kn(),ge(),fn("sessions"),r.memoryQuietFloor&&(r.memoryQuietFloor.textContent=String(_e)),ct("");try{!function(){if(window.aegisProviderToolbar&&r.ptList)if(Ye=window.aegisProviderToolbar.mount({list:r.ptList,count:r.ptCount,search:r.ptSearch,hint:r.ptHint,onSelect:Xe}),r.ptRefresh&&r.ptRefresh.addEventListener("click",(()=>{Je(!0)})),"function"==typeof IntersectionObserver&&r.ptList.closest("section")){const e=new IntersectionObserver((t=>{t.some((e=>e.isIntersecting))&&(e.disconnect(),Je(!1))}));e.observe(r.ptList.closest("section"))}else Je(!1)}()}catch(e){r.ptHint&&(r.ptHint.textContent=`provider list unavailable: ${e&&e.message||e}`)}if(r.companionDismiss&&r.companionDismiss.addEventListener("click",(()=>{localStorage.setItem(Ze,JSON.stringify({day:window.aegisCompanion?window.aegisCompanion.dayKey(new Date):"",id:r.companionCard.dataset.messageId||""})),r.companionCard.hidden=!0})),tt(),window.aegisFingerprint)try{Ve=window.aegisFingerprint.mount({api:e,getSessionId:()=>T}),Ve.refresh().catch((()=>{}))}catch(e){const t=r.fpCardStatus;t&&(t.textContent=`authorship panel unavailable: ${e&&e.message||e}`)}}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",On):On()}();
|
|
3
|
+
"use strict";!function(){const e=window.aegis,t=window.models,n=window.sync,o=window.quickLauncher,s=window.queue,a=window.auto;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 i={updateBanner:"update-banner",updateBannerText:"update-banner-text",updateDownloadBtn:"update-download-btn",updateRestartBtn:"update-restart-btn",updateRetryBtn:"update-retry-btn",updateLaterBtn:"update-later-btn",accountBanner:"account-banner",accountBannerText:"account-banner-text",accountRetryBtn:"account-retry-btn",keysAccount:"keys-account",keysAccountRetry:"keys-account-retry",connDot:"conn-dot",connText:"conn-text",app:"st-app",client:"st-client",base:"st-base",key:"st-key",plan:"st-plan",balance:"st-balance",upgradePlan:"upgrade-plan",topupBtn:"topup-btn",topupAmount:"topup-amount",billingHint:"billing-hint",apiKeyInput:"api-key-input",apiKeySave:"api-key-save",apiKeyVerify:"api-key-verify",apiKeyHint:"api-key-hint",classSelect:"class-select",modelSelect:"model-select",providerMark:"provider-mark",ptSearch:"pt-search",ptRefresh:"pt-refresh",ptList:"pt-list",ptCount:"pt-count",ptHint:"pt-hint",companionCard:"companion-card",companionText:"companion-text",companionDismiss:"companion-dismiss",modelFree:"model-input",budgetHint:"budget-hint",autonomousToggle:"autonomous-toggle",autonomousToggleWrap:"autonomous-toggle-wrap",autonomousControls:"autonomous-controls",effortSelect:"effort-select",autonomousWorkers:"autonomous-workers",modelHint:"model-hint",settingsList:"settings-list",settingsHint:"settings-hint",customBaseUrl:"custom-base-url",customKey:"custom-key",customModel:"custom-model",customSave:"custom-save",customRemove:"custom-remove",customStatus:"custom-status",quickLauncherEnabled:"quick-launcher-enabled",quickLauncherShortcut:"quick-launcher-shortcut",quickLauncherSave:"quick-launcher-save",quickLauncherHint:"quick-launcher-hint",confirmMode:"confirm-mode-toggle",confirmModeHint:"confirm-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",syncNow:"sync-now",syncStatus:"sync-status",sessionMeter:"session-meter",newChat:"new-chat",memorySearchForm:"memory-search-form",memoryQuery:"memory-query",memoryResults:"memory-results",memoryEntry:"memory-entry",memorySaveBtn:"memory-save-btn",memoryImportBtn:"memory-import-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",fpCardStatus:"fp-card-status",fpOpen:"fp-open",fpOverlay:"fp-overlay",messages:"messages",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",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"},r={};for(const[e,t]of Object.entries(i))Object.defineProperty(r,e,{get:()=>document.getElementById(t),enumerable:!0,configurable:!0});const l="aegis.class",c="aegis.queueClass",d="aegis.autonomous",u="aegis.effort",m="aegis.autonomousWorkers",p="aegis.explore",y="aegis.welcomeConnectDismissed",h="aegis",f=new Set(["__aegis","aegis"]),g="local",v="custom",k="http://localhost:11434",C="https://aegiscloud.org/key?s=desktop&c=key_prompt",b="The autonomous queue keeps running after you close the laptop.",w="https://aegiscloud.org",x=/^[a-z0-9][a-z0-9_-]{0,63}$/;function S(e,t){const n=new URL(`${w}/go/${e}`);n.searchParams.set("s","desktop");const o=null==t?"":String(t).trim().toLowerCase();return x.test(o)&&n.searchParams.set("c",o),n.toString()}function E(e){return S("upgrade",e)}function $(e){return S("topup",e)}const q={welcome_cloud:"welcome",queue_cap:"queue",memory_quota:"memory",status_card:"status",topup_bank:"topup"},L="upgrade_prompt_rendered",A="upgrade_prompt_clicked";let M=!1;function N(e,t){try{const n=q[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(!M){M=!0;try{console.debug("telemetry: prompt event failed (suppressed)",e)}catch{}}}}function H(e,t,n,o){const s=document.createElement("a");return s.href=function(e,t){const n="topup_bank"===t?$(t):E(t);if(!e)return n;let o;try{o=new URL(e,w)}catch{return e}return o.origin!==w||o.searchParams.get("s")||o.searchParams.get("utm_source")?e:/topup/.test(o.pathname)?$(t):n}(t,n),s.target="_blank",s.rel="noreferrer noopener",s.textContent=o,s.addEventListener("click",(()=>N(A,n))),e.appendChild(s),!1===e.isConnected||e.hidden||N(L,n),s}let I=null,B=null,T=null,R=[],U=[],O=new Map;const D=new Map;function F(e,t,n={}){const o=e||"",s=rollTurn(function(e){const t=e||"";return D.has(t)||D.set(t,emptyRoll()),D.get(t)}(o),t,n);return D.set(o,s),K(o),s}function K(e,t){const n=r.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(!I)return null;let e=I.querySelector(".typing-tokens");return e||(e=document.createElement("span"),e.className="typing-tokens",e.hidden=!0,I.appendChild(e)),e}():null;if(s&&(s.textContent=o,s.hidden=!o),!n)return;if(T!==e)return void(n.hidden=!0);let a=D.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 P(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 _="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.",j=[{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 G=0;const Q=new Set;function W(){for(const e of Q)try{t.cancel(e)}catch{}Q.clear()}let V=0,Y=null,z=null,J=null;function X(e){return!!J&&J.follow(e)}let Z=null;function ee(){if(!B)return!1;if(!stopAppliesTo(Y,z))return!1;z=Y;const e=B;Z={sessionId:e,at:Date.now(),state:"requested"};try{const n=t.cancel(e);n&&"function"==typeof n.then&&n.then((t=>{Z={sessionId:e,at:Date.now(),state:"settled",accepted:!t||!1!==t.ok,result:void 0===t?null:t}}),(t=>{Z={sessionId:e,at:Date.now(),state:"rejected",accepted:!1,error:t&&t.message||String(t)}}))}catch(t){Z={sessionId:e,at:Date.now(),state:"threw",accepted:!1,error:t&&t.message||String(t)}}if(I){const e=I.querySelector(".cancel-btn");e&&(e.disabled=!0,e.textContent="stopping…")}return!0}function te(){const e=r.autonomousToggle;return Boolean(e&&e.checked)}function ne(){if(!r.autonomousControls)return;const e=r.autonomousToggleWrap&&!r.autonomousToggleWrap.hidden;r.autonomousControls.hidden=!(e&&te())}function oe(){if(r.modelFree&&!r.modelFree.hidden){const e=r.modelFree.value.trim();if(e)return e}return r.modelSelect.value}function se(e,t){const n=void 0===t?oe():t;r.budgetHint&&(r.budgetHint.textContent=function(e,t){const n=ie(),o=n,s=n;return e===h?`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)),ae()}function ae(){r.providerMark&&window.aegisProviderMark&&window.aegisProviderMark.paint(r.providerMark,oe())}function ie(){const e=r.effortSelect&&r.effortSelect.value;return"low"===e||"medium"===e||"max"===e?e:"high"}function re(e,t){r.connDot.classList.toggle("ok",Boolean(e)),r.connText.textContent=t}let le=null,ce=!1;function de(e){if(!e)return le=null,ce=!1,void re(!1,"IPC unavailable");le=Boolean(e.keyConfigured),ce=Boolean(e.providerConfigured),r.app.textContent=e.appVersion?`v${e.appVersion}`:"–",r.client.textContent=e.clientVersion||"–",r.base.textContent=e.apiBase||"–",r.key.textContent=e.keyConfigured?e.keyMask:"not set",re(e.keyConfigured,e.keyConfigured?"key configured":"no API key"),Lt(),bt(),function(){const e=document.getElementById("keys-overlay");if(!e)return;let t=!1;try{t="on"===localStorage.getItem(Tt)}catch{}t||null===le?e.hidden=!0:(Rt(),Boolean(B)?Ut():!0!==le||!0!==ce?r.keysOverlay&&(Rt(),r.keysOverlay.hidden&&(r.keysOverlay.hidden=!1,document.body.classList.add("keys-open"))):Ut())}()}let ue=null,me=null;function pe(e){if(!r.updateBanner)return;ue=e;try{tt()}catch{}const t=e&&e.status;if(!t||"idle"===t||"disabled"===t||"checking"===t||"up-to-date"===t||"unavailable"===t||t===me)return void(r.updateBanner.hidden=!0);let n="",o=!1,s=!1,a=!1;const i=e.version?`v${e.version} `:"";if("available"===t)n=e.command?e.commandIsSentence?`Update ${i}available. ${e.command}`:`Update ${i}available — run: ${e.command}`:`Update ${i}available.`,o=!!e.canDownload,o&&(n=`Update ${i}available.`);else if("downloading"===t)n=`Downloading update${"number"==typeof e.progress?` (${Math.round(e.progress)}%)`:""}…`;else if("downloaded"===t)n=`Update ${i}downloaded — restart to install.`,s=!0;else{if("error"!==t)return void(r.updateBanner.hidden=!0);n=`Update check failed: ${e.error||"unknown error"}`,e.transient&&(n+=" — will retry automatically."),a=!0}r.updateBannerText.textContent=n,r.updateDownloadBtn.hidden=!o,r.updateRestartBtn.hidden=!s,r.updateRetryBtn&&(r.updateRetryBtn.hidden=!a),r.updateBanner.hidden=!1}let ye=null;function he(e){ye=e&&"no-key"===e.status?e.reason:null,Rt(),r.accountBanner&&(ye?(r.accountBannerText.textContent=`No AEGIS account key on this machine: ${ye}.`,r.accountBanner.hidden=!1):r.accountBanner.hidden=!0)}function fe(t){t.disabled=!0,e.registerAccount().then((e=>{if(he(e),!e)return ke()})).catch((e=>he({status:"no-key",reason:String(e&&e.message||e)}))).finally((()=>{t.disabled=!1}))}async function ge(){try{const t=await e.verifyApiKey();t&&t.ok?r.plan.textContent=t.valid?t.plan||"active":"invalid key":r.plan.textContent="unavailable"}catch{r.plan.textContent="unavailable"}try{const t=await e.tokenBankBalance();r.balance.textContent=t&&null!=t.balance_eur?`€${t.balance_eur}`:"–"}catch{r.balance.textContent="unavailable"}}async function ve(t){const n=Math.round(Number(r.topupAmount&&r.topupAmount.value)||10),o="topup"===t?r.topupBtn:r.upgradePlan;if(o&&(o.disabled=!0),"topup"===t&&!1===le)return o&&(o.disabled=!1),void(r.billingHint.textContent="add your AEGIS API key above — a top-up is credited to your account");r.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?(r.billingHint.textContent=`free plan cap reached — ${n} lifts it. `,void H(r.billingHint,e.upgrade.url,"topup"===t?"topup_bank":"status_card","See plans →")):void(e.setupRequired?r.billingHint.textContent="checkout is not configured on the server yet (no Stripe price id)":r.billingHint.textContent=`${n} failed: ${e.reason||"the server returned no checkout URL"}`);r.billingHint.textContent=`add your AEGIS API key above — a ${n} needs an account`}(o||{},t);r.billingHint.textContent="opening checkout…";const s=await e.openExternal(o.url);if(s&&!1===s.ok)return void(r.billingHint.textContent=`could not open the checkout page: ${s.reason||"unknown reason"}`);r.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){r.billingHint.textContent=`billing failed: ${e&&e.message?e.message:e}`}finally{o&&(o.disabled=!1)}}async function ke(){try{de(await e.status())}catch{de(null)}await Zt(),await ge()}async function Ce(){const t=r.apiKeyInput.value.trim();r.apiKeySave.disabled=!0,r.apiKeyVerify.disabled=!0,r.apiKeyHint.textContent="saving…";try{const n=await e.setApiKey(t);if(!n||!n.ok)throw new Error(n&&n.error||"save failed");r.apiKeyInput.value="",r.apiKeyHint.textContent=t?`saved (${n.keyMask?n.keyMask:"configured"})`:"key cleared",await ke()}catch(e){r.apiKeyHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{r.apiKeySave.disabled=!1,r.apiKeyVerify.disabled=!1}}async function be(){r.apiKeyVerify.disabled=!0,r.apiKeyHint.textContent="verifying…";try{const t=await e.verifyApiKey();if(!t||!t.ok)throw new Error(t&&t.error||"verify failed");r.apiKeyHint.textContent=t.valid?`valid (${t.plan||"active"})`:"invalid key"}catch(e){r.apiKeyHint.textContent=`verify failed: ${e&&e.message?e.message:e}`}finally{r.apiKeyVerify.disabled=!1}}function we(e){if(!e)return;r.quickLauncherEnabled.checked=Boolean(e.enabled),r.quickLauncherShortcut.value=e.shortcut||"",r.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),r.quickLauncherHint.textContent=t.join(" · ")}async function xe(){if(o){r.quickLauncherSave.disabled=!0,r.quickLauncherHint.textContent="saving…";try{we(await o.setConfig({enabled:r.quickLauncherEnabled.checked,shortcut:r.quickLauncherShortcut.value.trim()}))}catch(e){r.quickLauncherHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{r.quickLauncherSave.disabled=!1}}}function Se(e){if(!r.confirmMode||!e)return;const t=!1!==e.enabled;r.confirmMode.checked=t,r.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.",Ee(t)}function Ee(e){if(!r.autoMode)return;const t=!e;r.autoMode.setAttribute("aria-pressed",t?"true":"false"),r.autoMode.classList.toggle("is-auto",t),r.autoModeLabel&&(r.autoModeLabel.textContent=t?"auto mode":"ask before tools"),r.autoModeHint&&(r.autoModeHint.textContent=t?"on — tools run without asking. Click to require approval.":"off — click for auto mode, or use Settings → Tool approvals.")}async function $e(t){if(r.confirmMode){r.confirmMode.disabled=!0,r.autoMode&&(r.autoMode.disabled=!0);try{Se(await e.setConfirmMode(t))}catch(e){r.confirmMode.checked=!t,r.confirmModeHint.textContent=`save failed: ${e&&e.message?e.message:e}`,Ee(r.confirmMode.checked)}finally{r.confirmMode.disabled=!1,r.autoMode&&(r.autoMode.disabled=!1)}}}let qe="",Le=!1;function Ae(e){qe=e||"",r.queueHint&&(r.queueHint.textContent=qe)}function Me(e){const t=document.createElement("li");t.className="session-row",t.dataset.status=e.status;const n=document.createElement("span");n.className="session-title";const o=String(e.task||"").replace(/\s+/g," ").trim();var s;n.textContent=`#${e.id} ${s=e.status,"done"===s?"✓":"error"===s?"✗":"running"===s?"…":"·"} ${o.length>90?`${o.slice(0,89)}…`:o}`,t.appendChild(n);const a=document.createElement("span");if(a.className="session-meta",a.textContent=function(e){const t=[e.status];if(e.model&&t.push(e.model),t.push(!1===e.singlePass||!0===e.autonomous?"fan-out":"single pass"),"error"===e.status)t.push(e.error?String(e.error):"failed — no reason recorded");else if("done"===e.status){const n=(e.result&&e.result.output?String(e.result.output):"").replace(/\s+/g," ").trim();n&&t.push(n.length>140?`${n.slice(0,139)}…`:n);const o=e.result&&Array.isArray(e.result.files)?e.result.files:[];o.length&&t.push(`touched ${o.length} file${1===o.length?"":"s"}`)}else"running"===e.status?t.push(e.startedAt?`started ${nt(e.startedAt)}`:"working"):(e.attempts&&t.push(`${e.attempts} attempt${1===e.attempts?"":"s"}`),e.created&&t.push(nt(e.created)));return t.join(" · ")}(e),t.appendChild(a),"done"===e.status||"error"===e.status){const n=document.createElement("button");n.type="button",n.className="ghost-btn",n.textContent="Retry",n.title="Put this task back in line and run it again",n.addEventListener("click",(()=>Re("retry",e.id))),t.appendChild(n)}if("running"!==e.status){const n=document.createElement("button");n.type="button",n.className="ghost-btn",n.textContent="Remove",n.addEventListener("click",(()=>Re("remove",e.id))),t.appendChild(n)}return t}function Ne(e){if(!r.queueList||!e||"object"!=typeof e)return;Le=Boolean(e.draining),r.queueCwd&&!r.queueCwd.value&&(r.queueCwd.value=e.defaultCwd||""),r.queueEnqueue&&(r.queueEnqueue.disabled=Le),r.queueDrain&&(r.queueDrain.disabled=Le),r.queueProceed&&(r.queueProceed.disabled=Le),r.queueStop&&(r.queueStop.hidden=!Le);const t=Array.isArray(e.items)?e.items:[];if(r.queueList.innerHTML="",t.length)for(const e of t)r.queueList.appendChild(Me(e));else{const e=document.createElement("li");e.className="empty",e.textContent="queue is empty",r.queueList.appendChild(e)}const n=[];e.running?n.push(`running #${e.running.id}`):Le&&n.push("draining…"),n.push(`${e.pending||0} pending`),e.defaultModel&&n.push(`Aegis Cloud · ${e.defaultModel}`),Le&&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(r.queueFanout&&(r.queueFanout.disabled=!o,o||(r.queueFanout.checked=!1)),r.queueBoundary&&(r.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||"":""),r.queueUpgrade&&(r.queueUpgrade.innerHTML="",n&&!o)){const e="balance"===t.wall;H(r.queueUpgrade,t.upgradeUrl,t.campaign,e?"Top up your balance ↗":"See what Pro covers ↗")}}(e),r.queueHint&&(r.queueHint.textContent=[qe,n.join(" · ")].filter(Boolean).join(" · "))}async function He(){if(!s||!r.queueList)return null;try{const e=await s.list();return Ne(e),e}catch(e){return Ae(`queue list failed: ${e&&e.message?e.message:e}`),null}}async function Ie(){if(!s||!r.queueTask)return;const e=r.queueTask.value.trim();if(e){r.queueEnqueue&&(r.queueEnqueue.disabled=!0),Ae("queueing…");try{const t=await s.enqueue({task:e,cwd:r.queueCwd?r.queueCwd.value.trim():"",class:r.queueClassSelect?r.queueClassSelect.value:void 0,model:tn(),commit:!!r.queueCommit&&r.queueCommit.checked});t&&t.ok?(r.queueTask.value="",Ae(`queued #${t.item.id}`)):Ae(t&&t.reason||"enqueue failed"),Ne(t)}catch(e){Ae(`enqueue failed: ${e&&e.message?e.message:e}`)}finally{r.queueEnqueue&&(r.queueEnqueue.disabled=Le)}}else Ae("type a task first")}async function Be(e){if(s){Le=!0,Ae("one"===e?"running one task…":"draining the queue…"),r.queueDrain&&(r.queueDrain.disabled=!0),r.queueProceed&&(r.queueProceed.disabled=!0),r.queueEnqueue&&(r.queueEnqueue.disabled=!0),r.queueStop&&(r.queueStop.hidden=!1);try{const t=await("one"===e?s.drain():s.proceed());Ae(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)),Ne(t)}catch(e){Le=!1,r.queueDrain&&(r.queueDrain.disabled=!1),r.queueProceed&&(r.queueProceed.disabled=!1),r.queueEnqueue&&(r.queueEnqueue.disabled=!1),r.queueStop&&(r.queueStop.hidden=!0),Ae(`drain failed: ${e&&e.message?e.message:e}`)}}}async function Te(){if(s){r.queueStop&&(r.queueStop.disabled=!0),Ae("stopping…");try{const e=await s.stop(),t=e&&e.cancelled&&e.cancelled.ok;qe=t?"stopped the running task":"stop requested",Ne(e)}catch(e){Ae(`stop failed: ${e&&e.message?e.message:e}`)}finally{r.queueStop&&(r.queueStop.disabled=!1)}}}async function Re(e,t){if(s){Ae(`${e} #${t}…`);try{const n=await s[e](t);n&&!1===n.ok?Ae(n.reason||`${e} failed`):Ae(`${"retry"===e?"re-queued":"removed"} #${t}`),Ne(n)}catch(t){Ae(`${e} failed: ${t&&t.message?t.message:t}`)}}}function Ue(e){e&&"object"==typeof e&&e.drain&&function(e){if(!r.queueAuto||!e||"object"!=typeof e)return;const t=!0===e.enabled;if(r.queueAuto.checked=t,r.queueAutoInterval){r.queueAutoInterval.disabled=!t;const n=Number(e.intervalMs);Number.isFinite(n)&&(r.queueAutoInterval.value=String(n))}if(r.queueAutoLabel&&(r.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"),!r.queueAutoHint)return;if(!t)return void(r.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"),r.queueAutoHint.textContent=n.join(" · ")}(e.drain)}async function Oe(e){if(!a||"function"!=typeof a.setDrain)return;const t={enabled:Boolean(e)};r.queueAutoInterval&&r.queueAutoInterval.value&&(t.intervalMs=Number(r.queueAutoInterval.value));try{const e=await a.setDrain(t);e&&!1===e.ok&&r.queueAutoHint&&(r.queueAutoHint.textContent=e.error||"could not save that"),Ue(e)}catch(e){r.queueAutoHint&&(r.queueAutoHint.textContent=`could not save that: ${e&&e.message?e.message:e}`)}}function De(e){if(!e||"object"!=typeof e)return;const t=null==e.taskId?"":`#${e.taskId} `;if("start"===e.type)Ae(`${t}running${e.model?` on ${e.model}`:""}…`);else if("tool"===e.type&&e.tool)Ae(`${t}${Vt(e.tool)}`);else if("finish"===e.type)Ae(`${t}${e.ok?"done":"failed"} — refreshing`),He();else if("recovered"===e.type){const t=Array.isArray(e.ids)?e.ids:[];Ae(`recovered ${t.length} stalled task${1===t.length?"":"s"}`)}else"locked"===e.type?Ae("another drain is already running"):"queued"===e.type&&Ae(`queued phase ${e.phase}`)}function Fe(e){const t=e&&e.prompt,o=e&&e.response;if(!t||!o)return;T||(T=Xt());const s=T,a=e&&e.model||"",i=e&&e.class||"",r=i||a?[i?i.toUpperCase():"",a].filter(Boolean).join(" · "):void 0;Ft("user",t),Ft("assistant",o,r,s),R.push({role:"user",content:t}),R.push({role:"assistant",content:o}),n.append(s,{role:"user",content:t}).catch((()=>{})),n.append(s,{role:"assistant",content:o}).catch((()=>{}))}const Ke=10,Pe=6,_e=50,je={entries:[],query:"",source:"",role:"",error:"",upgrade:null,loading:!1};function Ge(){if(Qe())return!0;if(We())return!0;if(Ve&&"function"==typeof Ve.isOpen)try{return!!Ve.isOpen()}catch(e){return!1}return!1}function Qe(){return!!r.memoryOverlay&&!r.memoryOverlay.hidden}function We(){return!!r.keysOverlay&&!r.keysOverlay.hidden}let Ve=null,Ye=null,ze=!1;async function Je(e){if(!Ye)return;if(ze&&!e)return;r.ptHint&&(r.ptHint.textContent="listing providers…");const n=await async function(){let e=[];try{e=await t.listClasses()||[]}catch(e){return r.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}();ze=!0,Ye.set(n)}function Xe(e){e&&e.class&&Array.from(r.classSelect.options).some((t=>t.value===e.class))&&(r.classSelect.value=e.class,localStorage.setItem(l,e.class),se(e.class),en(e.class).then((()=>{e.model&&Array.from(r.modelSelect.options).some((t=>t.value===e.model))&&(r.modelSelect.value=e.model,r.modelSelect.dispatchEvent(new Event("change")))})))}const Ze="aegis.companion.dismissed";function et(){const e={keyConfigured:null===le?void 0:le};return Array.isArray(je.entries)&&je.entries.length&&(e.memoryCount=je.entries.length),ue&&"downloaded"===ue.status&&ue.version&&(e.updatePending=String(ue.version)),U.length&&r.modelSelect&&r.modelSelect.options.length>1&&(e.modelCount=r.modelSelect.options.length),e}function tt(){if(!window.aegisCompanion||!r.companionCard||!r.companionText)return;const e=new Date;let t=null;try{t=JSON.parse(localStorage.getItem(Ze)||"null")}catch{t=null}if(window.aegisCompanion.dismissedToday(t,e))return void(r.companionCard.hidden=!0);const n=window.aegisCompanion.pickMessage(et(),e);n&&n.text?(r.companionText.textContent=n.text,r.companionCard.dataset.kind=n.kind,r.companionCard.dataset.messageId=n.id,r.companionCard.hidden=!1):r.companionCard.hidden=!0}function nt(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 ot(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(ot):[];return o&&o.upgrade?{entries:a,error:"",upgrade:o.upgrade}:{entries:a,error:"",upgrade:null}}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||E("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}}}function at(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 it(e,t,n,o,s){if(!e)return;const a=null!=t.used?at(t.used):"?",i=null!=t.limit?at(t.limit):"?";e.textContent=`${n||"sync limit reached"} — ${a} of ${i} tokens synced. Nothing was lost. ${b} `,H(e,t.url,s||"memory_quota",o||"See what Pro covers →")}function rt(e,t){it(r.memoryHint,e,t)}function lt(e,t,n,o=!1){r.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)>=Pe))}(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;r.tabMemory&&(r.tabMemory.hidden=!(t||n||o)),r.memoryBox&&(r.memoryBox.hidden=!n),r.memoryQuiet&&(r.memoryQuiet.hidden=!o),r.tabMemory&&r.tabMemory.hidden&&"memory"===pn&&yn("sessions")}({hasAny:s.length>0,hasBox:a,quietNotice:i}),a){if(n){const e=document.createElement("li");return e.className="empty mem-side-upgrade",r.memoryResults.appendChild(e),void H(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 r.memoryResults.appendChild(e)}if(!s.length){const e=document.createElement("li");return e.className="empty",e.textContent="no memory entries",void r.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),r.memoryResults.appendChild(t)}}}async function ct(e){r.memoryHint.textContent="searching…";const t=await st(e,Ke);lt(t.entries,t.error,t.upgrade,""===e),t.upgrade?rt(t.upgrade,"cloud memory needs an active plan"):r.memoryHint.textContent=t.error||""}function dt(e,t){const n=document.createElement("span");return n.className="mem-chip"+(t?` ${t}`:""),n.textContent=e,n}function ut(e){const t=document.createElement("li");t.className="mem-card";const n=document.createElement("div");n.className="mem-card-head",n.appendChild(dt(e.source,"src")),e.role&&n.appendChild(dt(e.role,"role")),null!=e.importance&&n.appendChild(dt(`imp ${e.importance}`,"imp")),e.sentiment&&n.appendChild(dt(e.sentiment,"sent")),e.summary&&n.appendChild(dt("summary","flag"));const o=document.createElement("span");o.className="mem-card-meta";const s=[],a=nt(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(dt(t,"pill"));t.appendChild(e)}return i.addEventListener("click",(()=>{window.getSelection&&String(window.getSelection())||t.classList.toggle("expanded")})),t}function mt(e){const t=new Map;for(const n of je.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 pt(){if(!Qe())return;const e=je.entries.length;if(r.memoryList.innerHTML="",function(){if(r.memoryChips.innerHTML="",je.upgrade||je.error)return;const e=[["source","source",mt("source")],["role","role",mt("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"+(je[t]===n?" on":""),o.textContent=`${n} ${s}`,o.addEventListener("click",(()=>{je[t]=je[t]===n?"":n,pt()})),e.appendChild(o)}r.memoryChips.appendChild(e)}}(),je.loading)return void(r.memoryCount.textContent="loading…");if(je.upgrade){r.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!=je.upgrade.used?at(je.upgrade.used):"?",s=null!=je.upgrade.limit?at(je.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. `+b,e.appendChild(t),e.appendChild(n),r.memoryList.appendChild(e),void H(e,je.upgrade.url,"memory_quota","Open subscribe page ↗")}if(je.error){r.memoryCount.textContent="";const e=document.createElement("li");return e.className="mem-empty",e.textContent=je.error,void r.memoryList.appendChild(e)}if(!e){r.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 r.memoryList.appendChild(e)}const t=je.query.trim().toLowerCase(),n=je.entries.filter((e=>(!je.source||e.source===je.source)&&(!je.role||e.role===je.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(je.entries.map((e=>e.source))).size;if(r.memoryCount.textContent=`${n.length} of ${e} shown · ${o} source${1===o?"":"s"}`+(e>=_e?` · newest ${_e}`:""),!n.length){const e=document.createElement("li");return e.className="mem-empty",e.textContent="Nothing matches those filters.",void r.memoryList.appendChild(e)}for(const e of n)r.memoryList.appendChild(ut(e))}async function yt(e){je.loading=!0,je.error="",je.upgrade=null,pt();const t=await st(e,_e);je.entries=t.entries,je.error=t.error,je.upgrade=t.upgrade,je.loading=!1,pt()}function ht(){r.memoryOverlay&&(r.memoryOverlay.hidden=!1,document.body.classList.add("memory-open"),r.memoryOverlayQuery.value=r.memoryQuery?r.memoryQuery.value.trim():"",je.query=r.memoryOverlayQuery.value,je.source="",je.role="",pt(),yt(je.query),r.memoryOverlayQuery&&r.memoryOverlayQuery.focus())}function ft(){r.memoryOverlay&&(r.memoryOverlay.hidden=!0,document.body.classList.remove("memory-open"),r.memoryOpen&&r.memoryOpen.focus())}async function gt(){if(e.memoryImport){r.memoryImportBtn.disabled=!0,r.memoryHint.textContent="scanning for other AI tool memory…";try{const t=await e.memoryImport({confirm:!1});if(!t||!t.totals||!t.totals.entries)return void(r.memoryHint.textContent=t&&t.summary?t.summary:"nothing found.");const n=(t.sources||[]).filter((e=>e.present&&e.count>0)).map((e=>`${e.label}: ${e.count}`)).join(" · ");r.memoryHint.textContent=`importing ${t.totals.entries} entries — ${n}`;const o=await e.memoryImport({confirm:!0,limit:1e3});if(o&&o.upgrade)return rt(o.upgrade,`import stopped after ${o.saved||0} entries`),void await kt();const s=o&&o.queued?` (${o.queued} queued offline)`:"";r.memoryHint.textContent=o&&o.ok?`imported ${o.saved} entries${s}.`:`import stopped: ${o&&o.reason||"unknown error"}`,await kt()}catch(e){r.memoryHint.textContent=`import failed: ${e&&e.message?e.message:e}`}finally{r.memoryImportBtn.disabled=!1}}}async function vt(){const t=Qe()&&r.memoryOverlayEntry?r.memoryOverlayEntry:r.memoryEntry;if(!t)return;const n=t.value.trim();if(n){r.memorySaveBtn.disabled=!0,r.memoryOverlaySave&&(r.memoryOverlaySave.disabled=!0),r.memoryHint.textContent="saving…";try{const o=await e.memorySave({text:n,source:"aegis-desktop"});if(o&&o.upgrade)return rt(o.upgrade,"free plan limit reached"),void await kt();t.value="",r.memoryHint.textContent=o&&o.queued?"saved offline — syncs when AEGIS is reachable.":"saved.",await kt()}catch(e){r.memoryHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{r.memorySaveBtn.disabled=!1,r.memoryOverlaySave&&(r.memoryOverlaySave.disabled=!1)}}}async function kt(){const e=r.memoryQuery?r.memoryQuery.value.trim():"";await ct(e),Qe()&&await yt(je.query)}function Ct(){const e=et();return void 0===e.keyConfigured&&delete e.keyConfigured,e}function bt(){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(Ct(),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 wt="aegis.welcomeAiLine",xt=120,St=200;function Et(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 $t(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 qt(){const e=document.getElementById("welcome-template");if(!e)return;r.messages.innerHTML="",r.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?"}(),bt(),async function(){const e=document.getElementById("welcome-personal");if(!e)return;if(void 0===t||!t||"function"!=typeof t.chat)return;if(!(!0===le||r.modelSelect&&r.modelSelect.options&&r.modelSelect.options.length>1))return;const n=new Date,o=function(e){let t=null;try{t=JSON.parse(localStorage.getItem(wt)||"null")}catch{t=null}return t&&"string"==typeof t.text&&t.text?t.day!==Et(e)?null:t.text:null}(n);if(o)return e.textContent=o,e.dataset.kind="ai",void(e.hidden=!1);const s=Ct(),a=r.classSelect&&r.classSelect.value?r.classSelect.value:"aegis",i=r.modelSelect&&r.modelSelect.value?r.modelSelect.value:"",l={class:a,prompt:$t(s),maxTokens:xt,tools:!1,singlePass:!0,effort:"low",bestEffort:!0};i&&(l.model=i);let c=null;try{c=await t.chat(l)}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>St){const e=n.slice(0,St),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(wt,JSON.stringify({day:Et(n),text:u}))}catch{}}}();const n=document.getElementById("welcome-byok");n&&n.addEventListener("click",Nt);const o=document.getElementById("welcome-cloud");o&&o.addEventListener("click",Ht);const s=document.getElementById("welcome-dismiss");s&&s.addEventListener("click",Bt),Lt()}function Lt(){const e=document.getElementById("welcome-connect");if(!e)return;let t=!1;try{t="on"===localStorage.getItem(y)}catch{}const n=!0!==le,o=!0!==ce;e.hidden=t||!n&&!o,At("welcome-cloud",!n),At("welcome-cloud-note",!n),At("welcome-byok",!o),At("welcome-byok-note",!o)}function At(e,t){const n=document.getElementById(e);n&&(n.hidden=t)}function Mt(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 Nt(){if(It("byok"),Array.from(r.classSelect.options).some((e=>"byok"===e.value))&&"byok"!==r.classSelect.value&&(r.classSelect.value="byok",r.classSelect.dispatchEvent(new Event("change"))),Mt(r.settingsList),!1===le&&r.apiKeyHint&&(r.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===le&&r.apiKeyInput)return r.apiKeyInput.focus(),void Mt(r.apiKeyInput);const e=r.settingsList?r.settingsList.querySelector('.setting-row input[type="password"]'):null;e&&e.focus()}function Ht(){It("cloud"),Mt(r.apiKeyInput),r.apiKeyInput&&r.apiKeyInput.focus()}function It(e){const t=r.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: ${b} Paste your AEGIS key, then Save. Free key at `));const n=document.createElement("a");n.href=C,n.target="_blank",n.rel="noreferrer noopener",n.textContent="aegiscloud.org",t.appendChild(n),t.appendChild(document.createTextNode("."))}function Bt(){try{localStorage.setItem(y,"on")}catch{}const e=document.getElementById("welcome-connect");e&&(e.hidden=!0)}const Tt="aegis.keysPopupDismissed";function Rt(){const e=!0===le,t=!0===ce;r.keysAegisState&&(r.keysAegisState.textContent=e?"set":"not set"),r.keysByokState&&(r.keysByokState.textContent=t?"set":"not set"),r.keysRowAegis&&r.keysRowAegis.classList.toggle("set",e),r.keysRowByok&&r.keysRowByok.classList.toggle("set",t),r.keysCount&&(r.keysCount.textContent=(e?1:0)+(t?1:0)+" / 2"),r.keysAccount&&(r.keysAccount.hidden=!ye,r.keysAccount.textContent=ye?`The AEGIS account key could not be set up: ${ye}.`:""),r.keysAccountRetry&&(r.keysAccountRetry.hidden=!ye),r.keysHint&&(r.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 Desktop and the aegiscode CLI run.`)}function Ut(){r.keysOverlay&&(r.keysOverlay.hidden=!0,document.body.classList.remove("keys-open"))}function Ot(){try{localStorage.setItem(Tt,"on")}catch{}Ut()}function Dt(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 Ft(e,t,n,o,s){!function(){const e=document.getElementById("chat-welcome");e&&e.remove()}();const a=document.createElement("div");a.className=`msg ${e}`;const i=document.createElement("div");if(i.className="body",Dt(i,e,t),Array.isArray(s)&&s.length){const e=document.createElement("div");e.className="tool-activity";for(const t of s){const n=document.createElement("div");n.textContent=Vt(t),e.appendChild(n)}a.appendChild(e)}if(a.appendChild(i),n){const e=document.createElement("div");e.className="meta",e.textContent=n,a.appendChild(e)}if("assistant"===e&&o){const e=document.createElement("button");e.type="button",e.className="copy-btn",e.textContent="copy",e.addEventListener("click",(()=>async function(e,t){try{await navigator.clipboard.writeText(e),t&&(t.textContent="copied!")}catch(e){t&&(t.textContent="copy failed")}finally{t&&setTimeout((()=>{t.textContent="copy"}),1500)}}(t,e))),a.appendChild(e)}return r.messages.appendChild(a),X(),a}function Kt(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 l=document.createElement("span");l.className="flow-state",l.textContent="queued",a.appendChild(i),a.appendChild(r),a.appendChild(l);const c=document.createElement("div");c.className="flow-body",c.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),l.textContent="stopped",s.classList.remove("pending"),s.classList.add("stopped"),u.remove()})),s.appendChild(a),s.appendChild(c),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${++G}`;e.dataset.session=o,Q.add(o);const s=e.querySelector(".flow-body"),a=e.querySelector(".flow-state"),i=e.querySelector(".flow-meta");let r="";const l=t=>{if(t&&t.approval)return e.classList.contains("pending")&&(e.classList.remove("pending"),a.textContent="needs approval"),void Jt(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 Wt(t.tool):void Yt(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 c=await t.chat({class:n.cls,system:`${_}\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},l),d=c&&c.choices&&c.choices[0]||{};if(c&&c.bestEffortFailed)throw new Error(c.message||"the provider did not answer");if(c&&c.aborted){const e=new Error(c.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)";Dt(s,"assistant",u),e.classList.remove("pending"),e.classList.add("done"),a.textContent="done";const m=[n.path.title];c&&c.model?m.push(c.model):n.model&&m.push(n.model);const p=turnAccounting(c&&c.usage,n.model,{costUsd:c&&"number"==typeof c.costUsd?c.costUsd:void 0}),y=displayTokens(p);null!=y&&m.push(`${y} tokens`),null!=p.cost&&m.push(fmtCost(p.cost,p.real));const h=F(n.parentSessionId,c&&c.usage,{model:n.model,costUsd:c&&"number"==typeof c.costUsd?c.costUsd:void 0,calls:c&&c.calls,turns:0,prompt:`Original request:\n${n.prompt}\n\n${n.path.hint}`,reply:u}),f=fmtRoll(h);f&&m.push(`session: ${f}`),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{Q.delete(o);const t=e.querySelector(".flow-abort");t&&t.remove()}}(s,{...o,path:e}),s}function Pt(){return I||(I=Ft("assistant",""),I.classList.remove("pending"),I)}function _t(e,{cancellable:t}={}){if(r.send.disabled=e,r.prompt.disabled=e,e){I=Ft("assistant",""),I.classList.add("pending");const e=document.createElement("span");e.className="typing-dots";for(let t=0;t<3;t++)e.appendChild(document.createElement("span"));I.querySelector(".body").appendChild(e);const n=document.createElement("span");if(n.className="typing-tokens",n.hidden=!0,I.appendChild(n),t){const e=document.createElement("button");e.type="button",e.className="cancel-btn",e.textContent="cancel",e.addEventListener("click",(()=>ee())),I.appendChild(e)}}else I&&(I.remove(),I=null)}const jt=72,Gt=new Set(["editFile","writeFile","Edit","Write","MultiEdit"]),Qt=new Map;function Wt(e){if(!e||!Gt.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&&Qt.set(e.id,n)}function Vt(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>jt?`${i.slice(0,jt-1)}…`:i;return`→ ${t}${r?` ${r}`:""} ${o}`}function Yt(e,t,n,o){if(!e)return;let s=e.querySelector(`.${n}`);if(!s){s=document.createElement("div"),s.className=n;const t=o?e.querySelector(o):null;t?e.insertBefore(s,t):e.appendChild(s)}const a=t&&null!=t.id?Qt.get(t.id):null;if(a){Qt.delete(t.id);const e=renderDiffBlock(a,document);if(e)return s.appendChild(e),s}const i=document.createElement("div");return i.textContent=Vt(t),s.appendChild(i),s}function zt(e){return e.startsWith("@@")?"diff-hunk":e.startsWith("+++")||e.startsWith("---")?"diff-file":e.startsWith("+")?"diff-add":e.startsWith("-")?"diff-del":"diff-ctx"}function Jt(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=zt(t),n.textContent=t,e.appendChild(n)}s.appendChild(e)}const r=document.createElement("div");r.className="approval-actions";const l=(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":"Allowed once",s.appendChild(o),t.respondApproval(n.id,e)})(a))),i};r.appendChild(l("Allow once","allow","once")),r.appendChild(l("Allow for this session","allow-session","session")),r.appendChild(l("Deny","deny","deny")),s.appendChild(r);let c=e.querySelector(".approval-slot");if(!c){c=document.createElement("div"),c.className="approval-slot";const t=o?e.querySelector(o):null;t?e.insertBefore(c,t):e.appendChild(c)}return c.appendChild(s),s}function Xt(){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 Zt(){try{U=await t.listClasses()||[]}catch(e){U=[],r.modelHint.textContent=`listClasses failed: ${e&&e.message?e.message:e}`}r.classSelect.innerHTML="";for(const e of U){const t=document.createElement("option");t.value=e.class,t.textContent=e.configured?e.label:`${e.label} (not configured)`,r.classSelect.appendChild(t)}const e=localStorage.getItem(l);e&&U.some((t=>t.class===e))&&(r.classSelect.value=e),await en(r.classSelect.value)}async function en(e){if(r.autonomousToggleWrap&&(r.autonomousToggleWrap.hidden=e!==h),ne(),se(e),r.modelSelect.hidden=!1,r.modelSelect.disabled=!1,r.modelFree.hidden=!0,r.modelFree.value="",r.modelHint.textContent="",r.modelSelect.innerHTML="",O=new Map,"aegis"===e){const e=document.createElement("option");e.value="",e.textContent="server default (auto)",r.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),l=Boolean(n&&n.providersFailed),c=Array.isArray(n&&n.unmatchedProviders)?n.unmatchedProviders:[];r.modelFree.hidden=!("local"===e&&(a||!i));for(const e of o){O.set(e.id,e);const t=document.createElement("option");t.value=e.id,t.textContent=e.label||e.id,r.modelSelect.appendChild(t)}let d;if(ae(),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&&l)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&&!l&&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(O.get(oe()));if(s){r.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=C,e.target="_blank",e.rel="noreferrer noopener",e.textContent="free key at aegiscloud.org",r.modelHint.appendChild(e),void r.modelHint.appendChild(document.createTextNode("), then Save."))}r.modelHint.textContent=u<FLAT_CEILING?`${d} · max output: ${u.toLocaleString()}`:d}catch(e){O=new Map,r.modelHint.textContent=`listModels failed: ${e&&e.message?e.message:e}`,ae()}}function tn(){if(r.queueModelInput&&!r.queueModelInput.hidden){const e=r.queueModelInput.value.trim();if(e)return e}return r.queueModelSelect?r.queueModelSelect.value:""}async function nn(e){if(r.queueModelSelect){if(function(e){const t=r.queueFanout&&r.queueFanout.closest("label");t&&(t.hidden="aegis"!==e)}(e),r.queueModelSelect.hidden=!1,r.queueModelSelect.disabled=!1,r.queueModelInput&&(r.queueModelInput.hidden=!0,r.queueModelInput.value=""),r.queueModelHint&&(r.queueModelHint.textContent=""),r.queueModelSelect.innerHTML="","aegis"===e){const e=document.createElement("option");e.value="",e.textContent="server default (auto)",r.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);r.queueModelInput&&(r.queueModelInput.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,r.queueModelSelect.appendChild(t)}if(!r.queueModelHint)return;s?r.queueModelHint.textContent="Connect this class in the Model card above (API key / provider key), then Refresh.":a?r.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&&(r.queueModelHint.textContent="A provider key is required before a queued task on this model can run — add one in the Model card above."):r.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.":r.queueModelHint.textContent="That address answered but listed no models — type the model tag above."}catch(e){r.queueModelHint&&(r.queueModelHint.textContent=`listModels failed: ${e&&e.message?e.message:e}`)}}}function on({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 l=document.createElement("div");l.className="setting-status",l.textContent=n.configured?`configured (${n.keyMask})`:"no key",a.appendChild(l);const c=document.createElement("div");c.className="setting-actions";const d=document.createElement("button");d.type="button",d.className="ghost-btn",d.textContent="Save",d.addEventListener("click",(()=>o(r.value))),c.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),c.appendChild(u),a.appendChild(c),a}async function sn(e){r.settingsHint.textContent="saving…";try{const n=String(null==e?"":e).trim()||k,o=await t.settings.set(g,{baseURL:n}),s=o&&o.baseURL||n;r.settingsHint.textContent=`saved: local model server at ${s}`,await an(),await en(r.classSelect.value)}catch(e){r.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function an(){r.settingsList.innerHTML="";const e=[];let n=[];try{n=await t.settings.get()||[]}catch{}Array.isArray(n)&&(n=n.filter((e=>e&&!f.has(e.provider))));{const e=n.find((e=>e&&e.provider===g))||{provider:g,baseURL:"",configured:!1,keyMask:null};r.settingsList.appendChild(function(e){const t=g,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=k,s.value=e.baseURL||"",s.addEventListener("keydown",(e=>{"Enter"===e.key&&sn(s.value)})),n.appendChild(s);const a=document.createElement("div");a.className="setting-status",a.textContent=e.baseURL?e.baseURL:`default (${k})`,n.appendChild(a);const i=document.createElement("div");i.className="setting-actions";const r=document.createElement("button");r.type="button",r.className="ghost-btn",r.textContent="Save",r.addEventListener("click",(()=>sn(s.value))),i.appendChild(r);const l=document.createElement("button");return l.type="button",l.className="ghost-btn danger",l.textContent="Reset",l.disabled=!e.baseURL,l.addEventListener("click",(()=>un(t))),i.appendChild(l),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===v)continue;const o=`byok:${t.id}`,s=n.find((e=>e.provider===o))||{provider:o,baseURL:"",configured:!1,keyMask:null};r.settingsList.appendChild(on({provider:o,name:`BYOK: ${t.label||t.id}`,cfg:s,onSave:e=>dn(o,e),onRemove:()=>un(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),r.settingsList.appendChild(e)}}catch{}try{await async function(e){if(!r.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 l=document.createElement("div");l.className="setting-row",l.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)}l.appendChild(e),c.setAttribute("list","user-model-providers")}l.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,l.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();r.settingsHint.textContent="adding…";try{const o=await t.userModels.add(e,n);r.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 an(),await en(r.classSelect.value)}catch(e){r.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 y=document.createElement("div");y.className="setting-status",y.id="user-model-discovered",y.hidden=!0,p.addEventListener("click",(async()=>{const e=c.value.trim();if(!e)return void(r.settingsHint.textContent="type a provider id first (the CLI's /byok lists them).");if("function"!=typeof t.userModels.discover)return void(r.settingsHint.textContent="this build cannot ask a provider — type the model id.");let n;r.settingsHint.textContent=`asking ${e}…`,y.hidden=!0,y.textContent="";try{n=await t.userModels.discover(e)}catch(e){return void(r.settingsHint.textContent=`${e&&e.message?e.message:e}`)}if(!n||!n.ok)return void(r.settingsHint.textContent=`${e}: ${n&&n.error||"no answer"}`);r.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],y.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()=>{r.settingsHint.textContent=`adding ${n.count}…`;try{const e=await t.userModels.addAll(n.provider,n.ids);r.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 an(),await en(r.classSelect.value)}catch(e){r.settingsHint.textContent=`${e&&e.message?e.message:e}`}})),y.appendChild(e)}else y.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(", ")}`,y.appendChild(e)}y.hidden=!1})),l.appendChild(u),l.appendChild(y);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)",l.appendChild(h),a.appendChild(l);const f=Object.keys(o).sort();for(const e of f)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 l=document.createElement("div");l.className="setting-status",l.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(l);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()=>{r.settingsHint.textContent="removing…";try{const o=await t.userModels.remove(e,n);r.settingsHint.textContent=o&&!1===o.removed?`${e}:${n} was not declared.`:`removed ${e}:${n}.`,await an(),await en(r.classSelect.value)}catch(e){r.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)}r.settingsList.appendChild(a)}(e)}catch(e){r.settingsHint.textContent=`your own models: ${e&&e.message?e.message:e}`}try{await rn()}catch(e){r.customStatus&&(r.customStatus.textContent=`custom provider: ${e&&e.message?e.message:e}`)}}async function rn(){if(!r.customBaseUrl)return;let e=null,n=[];try{const n=await t.settings.get()||[],o=(Array.isArray(n)?n:[]).find((e=>e&&e.provider===`byok:${v}`));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[v])?o[v]:[]}catch{}!function(e,t){if(!r.customBaseUrl)return;const n=e||{},o=Array.isArray(t)?t:[];if(!r.customBaseUrl.value&&n.baseURL&&(r.customBaseUrl.value=n.baseURL),r.customKey&&(r.customKey.placeholder=n.configured?`key ${n.keyMask||"••••"} (blank = keep)`:"sk-…",r.customKey.value=""),r.customRemove&&(r.customRemove.disabled=!n.configured&&!n.baseURL),!r.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"),r.customStatus.textContent=s.join(" · ")}(e,n)}async function ln(){if(!r.customBaseUrl)return;const e=String(r.customBaseUrl.value||"").trim(),n=r.customKey?String(r.customKey.value||"").trim():"",o=r.customModel?String(r.customModel.value||"").trim():"",s=e=>{r.customStatus&&(r.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:${v}`;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(v,o)}catch(e){return s(`endpoint saved, model NOT declared: ${e&&e.message?e.message:e}`),await rn(),void await en(r.classSelect.value).catch((()=>{}))}r.customModel&&(r.customModel.value=""),s(`saved ${e} with model ${o} — pick it under provider "byok", then the model.`),await rn(),await an(),await en(r.classSelect.value).catch((()=>{}))}async function cn(){if(!r.customBaseUrl)return;const e=e=>{r.customStatus&&(r.customStatus.textContent=e)};e("removing…");let n=0;try{const e=await t.userModels.get(),o=e&&e.map||{},s=Array.isArray(o[v])?o[v]:[];for(const e of s)await t.userModels.remove(v,e),n+=1}catch{}try{await t.settings.remove(`byok:${v}`)}catch(t){return void e(`remove failed: ${t&&t.message?t.message:t}`)}r.customBaseUrl&&(r.customBaseUrl.value=""),e(`removed the custom endpoint${n?` and ${n} declared model(s)`:""}.`),await rn(),await an(),await en(r.classSelect.value).catch((()=>{}))}async function dn(e,n){r.settingsHint.textContent="saving…";try{const o={};n&&(o.key=n),await t.settings.set(e,o),r.settingsHint.textContent="saved.",await an(),await en(r.classSelect.value)}catch(e){r.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function un(e){r.settingsHint.textContent="removing…";try{await t.settings.remove(e),r.settingsHint.textContent="removed.",await an(),await en(r.classSelect.value)}catch(e){r.settingsHint.textContent=`remove failed: ${e&&e.message?e.message:e}`}}const mn=["sessions","memory"];let pn="sessions";function yn(e){const t=mn.includes(e)?e:"sessions";pn=t;for(const e of mn){const n="sessions"===e?r.paneSessions:r.paneMemory,o="sessions"===e?r.tabSessions:r.tabMemory,s=e===t;n&&(n.hidden=!s),o&&(o.setAttribute("aria-selected",s?"true":"false"),o.classList.toggle("is-active",s))}}async function hn(){r.sessionsList.innerHTML="",r.sessionsHint.textContent="";let e=[];try{const t=await n.listSessions();e=t&&t.sessions||[]}catch(e){return void(r.sessionsHint.textContent=`list failed: ${e&&e.message?e.message:e}`)}if(!e.length){const e=document.createElement("li");return e.className="empty",e.textContent="no sessions yet",void r.sessionsList.appendChild(e)}for(const t of e){const e=document.createElement("li");e.className="session-row",e.tabIndex=0;const n=document.createElement("span");n.className="session-title",n.textContent=t&&t.title||t&&t.id||"untitled",e.appendChild(n);const o=document.createElement("span");o.className="session-meta";const s=t&&Array.isArray(t.messages)&&t.messages.length||0,a=t&&t.updatedAt?new Date(t.updatedAt).toLocaleTimeString():"";o.textContent=`${s} msg${1===s?"":"s"}${a?" · "+a:""}`,e.appendChild(o),e.addEventListener("click",(()=>Cn(t.id))),r.sessionsList.appendChild(e)}}function fn(e){if(!r.syncStatus)return;if(!e)return void(r.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}`),r.syncStatus.textContent=t.join(" · ")}async function gn(){try{fn(await n.status())}catch{fn(null)}}function vn(){"function"==typeof n.auto&&n.auto().then((e=>{e&&e.upgrade&&it(r.sessionsHint,e.upgrade,"queued memory is waiting on the free-plan cap","See what Pro covers →")})).catch((()=>{}))}async function kn(){r.syncNow.disabled=!0,r.sessionsHint.textContent="syncing…";try{const e=await n.push(),t=await n.pull();e.upgrade||t.upgrade?it(r.sessionsHint,e.upgrade||t.upgrade,"queued memory is waiting on the free-plan cap","See what Pro covers →"):e.ok||t.ok?r.sessionsHint.textContent=`synced (pushed ${e.pushed||0}, pulled ${t.merged||0})`:r.sessionsHint.textContent=`sync failed: ${e.reason||t.reason||"unknown error"}`}catch(e){r.sessionsHint.textContent=`sync failed: ${e&&e.message?e.message:e}`}finally{r.syncNow.disabled=!1,await gn(),await hn()}}function Cn(e){n.open(e).then((e=>{if(!e)return void(r.sessionsHint.textContent="session not found");r.messages.innerHTML="";const t=Array.isArray(e.messages)?e.messages:[];t.length||qt();for(const n of t){const t="assistant"===n.role?"assistant":"system"===n.role?"system":"user";Ft(t,n.content||n.text||"",void 0,"assistant"===t?e.id:void 0)}T=e.id,D.set(e.id,rollMessages(t)),K(e.id),R=replayHistory(t),r.sessionsHint.textContent=`opened ${e.id.slice(0,8)}…`})).catch((e=>{r.sessionsHint.textContent=`open failed: ${e&&e.message?e.message:e}`}))}function bn(t){const n=T;n?e.exportSession(n,t).then((e=>{e&&e.ok?r.sessionsHint.textContent=`exported to ${e.filePath}`:e&&e.canceled||(r.sessionsHint.textContent=`export failed: ${e&&e.reason||"unknown error"}`)})).catch((e=>{r.sessionsHint.textContent=`export failed: ${e&&e.message?e.message:e}`})):r.sessionsHint.textContent="no open session to export"}function wn(){W(),T&&t.clearApprovals(T).catch((()=>{})),qt(),r.sessionsHint.textContent="",I=null,B=null,Y=null,z=null,T=null,R=[],G=0,K(null)}function xn(e){e&&("open"===e.action&&e.sessionId?Cn(e.sessionId):"new"===e.action&&(wn(),e.prompt&&(r.prompt.value=e.prompt,r.prompt.focus())))}async function Sn(){const e=r.prompt.value.trim(),o=En.length?En.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||r.send.disabled)return;const s=r.classSelect.value,a=oe();r.prompt.value="";const i=(l=En,Array.isArray(l)&&l.length?l.map((e=>`📎 ${e.name||e.path}`)).join("\n"):"");var l;const c=i?e?`${e}\n${i}`:i:e;En=[],$n=[],An();const d=++V;Y=d,z=null,Ft("user",c);const u=s===h&&te(),m=ie(),p=budgetFor(a,void 0,m),y=u&&parseInt(r.autonomousWorkers.value,10)||void 0;T||(T=Xt());const f=T;B=f,Ut();const g=replayHistory(R);R.push({role:"user",content:o&&!Ln()?Tn(e,o):c}),_t(!0,{cancellable:!0}),I&&K(f,{prompt:e,reply:"",reasoning:""}),X({force:!0});try{await n.append(f,{role:"user",content:c})}catch{}let v="",k="",C=0;const b=[];let w=null;const x=(S=()=>{if(!I)return;if(I.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}(I);e.textContent!==k&&(e.textContent=k)}const t=I.querySelector(".body");t&&t.textContent!==v&&(t.textContent=v);const n=v.length+k.length+4*C;liveMeterDue(w,n)&&(w=n,K(f,{prompt:e,reply:v,reasoning:k,measuredReasoningTokens:C})),X()},J?J.paint(S):S);var S;const E=e=>{if(e&&"number"==typeof e.thinkingTokens&&e.thinkingTokens>0)return C+=e.thinkingTokens,void x();if(e&&"string"==typeof e.reasoning&&e.reasoning)return k+=e.reasoning,void x();if(e&&"string"==typeof e.note&&e.note){const t=Pt();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 X()}if(e&&e.approval){const t=Pt();return t.classList.remove("pending"),Jt(t,e.approval,".body"),void X({force:!0})}if(e&&e.rounds){const n=Pt();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,l=document.createElement("div");l.className="approval-card rounds-card",l.dataset.roundsAskId=n.id;const c=document.createElement("div");c.className="approval-title",c.textContent="Round limit reached — keep going?",l.appendChild(c);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.)`,l.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;l.classList.add("resolved");const o=document.createElement("div");o.className="approval-decision",o.textContent=e?`Continuing — ${a} more rounds`:"Stopped — the work is held",l.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)),l.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(l)}(n,e.rounds,".body"),void X({force:!0})}if(e&&e.tool){if("run"===e.tool.phase)return void Wt(e.tool);b.push(e.tool);const t=Pt();return t.classList.remove("pending"),Yt(t,e.tool,"tool-activity",".body"),void X()}const n=e&&("string"==typeof e.delta?e.delta:e.content);n&&(v+=n,x())};try{const i=await t.chat({class:s,prompt:e,model:a,maxTokens:p,sessionId:f,autonomous:u,effort:m,workers:y,messages:g,attachments:o,roundsAsk:!0},E);if(i&&i.aborted){const e=new Error(i.message||"This operation was aborted");throw e.name="AbortError",e.code="ABORT_ERR",e}const l=i&&i.choices&&i.choices[0]||{},c=l.message&&l.message.content||v||"(empty response)";isPlaceholderContent(c)||R.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=U.find((t=>t.class===e));return t?t.label:e}(s)),u?d.push(`autonomous (${m}, ${y||"auto"}w)`):m&&d.push(`effort: ${m}`);const h=turnAccounting(i&&i.usage,a,{costUsd:i&&"number"==typeof i.costUsd?i.costUsd:void 0}),C=displayTokens(h);if(null!=C)d.push(`tokens: ${C}`);else{const t=estimatedBuckets(e,c,c===k?"":k);t&&t.output>0&&d.push(`~${t.output} tokens`)}const w=feeBillable(function(){const e="undefined"!=typeof state?state:null;return e&&e.entitlement?e.entitlement:null}());null!=h.cost&&w&&d.push(fmtCost(h.cost,h.real)),"byok"===s&&null!=h.cost&&w&&d.push("your provider bill (est.) + AEGIS handling fee");const x=F(f,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:!w});S&&d.push(`session: ${S}`),Ft("assistant",c,d.join(" · ")||void 0,f,b);try{await n.append(f,{role:"assistant",content:c,...P(i&&i.usage,a,h,{prompt:e,reply:c,reasoning:c===k?"":k,calls:i&&i.calls})}),await n.save({id:f,title:e.slice(0,60)}),"function"==typeof n.nameSession&&n.nameSession({sessionId:f,prompt:e,class:s,model:a}).then((e=>{e&&hn().catch((()=>{}))})).catch((()=>{}))}catch{}vn(),function(){const e=r.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",(()=>{Kt(j[G%j.length],a,e)})),a.appendChild(i),t.appendChild(n),t.appendChild(a),r.messages.appendChild(t);for(const t of j.slice(0,2))Kt(t,a,e)}({prompt:e,cls:s,model:a,maxTokens:p,parentSessionId:f})}catch(t){if(isCancellation(t,{userStopped:z===d})){const t=salvageTurn({streamedText:v,reasoningText:k}),o=t.text,s=t.reasoning,i=replayableContent(t.kind,o);R.push({role:"assistant",content:i});const r=turnAccounting(void 0,a,{}),l=F(f,void 0,{model:a,prompt:e,reply:o,reasoning:s}),c=["stopped by you"];"reasoning-only"===t.kind&&c.push("reasoning only");const d=displayTokens(r);if(null!=d)c.push(`tokens: ${d}`);else{const t=estimatedBuckets(e,o,s);t&&t.output>0&&c.push(`~${t.output} tokens`)}const u=fmtRoll(l);u&&c.push(`session: ${u}`),Ft("assistant",o,c.join(" · "),f,b);try{await n.append(f,{role:"assistant",content:i,...P(void 0,a,r,{prompt:e,reply:o,reasoning:s})})}catch{}vn()}else Ft("assistant",`Error: ${t&&t.message?t.message:t}`,"request failed")}finally{_t(!1),Y===d&&(Y=null,B=null),hn()}}let En=[],$n=[],qn=0;function Ln(){return r.classSelect&&"pro"===r.classSelect.value}function An(){const e=r.attachRow,t=r.attachNote;if(!e)return;e.textContent="";const n=En.length+$n.length;if(e.hidden=0===n,t&&(t.hidden=!0,t.textContent=""),n){for(const t of En){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} · ${Nn(t.size)}${t.truncated?" (truncated)":""}`,n.appendChild(s),n.appendChild(Mn((()=>{En=En.filter((e=>e!==t)),An()}))),e.appendChild(n)}for(const t of $n){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(Mn((()=>{$n=$n.filter((e=>e!==t)),An()}))),e.appendChild(n)}if(t&&Ln()){const e=En.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 Mn(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 Nn(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 Hn(t){const n=(t||"").split(/[\\/]/).pop()||t;if(En.length>=8)return $n.push({path:t,name:n,reason:"at most 8 files per message"}),void An();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 $n.push({path:t,name:n,reason:o&&o.reason||"not attached"}),void An();En.some((e=>e.path===o.attachment.path))||(En.push(o.attachment),An())}const In=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Bn(e){if(e&&"string"==typeof e.mime&&e.mime)return e.mime;const t=e&&"string"==typeof e.dataUrl?e.dataUrl:"",n=/^data:([^;,]+)[;,]/.exec(t);return n?n[1].toLowerCase():""}function Tn(e,t){const n=[],o="string"==typeof e?e:"";o.trim()&&n.push({type:"text",text:o});for(const e of t||[]){const t=Bn(e);"image"===e.kind&&e.dataUrl&&In.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}async function Rn(){try{de(await e.status())}catch{de(null)}"on"===localStorage.getItem(d)&&(r.autonomousToggle.checked=!0),r.autonomousToggle.addEventListener("change",(()=>{localStorage.setItem(d,r.autonomousToggle.checked?"on":"off"),ne()}));const n=localStorage.getItem(u)||localStorage.getItem("aegis.autonomousEffort"),i=Array.from(r.effortSelect.options).some((e=>e.value===n));n&&i?r.effortSelect.value=n:n&&localStorage.setItem(u,r.effortSelect.value),r.effortSelect.addEventListener("change",(()=>{localStorage.setItem(u,r.effortSelect.value),se(r.classSelect.value)}));const y=localStorage.getItem(m);y&&(r.autonomousWorkers.value=y),r.autonomousWorkers.addEventListener("change",(()=>{localStorage.setItem(m,r.autonomousWorkers.value)})),ne();const h=localStorage.getItem(p);r.exploreToggle.checked="on"===h,r.exploreToggle.addEventListener("change",(()=>{localStorage.setItem(p,r.exploreToggle.checked?"on":"off"),r.exploreToggle.checked||W()})),r.classSelect.addEventListener("change",(()=>{localStorage.setItem(l,r.classSelect.value),se(r.classSelect.value),en(r.classSelect.value)})),r.modelSelect.addEventListener("change",(()=>{const e=O.get(r.modelSelect.value),t=maxTokensCeiling(e),n=r.modelHint.textContent.replace(/ · max output: [\d,]+$/,"");r.modelHint.textContent=t<FLAT_CEILING?`${n} · max output: ${t.toLocaleString()}`:n,se(r.classSelect.value),"byok"===r.classSelect.value&&e&&e.provider&&!1===e.configured&&function(e){if(!r.settingsList||!e)return;const t=r.settingsList.querySelector(`.setting-row[data-provider="byok:${e}"] input[type="password"]`);if(Mt(r.settingsList),t&&t.focus(),r.modelHint){const t=r.modelHint.textContent.replace(/ — no .* key saved; add it below\.$/,"");r.modelHint.textContent=`${t} — no ${e} key saved; add it below.`}}(e.provider)})),r.modelFree.addEventListener("input",(()=>{se(r.classSelect.value)})),r.newChat.addEventListener("click",wn),e.onMenuNewChat&&e.onMenuNewChat(wn),e.onMenuSearch&&e.onMenuSearch(ht),e.onMenuFingerprint&&e.onMenuFingerprint((()=>{Ve&&"function"==typeof Ve.open&&Ve.open()})),e.onMenuGoogleDrive&&e.onMenuGoogleDrive((()=>{Ve&&"function"==typeof Ve.open&&Ve.open({focus:"drive"})})),e.onMenuExportMarkdown&&e.onMenuExportMarkdown((()=>bn("markdown"))),e.onMenuExportJson&&e.onMenuExportJson((()=>bn("json"))),e.onDeepLink&&e.onDeepLink(xn),e.onQuickLauncherPush&&e.onQuickLauncherPush(Fe),r.sessionsRefresh.addEventListener("click",hn),r.syncNow.addEventListener("click",kn),r.sessionsExport.addEventListener("click",(()=>bn("markdown"))),r.apiKeySave.addEventListener("click",Ce),r.apiKeyVerify.addEventListener("click",be),r.apiKeyInput.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),Ce())})),r.customSave&&r.customSave.addEventListener("click",ln),r.customRemove&&r.customRemove.addEventListener("click",cn);for(const e of[r.customBaseUrl,r.customKey,r.customModel])e&&e.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),ln())}));r.upgradePlan.addEventListener("click",(()=>ve("upgrade"))),r.topupBtn.addEventListener("click",(()=>ve("topup"))),attachScrollLift({panes:document.querySelectorAll(".messages, .side, .memory-scroll"),target:document.body,requestFrame:e=>window.requestAnimationFrame(e)}),r.quickLauncherSave.addEventListener("click",xe),r.quickLauncherShortcut.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),xe())})),r.confirmMode&&r.confirmMode.addEventListener("change",(()=>$e(r.confirmMode.checked))),r.autoMode&&r.autoMode.addEventListener("click",(()=>{r.confirmMode&&$e(!r.confirmMode.checked)})),r.composer.addEventListener("submit",(e=>{e.preventDefault(),Sn()})),r.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"))&&(qn+=1,document.body.classList.add("is-dropping"))})),window.addEventListener("dragleave",(()=>{qn=Math.max(0,qn-1),0===qn&&document.body.classList.remove("is-dropping")})),window.addEventListener("dragover",(e=>{e.dataTransfer&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")})),window.addEventListener("drop",(t=>{qn=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 Hn(n):($n.push({name:t.name||"file",reason:"no path available"}),An())}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=r.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 l=(s+i+e).length;try{t.setSelectionRange(l,l)}catch{}t.focus()}(s))}(t).catch((()=>{}))})),document.addEventListener("dragover",(e=>e.preventDefault())),document.addEventListener("drop",(e=>e.preventDefault())),r.classSelect&&r.classSelect.addEventListener("change",An),An()),r.prompt.addEventListener("keydown",(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),r.composer.requestSubmit())})),r.tabSessions&&r.tabSessions.addEventListener("click",(()=>yn("sessions"))),r.tabMemory&&r.tabMemory.addEventListener("click",(()=>yn("memory"))),r.memorySearchForm.addEventListener("submit",(e=>{e.preventDefault(),ct(r.memoryQuery.value.trim())})),r.memorySaveBtn.addEventListener("click",vt),r.memoryImportBtn.addEventListener("click",gt),r.memoryOpen&&r.memoryOpen.addEventListener("click",ht),r.memoryClose&&r.memoryClose.addEventListener("click",ft),r.memoryBackdrop&&r.memoryBackdrop.addEventListener("click",ft),r.memoryOverlaySave&&r.memoryOverlaySave.addEventListener("click",vt),r.memoryFilters&&r.memoryFilters.addEventListener("submit",(e=>{e.preventDefault(),je.query=r.memoryOverlayQuery.value.trim(),yt(je.query)})),r.memoryFiltersClear&&r.memoryFiltersClear.addEventListener("click",(()=>{r.memoryOverlayQuery.value="",je.query="",je.source="",je.role="",pt()})),r.keysClose&&r.keysClose.addEventListener("click",Ut),r.keysBackdrop&&r.keysBackdrop.addEventListener("click",Ut),r.keysDismiss&&r.keysDismiss.addEventListener("click",Ot),r.keysGotoAegis&&r.keysGotoAegis.addEventListener("click",(()=>{Ut(),Mt(r.apiKeyInput),r.apiKeyInput&&r.apiKeyInput.focus(),r.apiKeyHint&&(r.apiKeyHint.textContent=`Missing: ${function(){const e=[];return!0!==le&&e.push("the AEGIS key"),!0!==ce&&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.`)})),r.keysGotoByok&&r.keysGotoByok.addEventListener("click",(()=>{Ut(),Nt()})),s&&(r.queueEnqueue&&r.queueEnqueue.addEventListener("click",Ie),r.queueDrain&&r.queueDrain.addEventListener("click",(()=>Be("one"))),r.queueProceed&&r.queueProceed.addEventListener("click",(()=>Be("all"))),r.queueStop&&r.queueStop.addEventListener("click",Te),"function"==typeof s.onProgress&&s.onProgress(De),r.queueClassSelect&&r.queueClassSelect.addEventListener("change",(()=>{localStorage.setItem(c,r.queueClassSelect.value),nn(r.queueClassSelect.value)})),await He(),await async function(){if(!r.queueClassSelect)return;let e=[];try{e=await t.listClasses()||[]}catch(t){e=[],r.queueModelHint&&(r.queueModelHint.textContent=`listClasses failed: ${t&&t.message?t.message:t}`)}r.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)`,r.queueClassSelect.appendChild(e)}const n=localStorage.getItem(c);n&&e.some((e=>e.class===n))&&(r.queueClassSelect.value=n),await nn(r.queueClassSelect.value)}()),a&&(r.queueAuto&&r.queueAuto.addEventListener("change",(()=>Oe(r.queueAuto.checked))),r.queueAutoInterval&&r.queueAutoInterval.addEventListener("change",(()=>{r.queueAuto&&r.queueAuto.checked&&Oe(!0)})),await async function(){if(!a||"function"!=typeof a.status)return null;try{const e=await a.status();return Ue(e),e}catch(e){return r.queueAutoHint&&(r.queueAutoHint.textContent=`automation status unavailable: ${e&&e.message?e.message:e}`),null}}()),J=createTranscriptView({messages:r.messages,requestFrame:e=>requestAnimationFrame(e)}),J.attachScrollVeto();let f=null;window.__aegisSmoke=Object.freeze({isScrolledUp:()=>J.isScrolledUp(),metrics:()=>J.metrics(),escapeDecision:()=>f&&"function"==typeof f.lastDecision?f.lastDecision():null,stopOutcome:()=>Z}),f=bindEscapeInterrupt({doc:document,isOverlayOpen:Ge,onOverlayEscape:()=>{if(We())Ut();else{if(Ve&&"function"==typeof Ve.close)try{return void Ve.close()}catch(e){}ft()}},hasPendingTurn:()=>!!B,stopTurn:ee}),r.accountBanner&&e.onAccountStatus&&(e.onAccountStatus(he),e.accountStatus().then(he).catch((e=>console.warn("account status unavailable",e))),r.accountRetryBtn.addEventListener("click",(()=>fe(r.accountRetryBtn))),r.keysAccountRetry&&r.keysAccountRetry.addEventListener("click",(()=>fe(r.keysAccountRetry)))),r.updateBanner&&e.onUpdateStatus&&(e.onUpdateStatus(pe),e.updateStatus().then(pe).catch((()=>{})),r.updateDownloadBtn.addEventListener("click",(()=>{r.updateDownloadBtn.disabled=!0,Promise.resolve(e.downloadUpdate()).then((e=>{e&&e.status&&pe(e)})).catch((()=>{})).finally((()=>{r.updateDownloadBtn.disabled=!1}))})),r.updateRestartBtn.addEventListener("click",(()=>{e.quitAndInstallUpdate()})),r.updateRetryBtn&&e.checkForUpdates&&r.updateRetryBtn.addEventListener("click",(()=>{r.updateRetryBtn.disabled=!0,Promise.resolve(e.checkForUpdates()).then(pe).catch((()=>{})).finally((()=>{r.updateRetryBtn.disabled=!1}))})),r.updateLaterBtn.addEventListener("click",(()=>{me=ue&&ue.status,r.updateBanner.hidden=!0}))),r.messages.querySelector(".msg, .chatflow")||qt(),await Zt(),await an(),await async function(){if(o)try{we(await o.status())}catch(e){r.quickLauncherHint.textContent=`status failed: ${e&&e.message?e.message:e}`}}(),await async function(){if(r.confirmMode&&e.getConfirmMode)try{Se(await e.getConfirmMode())}catch(e){r.confirmModeHint.textContent=`status failed: ${e&&e.message?e.message:e}`}}(),await hn(),await gn(),ge(),yn("sessions"),r.memoryQuietFloor&&(r.memoryQuietFloor.textContent=String(Pe)),ct("");try{!function(){if(window.aegisProviderToolbar&&r.ptList)if(Ye=window.aegisProviderToolbar.mount({list:r.ptList,count:r.ptCount,search:r.ptSearch,hint:r.ptHint,onSelect:Xe}),r.ptRefresh&&r.ptRefresh.addEventListener("click",(()=>{Je(!0)})),"function"==typeof IntersectionObserver&&r.ptList.closest("section")){const e=new IntersectionObserver((t=>{t.some((e=>e.isIntersecting))&&(e.disconnect(),Je(!1))}));e.observe(r.ptList.closest("section"))}else Je(!1)}()}catch(e){r.ptHint&&(r.ptHint.textContent=`provider list unavailable: ${e&&e.message||e}`)}if(r.companionDismiss&&r.companionDismiss.addEventListener("click",(()=>{localStorage.setItem(Ze,JSON.stringify({day:window.aegisCompanion?window.aegisCompanion.dayKey(new Date):"",id:r.companionCard.dataset.messageId||""})),r.companionCard.hidden=!0})),tt(),window.aegisFingerprint)try{Ve=window.aegisFingerprint.mount({api:e,getSessionId:()=>T}),Ve.refresh().catch((()=>{}))}catch(e){const t=r.fpCardStatus;t&&(t.textContent=`authorship panel unavailable: ${e&&e.message||e}`)}}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",Rn):Rn()}();
|