aegisone 1.0.42 → 1.0.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +1 -1
- package/scripts/predist.mjs +1 -1
- package/vendor/cli/package.json +1 -1
- package/vendor/cli/src/chatflow.js +1 -1
- package/vendor/cli/src/commands.js +2 -2
- package/vendor/cli/src/limits.js +1 -1
- package/vendor/cli/src/permissions.js +4 -0
- package/vendor/cli/src/provenance.lock.json +2 -2
- package/vendor/cli/vendor/desktop/lib/local/check-command.js +3 -0
- package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/perm-store.js +7 -2
- package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/repeat-guard.js +3 -0
- package/vendor/cli/vendor/desktop/lib/local/tools.js +185 -1
- package/vendor/cli/vendor/desktop/lib/local/verify-stop.js +3 -0
- package/vendor/cli/vendor/desktop/main.js +133 -32
- package/vendor/desktop/lib/local/check-command.js +3 -0
- package/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/lib/local/perm-store.js +7 -2
- package/vendor/desktop/lib/local/prompt.js +1 -1
- package/vendor/desktop/lib/local/repeat-guard.js +3 -0
- package/vendor/desktop/lib/local/tools.js +185 -1
- package/vendor/desktop/lib/local/verify-stop.js +3 -0
- package/vendor/desktop/lib/sync/persist-gate.js +1 -1
- package/vendor/desktop/lib/sync/sessions.js +1 -1
- package/vendor/desktop/main.js +133 -32
- package/vendor/desktop/package.json +3 -2
- package/vendor/desktop/preload.js +1 -1
- package/vendor/desktop/renderer/app.js +3 -3
- package/vendor/desktop/renderer/index.html +43 -15
- package/vendor/desktop/renderer/library.js +3 -0
- package/vendor/desktop/renderer/style.css +149 -0
- package/vendor/desktop/vendor/faces/cli/package.json +1 -1
- package/vendor/desktop/vendor/faces/cli/src/chatflow.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/commands.js +2 -2
- package/vendor/desktop/vendor/faces/cli/src/limits.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/permissions.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/provenance.lock.json +2 -2
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/check-command.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-store.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/repeat-guard.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/verify-stop.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +3 -3
- package/vendor/desktop/vendor/sandbox/provenance.json +7 -7
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";!function(){const e=window.aegis,t=window.models,n=window.sync,o=window.quickLauncher,s=window.queue,a=window.auto,i="nexus",r="Nexus — auto-route";if(!e||!t)throw document.body.textContent="This page must run inside the AEGIS Electron host (window.aegis/window.models missing).",new Error("window.aegis/window.models unavailable — not running under Electron");const l={updateBanner:"update-banner",updateBannerText:"update-banner-text",updateDownloadBtn:"update-download-btn",updateRestartBtn:"update-restart-btn",updateRetryBtn:"update-retry-btn",updateLaterBtn:"update-later-btn",accountBanner:"account-banner",accountBannerText:"account-banner-text",accountRetryBtn:"account-retry-btn",keysAccount:"keys-account",keysAccountRetry:"keys-account-retry",connDot:"conn-dot",connText:"conn-text",app:"st-app",client:"st-client",base:"st-base",key:"st-key",plan:"st-plan",balance:"st-balance",upgradePlan:"upgrade-plan",topupBtn:"topup-btn",topupAmount:"topup-amount",billingHint:"billing-hint",apiKeyInput:"api-key-input",apiKeySave:"api-key-save",apiKeyVerify:"api-key-verify",apiKeyHint:"api-key-hint",classSelect:"class-select",modelSelect:"model-select",providerMark:"provider-mark",ptSearch:"pt-search",ptRefresh:"pt-refresh",ptList:"pt-list",ptCount:"pt-count",ptHint:"pt-hint",companionCard:"companion-card",companionText:"companion-text",companionDismiss:"companion-dismiss",modelFree:"model-input",budgetHint:"budget-hint",autonomousToggle:"autonomous-toggle",autonomousToggleWrap:"autonomous-toggle-wrap",autonomousControls:"autonomous-controls",effortSelect:"effort-select",autonomousWorkers:"autonomous-workers",modelHint:"model-hint",settingsList:"settings-list",settingsHint:"settings-hint",customBaseUrl:"custom-base-url",customKey:"custom-key",customModel:"custom-model",customSave:"custom-save",customRemove:"custom-remove",customStatus:"custom-status",quickLauncherEnabled:"quick-launcher-enabled",quickLauncherShortcut:"quick-launcher-shortcut",quickLauncherSave:"quick-launcher-save",quickLauncherHint:"quick-launcher-hint",permRulesList:"perm-rules-list",permRulesForm:"perm-rules-form",permRulesInput:"perm-rules-input",permRulesListSelect:"perm-rules-list-select",permRulesAdd:"perm-rules-add",permRulesStatus:"perm-rules-status",permRulesHint:"perm-rules-hint",sandboxMode:"sandbox-mode-select",sandboxNetwork:"sandbox-network-toggle",sandboxStatus:"sandbox-policy-status",confirmMode:"confirm-mode-toggle",confirmModeHint:"confirm-mode-hint",planMode:"plan-mode-toggle",planModeHint:"plan-mode-hint",autoMode:"auto-mode-toggle",autoModeLabel:"auto-mode-label",autoModeHint:"auto-mode-hint",sessionsRefresh:"sessions-refresh",sessionsExport:"sessions-export",sessionsList:"sessions-list",sessionsHint:"sessions-hint",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",importSessionBtn:"import-session-btn",importOverlay:"import-overlay",importBackdrop:"import-backdrop",importClose:"import-close",importHint:"import-hint",importList:"import-list",importCount:"import-count",importSync:"import-sync",importSessionsBtn:"import-sessions-btn",importMemoryBtn:"import-memory-btn",memoryHint:"memory-hint",memoryOpen:"memory-open",memoryBox:"memory-box",memoryQuiet:"memory-quiet",memoryQuietFloor:"memory-quiet-floor",paneTabs:"pane-tabs",tabSessions:"tab-sessions",tabMemory:"tab-memory",paneSessions:"pane-sessions",paneMemory:"pane-memory",memoryOverlay:"memory-overlay",memoryBackdrop:"memory-backdrop",memoryClose:"memory-close",memoryFilters:"memory-filters",memoryOverlayQuery:"memory-overlay-query",memoryFiltersClear:"memory-filters-clear",memoryChips:"memory-chips",memoryList:"memory-list",memoryCount:"memory-count",memoryOverlayEntry:"memory-overlay-entry",memoryOverlaySave:"memory-overlay-save",sessionOverlay:"session-overlay",sessionBackdrop:"session-backdrop",sessionClose:"session-close",sessionFilters:"session-filters",sessionQuery:"session-query",sessionClear:"session-clear",sessionHint:"session-hint",sessionList:"session-list",sessionCount:"session-count",creditsOverlay:"credits-overlay",creditsBackdrop:"credits-backdrop",creditsClose:"credits-close",creditsBody:"credits-body",creditsStatus:"credits-status",creditsLicenceTag:"credits-licence-tag",fpCardStatus:"fp-card-status",fpOpen:"fp-open",fpOverlay:"fp-overlay",messages:"messages",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"},c={};for(const[e,t]of Object.entries(l))Object.defineProperty(c,e,{get:()=>document.getElementById(t),enumerable:!0,configurable:!0});const d="aegis.class",u="aegis.queueClass",m="aegis.autonomous",p="aegis.effort",y="aegis.autonomousWorkers",f="aegis.explore",h="aegis.welcomeConnectDismissed",g="aegis",v=new Set(["__aegis","aegis"]),k="local",C="custom",b="http://localhost:11434",w="https://aegiscloud.org/key?s=desktop&c=key_prompt",x="The autonomous queue keeps running after you close the laptop.",S="https://aegiscloud.org",E=/^[a-z0-9][a-z0-9_-]{0,63}$/;function $(e,t){const n=new URL(`${S}/go/${e}`);n.searchParams.set("s","desktop");const o=null==t?"":String(t).trim().toLowerCase();return E.test(o)&&n.searchParams.set("c",o),n.toString()}function L(e){return $("upgrade",e)}function q(e){return $("topup",e)}const M={welcome_cloud:"welcome",queue_cap:"queue",memory_quota:"memory",status_card:"status",topup_bank:"topup"},A="upgrade_prompt_rendered",N="upgrade_prompt_clicked";let H=!1;function B(e,t){try{const n=M[t];if(!n)return;const o=window.aegis;if(!o||"function"!=typeof o.telemetryEvent)return;const s=o.telemetryEvent(e,{campaign:t,surface:n});s&&"function"==typeof s.catch&&s.catch((()=>{}))}catch(e){if(!H){H=!0;try{console.debug("telemetry: prompt event failed (suppressed)",e)}catch{}}}}function I(e,t,n,o){const s=document.createElement("a");return s.href=function(e,t){const n="topup_bank"===t?q(t):L(t);if(!e)return n;let o;try{o=new URL(e,S)}catch{return e}return o.origin!==S||o.searchParams.get("s")||o.searchParams.get("utm_source")?e:/topup/.test(o.pathname)?q(t):n}(t,n),s.target="_blank",s.rel="noreferrer noopener",s.textContent=o,s.addEventListener("click",(()=>B(N,n))),e.appendChild(s),!1===e.isConnected||e.hidden||B(A,n),s}let R=null,T=null,O=null,U=[],D=[],F=new Map;const P=new Map;function _(e,t,n={}){const o=e||"",s=rollTurn(function(e){const t=e||"";return P.has(t)||P.set(t,emptyRoll()),P.get(t)}(o),t,n);return P.set(o,s),K(o),s}function K(e,t){const n=c.sessionMeter,o=t?function(e){const t="string"==typeof e.reply?e.reply:"",n="string"==typeof e.reasoning?e.reasoning:"",o="number"==typeof e.measuredReasoningTokens&&e.measuredReasoningTokens>0?e.measuredReasoningTokens:0;if(!t&&!n&&!o)return"↓0 tokens";let s=0;try{const o=estimatedBuckets(e.prompt,t,n);o&&"number"==typeof o.output&&o.output>0&&(s=o.output)}catch(e){}if(!s){let e=0;for(const o of[t,n]){let t=0;for(;t<o.length;)t+=o.codePointAt(t)>65535?2:1,e+=1}s=Math.ceil(e/4)}return s+=o,s?`↓${o>0?"≥":""}${Math.round(s)} tokens`:""}(t):"",s=t?function(){if(!R)return null;let e=R.querySelector(".typing-tokens");return e||(e=document.createElement("span"),e.className="typing-tokens",e.hidden=!0,R.appendChild(e)),e}():null;if(s&&(s.textContent=o,s.hidden=!o),!n)return;if(O!==e)return void(n.hidden=!0);let a=P.get(e||"");t&&(a=rollTurn(a||emptyRoll(),void 0,{prompt:t.prompt,reply:t.reply,reasoning:t.reasoning,measuredReasoningTokens:t.measuredReasoningTokens}));const i=a?fmtRoll(a):"";return n.textContent=i,n.hidden=!i,n.classList.toggle("live",!!t&&!!i),i&&(n.title="This session, counted the way the CLI counts it — every turn rolled into one running total"),a}function j(e,t,n,o){const s=ledgerRow(e,n,{model:t,costUsd:n&&n.real&&"number"==typeof n.cost?n.cost:void 0,calls:o&&o.calls,prompt:o&&o.prompt,reply:o&&o.reply,reasoning:o&&o.reasoning}),a=s?Object.assign({},s):{};return t&&(a.model=t),a}const G="You are the exploratory half of a chat assistant. The user is reading the main answer elsewhere, so never restate it. Be concrete and brief: one lead line naming the path, then 3-5 tight bullets. Never pad.",Q=[{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 W=0;const V=new Set;function Y(){for(const e of V)try{t.cancel(e)}catch{}V.clear()}let z=0,J=null,X=null,Z=null;function ee(e){return!!Z&&Z.follow(e)}let te=null;function ne(){if(!T)return!1;if(!stopAppliesTo(J,X))return!1;X=J;const e=T;te={sessionId:e,at:Date.now(),state:"requested"};try{const n=t.cancel(e);n&&"function"==typeof n.then&&n.then((t=>{te={sessionId:e,at:Date.now(),state:"settled",accepted:!t||!1!==t.ok,result:void 0===t?null:t}}),(t=>{te={sessionId:e,at:Date.now(),state:"rejected",accepted:!1,error:t&&t.message||String(t)}}))}catch(t){te={sessionId:e,at:Date.now(),state:"threw",accepted:!1,error:t&&t.message||String(t)}}if(R){const e=R.querySelector(".cancel-btn");e&&(e.disabled=!0,e.textContent="stopping…")}return!0}function oe(){const e=c.autonomousToggle;return Boolean(e&&e.checked)}function se(){if(!c.autonomousControls)return;const e=c.autonomousToggleWrap&&!c.autonomousToggleWrap.hidden;c.autonomousControls.hidden=!(e&&oe())}function ae(){if(c.modelFree&&!c.modelFree.hidden){const e=c.modelFree.value.trim();if(e)return e}return c.modelSelect.value}function ie(e,t){const n=void 0===t?ae():t;c.budgetHint&&(c.budgetHint.textContent=function(e,t){const n=le(),o=n,s=n;return e===g?`budget: ${{low:16384,medium:32768,high:65536,max:65536}[o].toLocaleString()} tokens from effort (${s}), summed across the worker fan-out by the Aegis Cloud pool — no max_tokens is sent.`:DEEPSEEK_REASONING_MODEL_RE.test(String(t||""))?`budget: ${EFFORT_TOKEN_BUDGET[o].toLocaleString()} tokens from effort (${s}) — this model reasons against its own output budget, and the length of the answer is not predictable from the prompt.`:`no token cap is sent (effort: ${s}) — output length cannot be predicted from the prompt, so this app states no max_tokens and the provider's own limit applies.`}(e,n)),re()}function re(){if(!c.providerMark||!window.aegisProviderMark)return;const e=ae(),t="local"===(c.classSelect?c.classSelect.value:"")?"ollama":"";window.aegisProviderMark.paint(c.providerMark,e,"",t)}function le(){const e=c.effortSelect&&c.effortSelect.value;return"low"===e||"medium"===e||"max"===e?e:"high"}function ce(e,t){c.connDot.classList.toggle("ok",Boolean(e)),c.connText.textContent=t}let de=null,ue=!1;function me(e){if(!e)return de=null,ue=!1,void ce(!1,"IPC unavailable");de=Boolean(e.keyConfigured),ue=Boolean(e.providerConfigured),c.app.textContent=e.appVersion?`v${e.appVersion}`:"–",c.client.textContent=e.clientVersion||"–",c.base.textContent=e.apiBase||"–",c.key.textContent=e.keyConfigured?e.keyMask:"not set",ce(e.keyConfigured,e.keyConfigured?"key configured":"no API key"),tn(),Vt(),function(){const e=document.getElementById("keys-overlay");if(!e)return;let t=!1;try{t="on"===localStorage.getItem(cn)}catch{}t||null===de?e.hidden=!0:(dn(),Boolean(T)?un():!0!==de||!0!==ue?c.keysOverlay&&(dn(),c.keysOverlay.hidden&&(c.keysOverlay.hidden=!1,document.body.classList.add("keys-open"))):un())}()}let pe=null,ye=null;function fe(e){if(!c.updateBanner)return;pe=e;try{ut()}catch{}const t=e&&e.status;if(!t||"idle"===t||"disabled"===t||"checking"===t||"up-to-date"===t||"unavailable"===t||t===ye)return void(c.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(c.updateBanner.hidden=!0);n=`Update check failed: ${e.error||"unknown error"}`,e.transient&&(n+=" — will retry automatically."),a=!0}c.updateBannerText.textContent=n,c.updateDownloadBtn.hidden=!o,c.updateRestartBtn.hidden=!s,c.updateRetryBtn&&(c.updateRetryBtn.hidden=!a),c.updateBanner.hidden=!1}let he=null;function ge(e){he=e&&"no-key"===e.status?e.reason:null,dn(),c.accountBanner&&(he?(c.accountBannerText.textContent=`No AEGIS account key on this machine: ${he}.`,c.accountBanner.hidden=!1):c.accountBanner.hidden=!0)}function ve(t){t.disabled=!0,e.registerAccount().then((e=>{if(ge(e),!e)return be()})).catch((e=>ge({status:"no-key",reason:String(e&&e.message||e)}))).finally((()=>{t.disabled=!1}))}async function ke(){try{const t=await e.verifyApiKey();t&&t.ok?c.plan.textContent=t.valid?t.plan||"active":"invalid key":c.plan.textContent="unavailable"}catch{c.plan.textContent="unavailable"}try{const t=await e.tokenBankBalance();c.balance.textContent=t&&null!=t.balance_eur?`€${t.balance_eur}`:"–"}catch{c.balance.textContent="unavailable"}}async function Ce(t){const n=Math.round(Number(c.topupAmount&&c.topupAmount.value)||10),o="topup"===t?c.topupBtn:c.upgradePlan;if(o&&(o.disabled=!0),"topup"===t&&!1===de)return o&&(o.disabled=!1),void(c.billingHint.textContent="add your AEGIS API key above — a top-up is credited to your account");c.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?(c.billingHint.textContent=`free plan cap reached — ${n} lifts it. `,void I(c.billingHint,e.upgrade.url,"topup"===t?"topup_bank":"status_card","See plans →")):void(e.setupRequired?c.billingHint.textContent="checkout is not configured on the server yet (no Stripe price id)":c.billingHint.textContent=`${n} failed: ${e.reason||"the server returned no checkout URL"}`);c.billingHint.textContent=`add your AEGIS API key above — a ${n} needs an account`}(o||{},t);c.billingHint.textContent="opening checkout…";const s=await e.openExternal(o.url);if(s&&!1===s.ok)return void(c.billingHint.textContent=`could not open the checkout page: ${s.reason||"unknown reason"}`);c.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){c.billingHint.textContent=`billing failed: ${e&&e.message?e.message:e}`}finally{o&&(o.disabled=!1)}}async function be(){try{me(await e.status())}catch{me(null)}await Ln(),await ke()}async function we(){const t=c.apiKeyInput.value.trim();c.apiKeySave.disabled=!0,c.apiKeyVerify.disabled=!0,c.apiKeyHint.textContent="saving…";try{const n=await e.setApiKey(t);if(!n||!n.ok)throw new Error(n&&n.error||"save failed");c.apiKeyInput.value="",c.apiKeyHint.textContent=t?`saved (${n.keyMask?n.keyMask:"configured"})`:"key cleared",await be()}catch(e){c.apiKeyHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{c.apiKeySave.disabled=!1,c.apiKeyVerify.disabled=!1}}async function xe(){c.apiKeyVerify.disabled=!0,c.apiKeyHint.textContent="verifying…";try{const t=await e.verifyApiKey();if(!t||!t.ok)throw new Error(t&&t.error||"verify failed");c.apiKeyHint.textContent=t.valid?`valid (${t.plan||"active"})`:"invalid key"}catch(e){c.apiKeyHint.textContent=`verify failed: ${e&&e.message?e.message:e}`}finally{c.apiKeyVerify.disabled=!1}}function Se(e){if(!e)return;c.quickLauncherEnabled.checked=Boolean(e.enabled),c.quickLauncherShortcut.value=e.shortcut||"",c.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),c.quickLauncherHint.textContent=t.join(" · ")}async function Ee(){if(o){c.quickLauncherSave.disabled=!0,c.quickLauncherHint.textContent="saving…";try{Se(await o.setConfig({enabled:c.quickLauncherEnabled.checked,shortcut:c.quickLauncherShortcut.value.trim()}))}catch(e){c.quickLauncherHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{c.quickLauncherSave.disabled=!1}}}function $e(e){if(!c.confirmMode||!e)return;const t=!1!==e.enabled;c.confirmMode.checked=t,c.confirmModeHint.textContent=t?"On — exec, writeFile and editFile ask for your approval before they run.":"Off — the agent runs exec, writeFile and editFile without asking.",Le(t)}function Le(e){if(!c.autoMode)return;const t=!e;c.autoMode.setAttribute("aria-pressed",t?"true":"false"),c.autoMode.classList.toggle("is-auto",t),c.autoModeLabel&&(c.autoModeLabel.textContent=t?"auto mode":"ask before tools"),c.autoModeHint&&(c.autoModeHint.textContent=t?"on — tools run without asking. Click to require approval.":"off — click for auto mode, or use Settings → Tool approvals.")}async function qe(t){if(c.confirmMode){c.confirmMode.disabled=!0,c.autoMode&&(c.autoMode.disabled=!0);try{$e(await e.setConfirmMode(t))}catch(e){c.confirmMode.checked=!t,c.confirmModeHint.textContent=`save failed: ${e&&e.message?e.message:e}`,Le(c.confirmMode.checked)}finally{c.confirmMode.disabled=!1,c.autoMode&&(c.autoMode.disabled=!1)}}}function Me(e){if(!c.planMode||!e)return;const t="plan"===e.mode;c.planMode.checked=t,c.planModeHint&&(c.planModeHint.textContent=t?"On — writeFile, editFile and mutating exec calls are refused; read-only shell and search still run.":'Off — tool calls follow "confirm before running tools" above, as usual.')}const Ae=["deny","allow","ask"];function Ne(e){if(!c.permRulesList)return;c.permRulesList.innerHTML="";const t=e&&!0===e.ok,n=t&&e.rules?e.rules:null;if(!n){const n=document.createElement("li");return n.className="rules-row rules-row-muted",n.textContent=t?"no stored rules":`rules unavailable: ${e&&e.reason||"the permission store could not be read"}`,c.permRulesList.appendChild(n),void(c.permRulesHint&&(c.permRulesHint.dataset.residual=""))}let o=0;for(const e of Ae){const t=Array.isArray(n[e])?n[e]:[];for(const n of t){o+=1;const t=document.createElement("li");t.className="rules-row",t.dataset.list=e,t.dataset.rule=n;const s=document.createElement("span");s.className=`rules-tag rules-tag-${e}`,s.textContent=e,t.appendChild(s);const a=document.createElement("code");a.className="rules-pattern",a.textContent=n,t.appendChild(a);const i=document.createElement("button");i.type="button",i.className="ghost-btn danger rules-remove",i.textContent="Remove",i.addEventListener("click",(()=>He(e,n))),t.appendChild(i),c.permRulesList.appendChild(t)}}if(!o){const e=document.createElement("li");e.className="rules-row rules-row-muted",e.textContent="no stored rules",c.permRulesList.appendChild(e)}var s;c.permRulesHint&&(c.permRulesHint.textContent=`A rule is tool(pattern) — exec(npm test), exec(npm run *), writeFile(src/**). Deny beats allow. ${s=n.defaultMode,"allow"===s?"unmatched calls run without asking":"deny"===s?"unmatched calls are refused":"unmatched calls ask"}.`)}async function He(t,n){if(e.permRulesRemove)try{const o=await e.permRulesRemove(t,n);o&&!0===o.ok?(Ne(o),c.permRulesStatus&&(c.permRulesStatus.textContent=!1===o.removed?`already gone: ${n}`:`removed: ${n}`)):c.permRulesStatus&&(c.permRulesStatus.textContent=`remove failed: ${o&&o.reason||"the store refused it"}`)}catch(e){c.permRulesStatus&&(c.permRulesStatus.textContent=`remove failed: ${e&&e.message?e.message:e}`)}}const Be={"workspace-write":"Commands may write inside the open workspace and /tmp; everything else is read-only.","read-only":"Commands may write nothing at all. Every path is mounted read-only.",off:"No sandbox. Commands run with your full user permissions."};function Ie(e){if(!c.sandboxMode)return;const t=e&&"string"==typeof e.mode?e.mode:"workspace-write",n=e&&"open"===e.network?"open":"restricted";if(Array.isArray(e&&e.modes)&&e.modes.length&&Array.from(c.sandboxMode.options).map((e=>e.value)).join("\0")!==e.modes.join("\0")){c.sandboxMode.innerHTML="";for(const t of e.modes){const e=document.createElement("option");e.value=t,e.textContent=t,c.sandboxMode.appendChild(e)}}c.sandboxMode.value=t,c.sandboxNetwork&&(c.sandboxNetwork.checked="open"===n),c.sandboxStatus&&(c.sandboxStatus.textContent=e&&!1!==e.ok?function(e){const t=e&&"string"==typeof e.mode?e.mode:"workspace-write",n=e&&"open"===e.network?"open":"restricted",o=e&&"string"==typeof e.sentence?e.sentence:null,s=e?e.enforced:null;if(!1===s)return`${o||`sandbox: OFF — no mechanism available (mode ${t} is not being enforced)`}. Commands are NOT confined.`;if(null===s||!o){const e=null===s?"the sandbox probe could not be completed":"no mechanism reported";return`${Be[t]||t} Sandbox status unknown: ${e}, so this posture may not be enforced.`}return`${null!==o?o:""} ${Be[t]||t} Network: ${"open"===n?"allowed":"blocked"}.`.trim()}(e):`could not read the posture: ${e&&e.reason||"unknown error"}`)}async function Re(){if(c.sandboxMode&&e.getSandboxPolicy)try{Ie(await e.getSandboxPolicy())}catch(e){Ie({ok:!1,reason:e&&e.message||String(e)})}}async function Te(t,n){if(e.setSandboxPolicy)try{Ie(await e.setSandboxPolicy(t,n))}catch(e){c.sandboxStatus&&(c.sandboxStatus.textContent=`not saved: ${e&&e.message?e.message:e}`),Re()}}let Oe="",Ue=!1;function De(e){Oe=e||"",c.queueHint&&(c.queueHint.textContent=Oe)}function Fe(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 ${mt(e.startedAt)}`:"working"):(e.attempts&&t.push(`${e.attempts} attempt${1===e.attempts?"":"s"}`),e.created&&t.push(mt(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",(()=>Qe("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",(()=>Qe("remove",e.id))),t.appendChild(n)}return t}function Pe(e){if(!c.queueList||!e||"object"!=typeof e)return;Ue=Boolean(e.draining),c.queueCwd&&!c.queueCwd.value&&(c.queueCwd.value=e.defaultCwd||""),c.queueEnqueue&&(c.queueEnqueue.disabled=Ue),c.queueDrain&&(c.queueDrain.disabled=Ue),c.queueProceed&&(c.queueProceed.disabled=Ue),c.queueStop&&(c.queueStop.hidden=!Ue);const t=Array.isArray(e.items)?e.items:[];if(c.queueList.innerHTML="",t.length)for(const e of t)c.queueList.appendChild(Fe(e));else{const e=document.createElement("li");e.className="empty",e.textContent="queue is empty",c.queueList.appendChild(e)}const n=[];e.running?n.push(`running #${e.running.id}`):Ue&&n.push("draining…"),n.push(`${e.pending||0} pending`),e.defaultModel&&n.push(`Aegis Cloud · ${e.defaultModel}`),Ue&&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(c.queueFanout&&(c.queueFanout.disabled=!o,o||(c.queueFanout.checked=!1)),c.queueBoundary&&(c.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||"":""),c.queueUpgrade&&(c.queueUpgrade.innerHTML="",n&&!o)){const e="balance"===t.wall;I(c.queueUpgrade,t.upgradeUrl,t.campaign,e?"Top up your balance ↗":"See what Pro covers ↗")}}(e),c.queueHint&&(c.queueHint.textContent=[Oe,n.join(" · ")].filter(Boolean).join(" · "))}async function _e(){if(!s||!c.queueList)return null;try{const e=await s.list();return Pe(e),e}catch(e){return De(`queue list failed: ${e&&e.message?e.message:e}`),null}}async function Ke(){if(!s||!c.queueTask)return;const e=c.queueTask.value.trim();if(e){c.queueEnqueue&&(c.queueEnqueue.disabled=!0),De("queueing…");try{const t=await s.enqueue({task:e,cwd:c.queueCwd?c.queueCwd.value.trim():"",class:c.queueClassSelect?c.queueClassSelect.value:void 0,model:Mn(),commit:!!c.queueCommit&&c.queueCommit.checked});t&&t.ok?(c.queueTask.value="",De(`queued #${t.item.id}`)):De(t&&t.reason||"enqueue failed"),Pe(t)}catch(e){De(`enqueue failed: ${e&&e.message?e.message:e}`)}finally{c.queueEnqueue&&(c.queueEnqueue.disabled=Ue)}}else De("type a task first")}async function je(e){if(s){Ue=!0,De("one"===e?"running one task…":"draining the queue…"),c.queueDrain&&(c.queueDrain.disabled=!0),c.queueProceed&&(c.queueProceed.disabled=!0),c.queueEnqueue&&(c.queueEnqueue.disabled=!0),c.queueStop&&(c.queueStop.hidden=!1);try{const t=await("one"===e?s.drain():s.proceed());De(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)),Pe(t)}catch(e){Ue=!1,c.queueDrain&&(c.queueDrain.disabled=!1),c.queueProceed&&(c.queueProceed.disabled=!1),c.queueEnqueue&&(c.queueEnqueue.disabled=!1),c.queueStop&&(c.queueStop.hidden=!0),De(`drain failed: ${e&&e.message?e.message:e}`)}}}async function Ge(){if(s){c.queueStop&&(c.queueStop.disabled=!0),De("stopping…");try{const e=await s.stop(),t=e&&e.cancelled&&e.cancelled.ok;Oe=t?"stopped the running task":"stop requested",Pe(e)}catch(e){De(`stop failed: ${e&&e.message?e.message:e}`)}finally{c.queueStop&&(c.queueStop.disabled=!1)}}}async function Qe(e,t){if(s){De(`${e} #${t}…`);try{const n=await s[e](t);n&&!1===n.ok?De(n.reason||`${e} failed`):De(`${"retry"===e?"re-queued":"removed"} #${t}`),Pe(n)}catch(t){De(`${e} failed: ${t&&t.message?t.message:t}`)}}}function We(e){e&&"object"==typeof e&&e.drain&&function(e){if(!c.queueAuto||!e||"object"!=typeof e)return;const t=!0===e.enabled;if(c.queueAuto.checked=t,c.queueAutoInterval){c.queueAutoInterval.disabled=!t;const n=Number(e.intervalMs);Number.isFinite(n)&&(c.queueAutoInterval.value=String(n))}if(c.queueAutoLabel&&(c.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"),!c.queueAutoHint)return;if(!t)return void(c.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"),c.queueAutoHint.textContent=n.join(" · ")}(e.drain)}async function Ve(e){if(!a||"function"!=typeof a.setDrain)return;const t={enabled:Boolean(e)};c.queueAutoInterval&&c.queueAutoInterval.value&&(t.intervalMs=Number(c.queueAutoInterval.value));try{const e=await a.setDrain(t);e&&!1===e.ok&&c.queueAutoHint&&(c.queueAutoHint.textContent=e.error||"could not save that"),We(e)}catch(e){c.queueAutoHint&&(c.queueAutoHint.textContent=`could not save that: ${e&&e.message?e.message:e}`)}}function Ye(e){if(!e||"object"!=typeof e)return;const t=null==e.taskId?"":`#${e.taskId} `;if("start"===e.type)De(`${t}running${e.model?` on ${e.model}`:""}…`);else if("tool"===e.type&&e.tool)De(`${t}${wn(e.tool)}`);else if("finish"===e.type)De(`${t}${e.ok?"done":"failed"} — refreshing`),_e();else if("recovered"===e.type){const t=Array.isArray(e.ids)?e.ids:[];De(`recovered ${t.length} stalled task${1===t.length?"":"s"}`)}else"locked"===e.type?De("another drain is already running"):"queued"===e.type&&De(`queued phase ${e.phase}`)}function ze(e){const t=e&&e.prompt,o=e&&e.response;if(!t||!o)return;O||(O=$n());const s=O,a=e&&e.model||"",i=e&&e.class||"",r=i||a?[i?i.toUpperCase():"",a].filter(Boolean).join(" · "):void 0;yn("user",t),yn("assistant",o,r,s),U.push({role:"user",content:t}),U.push({role:"assistant",content:o}),n.append(s,{role:"user",content:t}).catch((()=>{})),n.append(s,{role:"assistant",content:o}).catch((()=>{}))}const Je=10,Xe=6,Ze=50,et={entries:[],query:"",source:"",role:"",error:"",upgrade:null,local:!1,loading:!1};function tt(){if(nt())return!0;if(qt())return!0;if(It())return!0;if(Dt())return!0;if(ot())return!0;if(st&&"function"==typeof st.isOpen)try{return!!st.isOpen()}catch(e){return!1}return!1}function nt(){return!!c.memoryOverlay&&!c.memoryOverlay.hidden}function ot(){return!!c.keysOverlay&&!c.keysOverlay.hidden}let st=null,at=null,it=!1;async function rt(e){if(!at)return;if(it&&!e)return;c.ptHint&&(c.ptHint.textContent="listing providers…");const n=await async function(){let e=[];try{e=await t.listClasses()||[]}catch(e){return c.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}();it=!0,at.set(n)}function lt(e){e&&e.class&&Array.from(c.classSelect.options).some((t=>t.value===e.class))&&(c.classSelect.value=e.class,localStorage.setItem(d,e.class),ie(e.class),qn(e.class).then((()=>{e.model&&Array.from(c.modelSelect.options).some((t=>t.value===e.model))&&(c.modelSelect.value=e.model,c.modelSelect.dispatchEvent(new Event("change")))})))}const ct="aegis.companion.dismissed";function dt(){const e={keyConfigured:null===de?void 0:de};return Array.isArray(et.entries)&&et.entries.length&&(e.memoryCount=et.entries.length),pe&&"downloaded"===pe.status&&pe.version&&(e.updatePending=String(pe.version)),D.length&&c.modelSelect&&c.modelSelect.options.length>1&&(e.modelCount=c.modelSelect.options.length),e}function ut(){if(!window.aegisCompanion||!c.companionCard||!c.companionText)return;const e=new Date;let t=null;try{t=JSON.parse(localStorage.getItem(ct)||"null")}catch{t=null}if(window.aegisCompanion.dismissedToday(t,e))return void(c.companionCard.hidden=!0);const n=window.aegisCompanion.pickMessage(dt(),e);n&&n.text?(c.companionText.textContent=n.text,c.companionCard.dataset.kind=n.kind,c.companionCard.dataset.messageId=n.id,c.companionCard.hidden=!1):c.companionCard.hidden=!0}function mt(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 pt(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 yt(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(pt):[];return o&&o.upgrade?{entries:a,error:"",upgrade:o.upgrade,local:!0===o.local}:{entries:a,error:"",upgrade:null,local:o&&!0===o.local}}catch(e){const t=e&&e.status,n=e&&e.data&&e.data.error;return 402===t||"free_session_limit_reached"===n?{entries:[],error:"",upgrade:{url:e.data&&e.data.upgradeUrl||L("memory_quota"),used:e.data&&(null!=e.data.tokensUsed?e.data.tokensUsed:e.data.sessionsUsed),limit:e.data&&(null!=e.data.tokenLimit?e.data.tokenLimit:e.data.freeSessionLimit)}}:{entries:[],error:`search failed: ${e&&e.message?e.message:e}`,upgrade:null,local:!1}}}function ft(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 ht(e,t,n,o,s){if(!e)return;const a=null!=t.used?ft(t.used):"?",i=null!=t.limit?ft(t.limit):"?";e.textContent=`${n||"sync limit reached"} — ${a} of ${i} tokens synced. Nothing was lost. ${x} `,I(e,t.url,s||"memory_quota",o||"See what Pro covers →")}function gt(e,t){ht(c.memoryHint,e,t)}async function vt(e){c.memoryHint.textContent="searching…";const t=await yt(e,Je);(function(e,t,n,o=!1){c.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)>=Xe))}(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;c.tabMemory&&(c.tabMemory.hidden=!(t||n||o)),c.memoryBox&&(c.memoryBox.hidden=!n),c.memoryQuiet&&(c.memoryQuiet.hidden=!o),c.tabMemory&&c.tabMemory.hidden&&"memory"===Fn&&Pn("sessions")}({hasAny:s.length>0,hasBox:a,quietNotice:i}),a){if(n){const e=document.createElement("li");return e.className="empty mem-side-upgrade",c.memoryResults.appendChild(e),void I(e,n.url,"memory_quota","Free plan limit reached — see what Pro covers →")}if(t){const e=document.createElement("li");return e.className="empty",e.textContent=t,void c.memoryResults.appendChild(e)}if(!s.length){const e=document.createElement("li");return e.className="empty",e.textContent="no memory entries",void c.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),c.memoryResults.appendChild(t)}}})(t.entries,t.error,t.upgrade,""===e),t.upgrade?gt(t.upgrade,"cloud memory needs an active plan"):t.local?c.memoryHint.textContent=kt:c.memoryHint.textContent=t.error||""}const kt="offline — showing this device’s saved copy";function Ct(e,t){const n=document.createElement("span");return n.className="mem-chip"+(t?` ${t}`:""),n.textContent=e,n}function bt(e){const t=document.createElement("li");t.className="mem-card";const n=document.createElement("div");n.className="mem-card-head",n.appendChild(Ct(e.source,"src")),e.role&&n.appendChild(Ct(e.role,"role")),null!=e.importance&&n.appendChild(Ct(`imp ${e.importance}`,"imp")),e.sentiment&&n.appendChild(Ct(e.sentiment,"sent")),e.summary&&n.appendChild(Ct("summary","flag"));const o=document.createElement("span");o.className="mem-card-meta";const s=[],a=mt(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(Ct(t,"pill"));t.appendChild(e)}return i.addEventListener("click",(()=>{window.getSelection&&String(window.getSelection())||t.classList.toggle("expanded")})),t}function wt(e){const t=new Map;for(const n of et.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 xt(){if(!nt())return;const e=et.entries.length;if(c.memoryList.innerHTML="",function(){if(c.memoryChips.innerHTML="",et.upgrade||et.error)return;const e=[["source","source",wt("source")],["role","role",wt("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"+(et[t]===n?" on":""),o.textContent=`${n} ${s}`,o.addEventListener("click",(()=>{et[t]=et[t]===n?"":n,xt()})),e.appendChild(o)}c.memoryChips.appendChild(e)}}(),et.loading)return void(c.memoryCount.textContent="loading…");if(et.upgrade){c.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!=et.upgrade.used?ft(et.upgrade.used):"?",s=null!=et.upgrade.limit?ft(et.upgrade.limit):"?";return n.textContent=`This account has used ${o} of ${s} tokens of synced conversation. Saved memory is still readable — only new saves are paused until there is room again. `+x,e.appendChild(t),e.appendChild(n),c.memoryList.appendChild(e),void I(e,et.upgrade.url,"memory_quota","Open subscribe page ↗")}if(et.error){c.memoryCount.textContent="";const e=document.createElement("li");return e.className="mem-empty",e.textContent=et.error,void c.memoryList.appendChild(e)}if(!e){c.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 c.memoryList.appendChild(e)}const t=et.query.trim().toLowerCase(),n=et.entries.filter((e=>(!et.source||e.source===et.source)&&(!et.role||e.role===et.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(et.entries.map((e=>e.source))).size,s=et.local?`offline · saved on this device · ${o} source${1===o?"":"s"}`:`${o} source${1===o?"":"s"}`;if(c.memoryCount.textContent=`${n.length} of ${e} shown · ${s}`+(e>=Ze?` · newest ${Ze}`:""),!n.length){const e=document.createElement("li");return e.className="mem-empty",e.textContent="Nothing matches those filters.",void c.memoryList.appendChild(e)}for(const e of n)c.memoryList.appendChild(bt(e))}async function St(e){et.loading=!0,et.error="",et.upgrade=null,et.local=!1,xt();const t=await yt(e,Ze);et.entries=t.entries,et.error=t.error,et.upgrade=t.upgrade,et.local=!0===t.local,et.loading=!1,xt()}function Et(){c.memoryOverlay&&(c.memoryOverlay.hidden=!1,document.body.classList.add("memory-open"),c.memoryOverlayQuery.value=c.memoryQuery?c.memoryQuery.value.trim():"",et.query=c.memoryOverlayQuery.value,et.source="",et.role="",xt(),St(et.query),c.memoryOverlayQuery&&c.memoryOverlayQuery.focus())}function $t(){c.memoryOverlay&&(c.memoryOverlay.hidden=!0,document.body.classList.remove("memory-open"),c.memoryOpen&&c.memoryOpen.focus())}let Lt=null;function qt(){return!!c.sessionOverlay&&!c.sessionOverlay.hidden}function Mt(e,t){const n=document.createElement("li");n.className="session-row",n.tabIndex=0;const o=document.createElement("span");o.className="session-title",o.textContent=e&&e.title||e&&e.id||"untitled",n.appendChild(o);const s=document.createElement("span");s.className="session-meta";const a=[],i=e&&Array.isArray(e.messages)&&e.messages.length||0;i&&a.push(`${i} msg${1===i?"":"s"}`),e&&e.updatedAt&&a.push(mt(new Date(e.updatedAt).getTime())||String(e.updatedAt)),t&&e&&e.reason&&a.push(`match: ${e.reason}`),s.textContent=a.join(" · "),n.appendChild(s);const r=()=>{Ht(),zn(e.id)};return n.addEventListener("click",r),n.addEventListener("keydown",(e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),r())})),n}async function At(e){const t=String(null==e?"":e).trim();if(Lt=t,c.sessionHint&&(c.sessionHint.textContent=t?`searching “${t}”…`:""),!n||"function"!=typeof n.searchSessions)return void(c.sessionHint&&(c.sessionHint.textContent="session search is unavailable in this build."));let o=null;try{o=await n.searchSessions(t,50)}catch(e){return void(c.sessionHint&&(c.sessionHint.textContent=`search failed: ${e&&e.message||e}`))}t===Lt&&(c.sessionHint&&(c.sessionHint.textContent=""),function(e,t){if(!c.sessionList)return;c.sessionList.innerHTML="";const n=e&&e.sessions||[];if(c.sessionCount&&(c.sessionCount.textContent=e&&Number.isInteger(e.total)?`${n.length} of ${e.total}`:String(n.length)),!n.length){const e=document.createElement("li");return e.className="empty",e.textContent=t?`no session matches “${t}”`:"no sessions yet",void c.sessionList.appendChild(e)}for(const e of n)c.sessionList.appendChild(Mt(e,t))}(o,t))}function Nt(){c.sessionOverlay&&(c.sessionOverlay.hidden=!1,document.body.classList.add("memory-open"),c.sessionQuery&&(c.sessionQuery.value="",c.sessionQuery.focus()),c.sessionHint&&(c.sessionHint.textContent=""),At(""))}function Ht(){c.sessionOverlay&&(c.sessionOverlay.hidden=!0,document.body.classList.remove("memory-open"))}let Bt=null;function It(){return!!c.importOverlay&&!c.importOverlay.hidden}function Rt(){c.importOverlay&&(c.importOverlay.hidden=!0,document.body.classList.remove("memory-open"),c.importSessionBtn&&c.importSessionBtn.focus())}function Tt(e){const t=document.createElement("li");t.className="import-row";const n=document.createElement("span");n.className="import-source",n.textContent=e.label||e.id,t.appendChild(n);const o=document.createElement("span");if(o.className="session-meta",e.present)if(e.unreadable)o.textContent="found, store not readable yet",t.classList.add("import-absent");else if(e.count){const t=e.messages?` · ${e.messages} msg${1===e.messages?"":"s"}`:"";o.textContent=`${e.count} session${1===e.count?"":"s"}${t}${e.verified?"":" · best-effort"}`}else o.textContent="found, no conversations";else o.textContent="not installed",t.classList.add("import-absent");return t.appendChild(o),t}async function Ot(){c.importOverlay&&(c.importOverlay.hidden=!1,document.body.classList.add("memory-open"),c.importList&&(c.importList.innerHTML=""),c.importSessionsBtn&&(c.importSessionsBtn.disabled=!0),c.importHint&&(c.importHint.textContent="scanning this machine…"),await async function(){if(!n||"function"!=typeof n.sessionsImportScan)return c.importHint&&(c.importHint.textContent="import is unavailable in this build."),null;c.importHint&&(c.importHint.textContent="scanning this machine…");try{Bt=await n.sessionsImportScan()}catch(e){return c.importHint&&(c.importHint.textContent=`scan failed: ${e&&e.message||e}`),null}return function(e){if(!c.importList)return;c.importList.innerHTML="";const t=e&&e.sources||[],n=e&&e.totals||{};if(c.importCount&&(c.importCount.textContent=`${n.sessions||0} session(s), ${n.messages||0} msg(s)`),!t.length){const e=document.createElement("li");return e.className="empty",e.textContent="no other AI tools were looked for",void c.importList.appendChild(e)}for(const e of t)c.importList.appendChild(Tt(e));const o=(n.sessions||0)>0;c.importSessionsBtn&&(c.importSessionsBtn.disabled=!o),c.importHint&&(c.importHint.textContent=o?"read-only scan — nothing is copied until you press Import sessions":"nothing importable was found; the Memory card can still import memory fragments")}(Bt),Bt}())}async function Ut(){if(!n||"function"!=typeof n.sessionsImport)return;const e=c.importSessionsBtn;e&&(e.disabled=!0),c.importHint&&(c.importHint.textContent="copying sessions into AEGIS…");try{const e=await n.sessionsImport({confirm:!0,limit:500,sync:!(!c.importSync||!c.importSync.checked)});if(!e||!e.ok)return void(c.importHint&&(c.importHint.textContent=`import stopped: ${e&&e.reason||"unknown error"}`));const t=e.skippedExisting?`, ${e.skippedExisting} already here`:"";c.importHint&&(c.importHint.textContent=`imported ${e.imported} session(s)${t}.`),await Gn()}catch(e){c.importHint&&(c.importHint.textContent=`import failed: ${e&&e.message||e}`)}finally{e&&(e.disabled=!1)}}
|
|
3
|
+
"use strict";!function(){const e=window.aegis,t=window.models,n=window.sync,o=window.quickLauncher,s=window.queue,a=window.auto,i="nexus",r="Nexus — auto-route";if(!e||!t)throw document.body.textContent="This page must run inside the AEGIS Electron host (window.aegis/window.models missing).",new Error("window.aegis/window.models unavailable — not running under Electron");const l={updateBanner:"update-banner",updateBannerText:"update-banner-text",updateDownloadBtn:"update-download-btn",updateRestartBtn:"update-restart-btn",updateRetryBtn:"update-retry-btn",updateLaterBtn:"update-later-btn",accountBanner:"account-banner",accountBannerText:"account-banner-text",accountRetryBtn:"account-retry-btn",keysAccount:"keys-account",keysAccountRetry:"keys-account-retry",connDot:"conn-dot",connText:"conn-text",app:"st-app",client:"st-client",base:"st-base",key:"st-key",plan:"st-plan",balance:"st-balance",upgradePlan:"upgrade-plan",topupBtn:"topup-btn",topupAmount:"topup-amount",billingHint:"billing-hint",apiKeyInput:"api-key-input",apiKeySave:"api-key-save",apiKeyVerify:"api-key-verify",apiKeyHint:"api-key-hint",classSelect:"class-select",modelSelect:"model-select",providerMark:"provider-mark",ptSearch:"pt-search",ptRefresh:"pt-refresh",ptList:"pt-list",ptCount:"pt-count",ptHint:"pt-hint",companionCard:"companion-card",companionText:"companion-text",companionDismiss:"companion-dismiss",modelFree:"model-input",budgetHint:"budget-hint",autonomousToggle:"autonomous-toggle",autonomousToggleWrap:"autonomous-toggle-wrap",autonomousControls:"autonomous-controls",effortSelect:"effort-select",autonomousWorkers:"autonomous-workers",modelHint:"model-hint",settingsList:"settings-list",settingsHint:"settings-hint",customBaseUrl:"custom-base-url",customKey:"custom-key",customModel:"custom-model",customSave:"custom-save",customRemove:"custom-remove",customStatus:"custom-status",quickLauncherEnabled:"quick-launcher-enabled",quickLauncherShortcut:"quick-launcher-shortcut",quickLauncherSave:"quick-launcher-save",quickLauncherHint:"quick-launcher-hint",permRulesList:"perm-rules-list",permRulesForm:"perm-rules-form",permRulesInput:"perm-rules-input",permRulesListSelect:"perm-rules-list-select",permRulesAdd:"perm-rules-add",permRulesStatus:"perm-rules-status",permRulesHint:"perm-rules-hint",sandboxMode:"sandbox-mode-select",sandboxNetwork:"sandbox-network-toggle",sandboxStatus:"sandbox-policy-status",confirmMode:"confirm-mode-toggle",confirmModeHint:"confirm-mode-hint",planMode:"plan-mode-toggle",planModeHint:"plan-mode-hint",autoMode:"auto-mode-toggle",autoModeLabel:"auto-mode-label",autoModeHint:"auto-mode-hint",sessionsRefresh:"sessions-refresh",sessionsExport:"sessions-export",sessionsList:"sessions-list",sessionsHint:"sessions-hint",sessionsFilter:"sessions-filter",sessionsCount:"sessions-count",syncNow:"sync-now",syncStatus:"sync-status",sessionMeter:"session-meter",newChat:"new-chat",memorySearchForm:"memory-search-form",memoryQuery:"memory-query",memoryResults:"memory-results",memoryEntry:"memory-entry",memorySaveBtn:"memory-save-btn",memoryImportBtn:"memory-import-btn",importSessionBtn:"import-session-btn",importOverlay:"import-overlay",importBackdrop:"import-backdrop",importClose:"import-close",importHint:"import-hint",importList:"import-list",importCount:"import-count",importSync:"import-sync",importSessionsBtn:"import-sessions-btn",importMemoryBtn:"import-memory-btn",memoryHint:"memory-hint",memoryOpen:"memory-open",memoryBox:"memory-box",memoryQuiet:"memory-quiet",memoryQuietFloor:"memory-quiet-floor",paneTabs:"pane-tabs",tabSessions:"tab-sessions",tabMemory:"tab-memory",paneSessions:"pane-sessions",paneMemory:"pane-memory",memoryOverlay:"memory-overlay",memoryBackdrop:"memory-backdrop",memoryClose:"memory-close",memoryFilters:"memory-filters",memoryOverlayQuery:"memory-overlay-query",memoryFiltersClear:"memory-filters-clear",memoryChips:"memory-chips",memoryList:"memory-list",memoryCount:"memory-count",memoryOverlayEntry:"memory-overlay-entry",memoryOverlaySave:"memory-overlay-save",sessionOverlay:"session-overlay",sessionBackdrop:"session-backdrop",sessionClose:"session-close",sessionFilters:"session-filters",sessionQuery:"session-query",sessionClear:"session-clear",sessionHint:"session-hint",sessionList:"session-list",sessionCount:"session-count",creditsOverlay:"credits-overlay",creditsBackdrop:"credits-backdrop",creditsClose:"credits-close",creditsBody:"credits-body",creditsStatus:"credits-status",creditsLicenceTag:"credits-licence-tag",fpCardStatus:"fp-card-status",fpOpen:"fp-open",fpOverlay:"fp-overlay",messages:"messages",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"},c={};for(const[e,t]of Object.entries(l))Object.defineProperty(c,e,{get:()=>document.getElementById(t),enumerable:!0,configurable:!0});const d="aegis.class",u="aegis.queueClass",m="aegis.autonomous",p="aegis.effort",y="aegis.autonomousWorkers",f="aegis.explore",h="aegis.welcomeConnectDismissed",g="aegis",v=new Set(["__aegis","aegis"]),C="local",k="custom",b="http://localhost:11434",w="https://aegiscloud.org/key?s=desktop&c=key_prompt",x="The autonomous queue keeps running after you close the laptop.",E="https://aegiscloud.org",S=/^[a-z0-9][a-z0-9_-]{0,63}$/;function $(e,t){const n=new URL(`${E}/go/${e}`);n.searchParams.set("s","desktop");const o=null==t?"":String(t).trim().toLowerCase();return S.test(o)&&n.searchParams.set("c",o),n.toString()}function L(e){return $("upgrade",e)}function q(e){return $("topup",e)}const M={welcome_cloud:"welcome",queue_cap:"queue",memory_quota:"memory",status_card:"status",topup_bank:"topup"},N="upgrade_prompt_rendered",A="upgrade_prompt_clicked";let H=!1;function B(e,t){try{const n=M[t];if(!n)return;const o=window.aegis;if(!o||"function"!=typeof o.telemetryEvent)return;const s=o.telemetryEvent(e,{campaign:t,surface:n});s&&"function"==typeof s.catch&&s.catch((()=>{}))}catch(e){if(!H){H=!0;try{console.debug("telemetry: prompt event failed (suppressed)",e)}catch{}}}}function I(e,t,n,o){const s=document.createElement("a");return s.href=function(e,t){const n="topup_bank"===t?q(t):L(t);if(!e)return n;let o;try{o=new URL(e,E)}catch{return e}return o.origin!==E||o.searchParams.get("s")||o.searchParams.get("utm_source")?e:/topup/.test(o.pathname)?q(t):n}(t,n),s.target="_blank",s.rel="noreferrer noopener",s.textContent=o,s.addEventListener("click",(()=>B(A,n))),e.appendChild(s),!1===e.isConnected||e.hidden||B(N,n),s}let R=null,T=null,O=null,D=[],U=[],F=new Map;const P=new Map;function _(e,t,n={}){const o=e||"",s=rollTurn(function(e){const t=e||"";return P.has(t)||P.set(t,emptyRoll()),P.get(t)}(o),t,n);return P.set(o,s),K(o),s}function K(e,t){const n=c.sessionMeter,o=t?function(e){const t="string"==typeof e.reply?e.reply:"",n="string"==typeof e.reasoning?e.reasoning:"",o="number"==typeof e.measuredReasoningTokens&&e.measuredReasoningTokens>0?e.measuredReasoningTokens:0;if(!t&&!n&&!o)return"↓0 tokens";let s=0;try{const o=estimatedBuckets(e.prompt,t,n);o&&"number"==typeof o.output&&o.output>0&&(s=o.output)}catch(e){}if(!s){let e=0;for(const o of[t,n]){let t=0;for(;t<o.length;)t+=o.codePointAt(t)>65535?2:1,e+=1}s=Math.ceil(e/4)}return s+=o,s?`↓${o>0?"≥":""}${Math.round(s)} tokens`:""}(t):"",s=t?function(){if(!R)return null;let e=R.querySelector(".typing-tokens");return e||(e=document.createElement("span"),e.className="typing-tokens",e.hidden=!0,R.appendChild(e)),e}():null;if(s&&(s.textContent=o,s.hidden=!o),!n)return;if(O!==e)return void(n.hidden=!0);let a=P.get(e||"");t&&(a=rollTurn(a||emptyRoll(),void 0,{prompt:t.prompt,reply:t.reply,reasoning:t.reasoning,measuredReasoningTokens:t.measuredReasoningTokens}));const i=a?fmtRoll(a):"";return n.textContent=i,n.hidden=!i,n.classList.toggle("live",!!t&&!!i),i&&(n.title="This session, counted the way the CLI counts it — every turn rolled into one running total"),a}function j(e,t,n,o){const s=ledgerRow(e,n,{model:t,costUsd:n&&n.real&&"number"==typeof n.cost?n.cost:void 0,calls:o&&o.calls,prompt:o&&o.prompt,reply:o&&o.reply,reasoning:o&&o.reasoning}),a=s?Object.assign({},s):{};return t&&(a.model=t),a}const G="You are the exploratory half of a chat assistant. The user is reading the main answer elsewhere, so never restate it. Be concrete and brief: one lead line naming the path, then 3-5 tight bullets. Never pad.",Q=[{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 W=0;const V=new Set;function Y(){for(const e of V)try{t.cancel(e)}catch{}V.clear()}let z=0,J=null,X=null,Z=null;function ee(e){return!!Z&&Z.follow(e)}let te=null;function ne(){if(!T)return!1;if(!stopAppliesTo(J,X))return!1;X=J;const e=T;te={sessionId:e,at:Date.now(),state:"requested"};try{const n=t.cancel(e);n&&"function"==typeof n.then&&n.then((t=>{te={sessionId:e,at:Date.now(),state:"settled",accepted:!t||!1!==t.ok,result:void 0===t?null:t}}),(t=>{te={sessionId:e,at:Date.now(),state:"rejected",accepted:!1,error:t&&t.message||String(t)}}))}catch(t){te={sessionId:e,at:Date.now(),state:"threw",accepted:!1,error:t&&t.message||String(t)}}if(R){const e=R.querySelector(".cancel-btn");e&&(e.disabled=!0,e.textContent="stopping…")}return!0}function oe(){const e=c.autonomousToggle;return Boolean(e&&e.checked)}function se(){if(!c.autonomousControls)return;const e=c.autonomousToggleWrap&&!c.autonomousToggleWrap.hidden;c.autonomousControls.hidden=!(e&&oe())}function ae(){if(c.modelFree&&!c.modelFree.hidden){const e=c.modelFree.value.trim();if(e)return e}return c.modelSelect.value}function ie(e,t){const n=void 0===t?ae():t;c.budgetHint&&(c.budgetHint.textContent=function(e,t){const n=le(),o=n,s=n;return e===g?`budget: ${{low:16384,medium:32768,high:65536,max:65536}[o].toLocaleString()} tokens from effort (${s}), summed across the worker fan-out by the Aegis Cloud pool — no max_tokens is sent.`:DEEPSEEK_REASONING_MODEL_RE.test(String(t||""))?`budget: ${EFFORT_TOKEN_BUDGET[o].toLocaleString()} tokens from effort (${s}) — this model reasons against its own output budget, and the length of the answer is not predictable from the prompt.`:`no token cap is sent (effort: ${s}) — output length cannot be predicted from the prompt, so this app states no max_tokens and the provider's own limit applies.`}(e,n)),re()}function re(){if(!c.providerMark||!window.aegisProviderMark)return;const e=ae(),t="local"===(c.classSelect?c.classSelect.value:"")?"ollama":"";window.aegisProviderMark.paint(c.providerMark,e,"",t)}function le(){const e=c.effortSelect&&c.effortSelect.value;return"low"===e||"medium"===e||"max"===e?e:"high"}function ce(e,t){c.connDot.classList.toggle("ok",Boolean(e)),c.connText.textContent=t}let de=null,ue=!1;function me(e){if(!e)return de=null,ue=!1,void ce(!1,"IPC unavailable");de=Boolean(e.keyConfigured),ue=Boolean(e.providerConfigured),c.app.textContent=e.appVersion?`v${e.appVersion}`:"–",c.client.textContent=e.clientVersion||"–",c.base.textContent=e.apiBase||"–",c.key.textContent=e.keyConfigured?e.keyMask:"not set",ce(e.keyConfigured,e.keyConfigured?"key configured":"no API key"),an(),Xt(),function(){const e=document.getElementById("keys-overlay");if(!e)return;let t=!1;try{t="on"===localStorage.getItem(pn)}catch{}t||null===de?e.hidden=!0:(yn(),Boolean(T)?fn():!0!==de||!0!==ue?c.keysOverlay&&(yn(),c.keysOverlay.hidden&&(c.keysOverlay.hidden=!1,document.body.classList.add("keys-open"))):fn())}()}let pe=null,ye=null;function fe(e){if(!c.updateBanner)return;pe=e;try{ut()}catch{}const t=e&&e.status;if(!t||"idle"===t||"disabled"===t||"checking"===t||"up-to-date"===t||"unavailable"===t||t===ye)return void(c.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(c.updateBanner.hidden=!0);n=`Update check failed: ${e.error||"unknown error"}`,e.transient&&(n+=" — will retry automatically."),a=!0}c.updateBannerText.textContent=n,c.updateDownloadBtn.hidden=!o,c.updateRestartBtn.hidden=!s,c.updateRetryBtn&&(c.updateRetryBtn.hidden=!a),c.updateBanner.hidden=!1}let he=null;function ge(e){he=e&&"no-key"===e.status?e.reason:null,yn(),c.accountBanner&&(he?(c.accountBannerText.textContent=`No AEGIS account key on this machine: ${he}.`,c.accountBanner.hidden=!1):c.accountBanner.hidden=!0)}function ve(t){t.disabled=!0,e.registerAccount().then((e=>{if(ge(e),!e)return be()})).catch((e=>ge({status:"no-key",reason:String(e&&e.message||e)}))).finally((()=>{t.disabled=!1}))}async function Ce(){try{const t=await e.verifyApiKey();t&&t.ok?c.plan.textContent=t.valid?t.plan||"active":"invalid key":c.plan.textContent="unavailable"}catch{c.plan.textContent="unavailable"}try{const t=await e.tokenBankBalance();c.balance.textContent=t&&null!=t.balance_eur?`€${t.balance_eur}`:"–"}catch{c.balance.textContent="unavailable"}}async function ke(t){const n=Math.round(Number(c.topupAmount&&c.topupAmount.value)||10),o="topup"===t?c.topupBtn:c.upgradePlan;if(o&&(o.disabled=!0),"topup"===t&&!1===de)return o&&(o.disabled=!1),void(c.billingHint.textContent="add your AEGIS API key above — a top-up is credited to your account");c.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?(c.billingHint.textContent=`free plan cap reached — ${n} lifts it. `,void I(c.billingHint,e.upgrade.url,"topup"===t?"topup_bank":"status_card","See plans →")):void(e.setupRequired?c.billingHint.textContent="checkout is not configured on the server yet (no Stripe price id)":c.billingHint.textContent=`${n} failed: ${e.reason||"the server returned no checkout URL"}`);c.billingHint.textContent=`add your AEGIS API key above — a ${n} needs an account`}(o||{},t);c.billingHint.textContent="opening checkout…";const s=await e.openExternal(o.url);if(s&&!1===s.ok)return void(c.billingHint.textContent=`could not open the checkout page: ${s.reason||"unknown reason"}`);c.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){c.billingHint.textContent=`billing failed: ${e&&e.message?e.message:e}`}finally{o&&(o.disabled=!1)}}async function be(){try{me(await e.status())}catch{me(null)}await An(),await Ce()}async function we(){const t=c.apiKeyInput.value.trim();c.apiKeySave.disabled=!0,c.apiKeyVerify.disabled=!0,c.apiKeyHint.textContent="saving…";try{const n=await e.setApiKey(t);if(!n||!n.ok)throw new Error(n&&n.error||"save failed");c.apiKeyInput.value="",c.apiKeyHint.textContent=t?`saved (${n.keyMask?n.keyMask:"configured"})`:"key cleared",await be()}catch(e){c.apiKeyHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{c.apiKeySave.disabled=!1,c.apiKeyVerify.disabled=!1}}async function xe(){c.apiKeyVerify.disabled=!0,c.apiKeyHint.textContent="verifying…";try{const t=await e.verifyApiKey();if(!t||!t.ok)throw new Error(t&&t.error||"verify failed");c.apiKeyHint.textContent=t.valid?`valid (${t.plan||"active"})`:"invalid key"}catch(e){c.apiKeyHint.textContent=`verify failed: ${e&&e.message?e.message:e}`}finally{c.apiKeyVerify.disabled=!1}}function Ee(e){if(!e)return;c.quickLauncherEnabled.checked=Boolean(e.enabled),c.quickLauncherShortcut.value=e.shortcut||"",c.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),c.quickLauncherHint.textContent=t.join(" · ")}async function Se(){if(o){c.quickLauncherSave.disabled=!0,c.quickLauncherHint.textContent="saving…";try{Ee(await o.setConfig({enabled:c.quickLauncherEnabled.checked,shortcut:c.quickLauncherShortcut.value.trim()}))}catch(e){c.quickLauncherHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{c.quickLauncherSave.disabled=!1}}}function $e(e){if(!c.confirmMode||!e)return;const t=!1!==e.enabled;c.confirmMode.checked=t,c.confirmModeHint.textContent=t?"On — exec, writeFile and editFile ask for your approval before they run.":"Off — the agent runs exec, writeFile and editFile without asking.",Le(t)}function Le(e){if(!c.autoMode)return;const t=!e;c.autoMode.setAttribute("aria-pressed",t?"true":"false"),c.autoMode.classList.toggle("is-auto",t),c.autoModeLabel&&(c.autoModeLabel.textContent=t?"auto mode":"ask before tools"),c.autoModeHint&&(c.autoModeHint.textContent=t?"on — tools run without asking. Click to require approval.":"off — click for auto mode, or use Settings → Tool approvals.")}async function qe(t){if(c.confirmMode){c.confirmMode.disabled=!0,c.autoMode&&(c.autoMode.disabled=!0);try{$e(await e.setConfirmMode(t))}catch(e){c.confirmMode.checked=!t,c.confirmModeHint.textContent=`save failed: ${e&&e.message?e.message:e}`,Le(c.confirmMode.checked)}finally{c.confirmMode.disabled=!1,c.autoMode&&(c.autoMode.disabled=!1)}}}function Me(e){if(!c.planMode||!e)return;const t="plan"===e.mode;c.planMode.checked=t,c.planModeHint&&(c.planModeHint.textContent=t?"On — writeFile, editFile and mutating exec calls are refused; read-only shell and search still run.":'Off — tool calls follow "confirm before running tools" above, as usual.')}const Ne=["deny","allow","ask"];function Ae(e){if(!c.permRulesList)return;c.permRulesList.innerHTML="";const t=e&&!0===e.ok,n=t&&e.rules?e.rules:null;if(!n){const n=document.createElement("li");return n.className="rules-row rules-row-muted",n.textContent=t?"no stored rules":`rules unavailable: ${e&&e.reason||"the permission store could not be read"}`,c.permRulesList.appendChild(n),void(c.permRulesHint&&(c.permRulesHint.dataset.residual=""))}let o=0;for(const e of Ne){const t=Array.isArray(n[e])?n[e]:[];for(const n of t){o+=1;const t=document.createElement("li");t.className="rules-row",t.dataset.list=e,t.dataset.rule=n;const s=document.createElement("span");s.className=`rules-tag rules-tag-${e}`,s.textContent=e,t.appendChild(s);const a=document.createElement("code");a.className="rules-pattern",a.textContent=n,t.appendChild(a);const i=document.createElement("button");i.type="button",i.className="ghost-btn danger rules-remove",i.textContent="Remove",i.addEventListener("click",(()=>He(e,n))),t.appendChild(i),c.permRulesList.appendChild(t)}}if(!o){const e=document.createElement("li");e.className="rules-row rules-row-muted",e.textContent="no stored rules",c.permRulesList.appendChild(e)}var s;c.permRulesHint&&(c.permRulesHint.textContent=`A rule is tool(pattern) — exec(npm test), exec(npm run *), writeFile(src/**). Deny beats allow. ${s=n.defaultMode,"allow"===s?"unmatched calls run without asking":"deny"===s?"unmatched calls are refused":"unmatched calls ask"}.`)}async function He(t,n){if(e.permRulesRemove)try{const o=await e.permRulesRemove(t,n);o&&!0===o.ok?(Ae(o),c.permRulesStatus&&(c.permRulesStatus.textContent=!1===o.removed?`already gone: ${n}`:`removed: ${n}`)):c.permRulesStatus&&(c.permRulesStatus.textContent=`remove failed: ${o&&o.reason||"the store refused it"}`)}catch(e){c.permRulesStatus&&(c.permRulesStatus.textContent=`remove failed: ${e&&e.message?e.message:e}`)}}const Be={"workspace-write":"Commands may write inside the open workspace and /tmp; everything else is read-only.","read-only":"Commands may write nothing at all. Every path is mounted read-only.",off:"No sandbox. Commands run with your full user permissions."};function Ie(e){if(!c.sandboxMode)return;const t=e&&"string"==typeof e.mode?e.mode:"workspace-write",n=e&&"open"===e.network?"open":"restricted";if(Array.isArray(e&&e.modes)&&e.modes.length&&Array.from(c.sandboxMode.options).map((e=>e.value)).join("\0")!==e.modes.join("\0")){c.sandboxMode.innerHTML="";for(const t of e.modes){const e=document.createElement("option");e.value=t,e.textContent=t,c.sandboxMode.appendChild(e)}}c.sandboxMode.value=t,c.sandboxNetwork&&(c.sandboxNetwork.checked="open"===n),c.sandboxStatus&&(c.sandboxStatus.textContent=e&&!1!==e.ok?function(e){const t=e&&"string"==typeof e.mode?e.mode:"workspace-write",n=e&&"open"===e.network?"open":"restricted",o=e&&"string"==typeof e.sentence?e.sentence:null,s=e?e.enforced:null;if(!1===s)return`${o||`sandbox: OFF — no mechanism available (mode ${t} is not being enforced)`}. Commands are NOT confined.`;if(null===s||!o){const e=null===s?"the sandbox probe could not be completed":"no mechanism reported";return`${Be[t]||t} Sandbox status unknown: ${e}, so this posture may not be enforced.`}return`${null!==o?o:""} ${Be[t]||t} Network: ${"open"===n?"allowed":"blocked"}.`.trim()}(e):`could not read the posture: ${e&&e.reason||"unknown error"}`)}async function Re(){if(c.sandboxMode&&e.getSandboxPolicy)try{Ie(await e.getSandboxPolicy())}catch(e){Ie({ok:!1,reason:e&&e.message||String(e)})}}async function Te(t,n){if(e.setSandboxPolicy)try{Ie(await e.setSandboxPolicy(t,n))}catch(e){c.sandboxStatus&&(c.sandboxStatus.textContent=`not saved: ${e&&e.message?e.message:e}`),Re()}}let Oe="",De=!1;function Ue(e){Oe=e||"",c.queueHint&&(c.queueHint.textContent=Oe)}function Fe(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 ${mt(e.startedAt)}`:"working"):(e.attempts&&t.push(`${e.attempts} attempt${1===e.attempts?"":"s"}`),e.created&&t.push(mt(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",(()=>Qe("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",(()=>Qe("remove",e.id))),t.appendChild(n)}return t}function Pe(e){if(!c.queueList||!e||"object"!=typeof e)return;De=Boolean(e.draining),c.queueCwd&&!c.queueCwd.value&&(c.queueCwd.value=e.defaultCwd||""),c.queueEnqueue&&(c.queueEnqueue.disabled=De),c.queueDrain&&(c.queueDrain.disabled=De),c.queueProceed&&(c.queueProceed.disabled=De),c.queueStop&&(c.queueStop.hidden=!De);const t=Array.isArray(e.items)?e.items:[];if(c.queueList.innerHTML="",t.length)for(const e of t)c.queueList.appendChild(Fe(e));else{const e=document.createElement("li");e.className="empty",e.textContent="queue is empty",c.queueList.appendChild(e)}const n=[];e.running?n.push(`running #${e.running.id}`):De&&n.push("draining…"),n.push(`${e.pending||0} pending`),e.defaultModel&&n.push(`Aegis Cloud · ${e.defaultModel}`),De&&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(c.queueFanout&&(c.queueFanout.disabled=!o,o||(c.queueFanout.checked=!1)),c.queueBoundary&&(c.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||"":""),c.queueUpgrade&&(c.queueUpgrade.innerHTML="",n&&!o)){const e="balance"===t.wall;I(c.queueUpgrade,t.upgradeUrl,t.campaign,e?"Top up your balance ↗":"See what Pro covers ↗")}}(e),c.queueHint&&(c.queueHint.textContent=[Oe,n.join(" · ")].filter(Boolean).join(" · "))}async function _e(){if(!s||!c.queueList)return null;try{const e=await s.list();return Pe(e),e}catch(e){return Ue(`queue list failed: ${e&&e.message?e.message:e}`),null}}async function Ke(){if(!s||!c.queueTask)return;const e=c.queueTask.value.trim();if(e){c.queueEnqueue&&(c.queueEnqueue.disabled=!0),Ue("queueing…");try{const t=await s.enqueue({task:e,cwd:c.queueCwd?c.queueCwd.value.trim():"",class:c.queueClassSelect?c.queueClassSelect.value:void 0,model:Bn(),commit:!!c.queueCommit&&c.queueCommit.checked});t&&t.ok?(c.queueTask.value="",Ue(`queued #${t.item.id}`)):Ue(t&&t.reason||"enqueue failed"),Pe(t)}catch(e){Ue(`enqueue failed: ${e&&e.message?e.message:e}`)}finally{c.queueEnqueue&&(c.queueEnqueue.disabled=De)}}else Ue("type a task first")}async function je(e){if(s){De=!0,Ue("one"===e?"running one task…":"draining the queue…"),c.queueDrain&&(c.queueDrain.disabled=!0),c.queueProceed&&(c.queueProceed.disabled=!0),c.queueEnqueue&&(c.queueEnqueue.disabled=!0),c.queueStop&&(c.queueStop.hidden=!1);try{const t=await("one"===e?s.drain():s.proceed());Ue(function(e){if(!e||"object"!=typeof e)return"the drain did not answer";if(e.locked){const t=e.holder&&e.holder.pid;return"another drain is already running"+(t?` (pid ${t})`:"")}if(!1===e.ok)return e.reason||"the drain did not run";const t=Array.isArray(e.ran)?e.ran:[];if(!t.length)return e.stopped?"stopped before the next task":"nothing pending";const n=t.filter((e=>!e.ok)),o=[`ran ${t.length} — ${t.length-n.length} done`];return n.length&&o.push(`failed #${n.map((e=>e.id)).join(", #")}`),e.stopped&&o.push("stopped"),o.join(" · ")}(t)),Pe(t)}catch(e){De=!1,c.queueDrain&&(c.queueDrain.disabled=!1),c.queueProceed&&(c.queueProceed.disabled=!1),c.queueEnqueue&&(c.queueEnqueue.disabled=!1),c.queueStop&&(c.queueStop.hidden=!0),Ue(`drain failed: ${e&&e.message?e.message:e}`)}}}async function Ge(){if(s){c.queueStop&&(c.queueStop.disabled=!0),Ue("stopping…");try{const e=await s.stop(),t=e&&e.cancelled&&e.cancelled.ok;Oe=t?"stopped the running task":"stop requested",Pe(e)}catch(e){Ue(`stop failed: ${e&&e.message?e.message:e}`)}finally{c.queueStop&&(c.queueStop.disabled=!1)}}}async function Qe(e,t){if(s){Ue(`${e} #${t}…`);try{const n=await s[e](t);n&&!1===n.ok?Ue(n.reason||`${e} failed`):Ue(`${"retry"===e?"re-queued":"removed"} #${t}`),Pe(n)}catch(t){Ue(`${e} failed: ${t&&t.message?t.message:t}`)}}}function We(e){e&&"object"==typeof e&&e.drain&&function(e){if(!c.queueAuto||!e||"object"!=typeof e)return;const t=!0===e.enabled;if(c.queueAuto.checked=t,c.queueAutoInterval){c.queueAutoInterval.disabled=!t;const n=Number(e.intervalMs);Number.isFinite(n)&&(c.queueAutoInterval.value=String(n))}if(c.queueAutoLabel&&(c.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"),!c.queueAutoHint)return;if(!t)return void(c.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"),c.queueAutoHint.textContent=n.join(" · ")}(e.drain)}async function Ve(e){if(!a||"function"!=typeof a.setDrain)return;const t={enabled:Boolean(e)};c.queueAutoInterval&&c.queueAutoInterval.value&&(t.intervalMs=Number(c.queueAutoInterval.value));try{const e=await a.setDrain(t);e&&!1===e.ok&&c.queueAutoHint&&(c.queueAutoHint.textContent=e.error||"could not save that"),We(e)}catch(e){c.queueAutoHint&&(c.queueAutoHint.textContent=`could not save that: ${e&&e.message?e.message:e}`)}}function Ye(e){if(!e||"object"!=typeof e)return;const t=null==e.taskId?"":`#${e.taskId} `;if("start"===e.type)Ue(`${t}running${e.model?` on ${e.model}`:""}…`);else if("tool"===e.type&&e.tool)Ue(`${t}${$n(e.tool)}`);else if("finish"===e.type)Ue(`${t}${e.ok?"done":"failed"} — refreshing`),_e();else if("recovered"===e.type){const t=Array.isArray(e.ids)?e.ids:[];Ue(`recovered ${t.length} stalled task${1===t.length?"":"s"}`)}else"locked"===e.type?Ue("another drain is already running"):"queued"===e.type&&Ue(`queued phase ${e.phase}`)}function ze(e){const t=e&&e.prompt,o=e&&e.response;if(!t||!o)return;O||(O=Nn());const s=O,a=e&&e.model||"",i=e&&e.class||"",r=i||a?[i?i.toUpperCase():"",a].filter(Boolean).join(" · "):void 0;vn("user",t),vn("assistant",o,r,s),D.push({role:"user",content:t}),D.push({role:"assistant",content:o}),n.append(s,{role:"user",content:t}).catch((()=>{})),n.append(s,{role:"assistant",content:o}).catch((()=>{}))}const Je=10,Xe=6,Ze=50,et={entries:[],query:"",source:"",role:"",error:"",upgrade:null,local:!1,loading:!1};function tt(){if(nt())return!0;if(Mt())return!0;if(Dt())return!0;if(Kt())return!0;if(ot())return!0;if(st&&"function"==typeof st.isOpen)try{return!!st.isOpen()}catch(e){return!1}return!1}function nt(){return!!c.memoryOverlay&&!c.memoryOverlay.hidden}function ot(){return!!c.keysOverlay&&!c.keysOverlay.hidden}let st=null,at=null,it=!1;async function rt(e){if(!at)return;if(it&&!e)return;c.ptHint&&(c.ptHint.textContent="listing providers…");const n=await async function(){let e=[];try{e=await t.listClasses()||[]}catch(e){return c.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}();it=!0,at.set(n)}function lt(e){e&&e.class&&Array.from(c.classSelect.options).some((t=>t.value===e.class))&&(c.classSelect.value=e.class,localStorage.setItem(d,e.class),ie(e.class),Hn(e.class).then((()=>{e.model&&Array.from(c.modelSelect.options).some((t=>t.value===e.model))&&(c.modelSelect.value=e.model,c.modelSelect.dispatchEvent(new Event("change")))})))}const ct="aegis.companion.dismissed";function dt(){const e={keyConfigured:null===de?void 0:de};return Array.isArray(et.entries)&&et.entries.length&&(e.memoryCount=et.entries.length),pe&&"downloaded"===pe.status&&pe.version&&(e.updatePending=String(pe.version)),U.length&&c.modelSelect&&c.modelSelect.options.length>1&&(e.modelCount=c.modelSelect.options.length),e}function ut(){if(!window.aegisCompanion||!c.companionCard||!c.companionText)return;const e=new Date;let t=null;try{t=JSON.parse(localStorage.getItem(ct)||"null")}catch{t=null}if(window.aegisCompanion.dismissedToday(t,e))return void(c.companionCard.hidden=!0);const n=window.aegisCompanion.pickMessage(dt(),e);n&&n.text?(c.companionText.textContent=n.text,c.companionCard.dataset.kind=n.kind,c.companionCard.dataset.messageId=n.id,c.companionCard.hidden=!1):c.companionCard.hidden=!0}function mt(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 pt(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 yt(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(pt):[];return o&&o.upgrade?{entries:a,error:"",upgrade:o.upgrade,local:!0===o.local}:{entries:a,error:"",upgrade:null,local:o&&!0===o.local}}catch(e){const t=e&&e.status,n=e&&e.data&&e.data.error;return 402===t||"free_session_limit_reached"===n?{entries:[],error:"",upgrade:{url:e.data&&e.data.upgradeUrl||L("memory_quota"),used:e.data&&(null!=e.data.tokensUsed?e.data.tokensUsed:e.data.sessionsUsed),limit:e.data&&(null!=e.data.tokenLimit?e.data.tokenLimit:e.data.freeSessionLimit)}}:{entries:[],error:`search failed: ${e&&e.message?e.message:e}`,upgrade:null,local:!1}}}function ft(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 ht(e,t,n,o,s){if(!e)return;const a=null!=t.used?ft(t.used):"?",i=null!=t.limit?ft(t.limit):"?";e.textContent=`${n||"sync limit reached"} — ${a} of ${i} tokens synced. Nothing was lost. ${x} `,I(e,t.url,s||"memory_quota",o||"See what Pro covers →")}function gt(e,t){ht(c.memoryHint,e,t)}async function vt(e){c.memoryHint.textContent="searching…";const t=await yt(e,Je);(function(e,t,n,o=!1){c.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)>=Xe))}(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;c.tabMemory&&(c.tabMemory.hidden=!(t||n||o)),c.memoryBox&&(c.memoryBox.hidden=!n),c.memoryQuiet&&(c.memoryQuiet.hidden=!o),c.tabMemory&&c.tabMemory.hidden&&"memory"===jn&&Gn("sessions")}({hasAny:s.length>0,hasBox:a,quietNotice:i}),a){if(n){const e=document.createElement("li");return e.className="empty mem-side-upgrade",c.memoryResults.appendChild(e),void I(e,n.url,"memory_quota","Free plan limit reached — see what Pro covers →")}if(t){const e=document.createElement("li");return e.className="empty",e.textContent=t,void c.memoryResults.appendChild(e)}if(!s.length){const e=document.createElement("li");return e.className="empty",e.textContent="no memory entries",void c.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),c.memoryResults.appendChild(t)}}})(t.entries,t.error,t.upgrade,""===e),t.upgrade?gt(t.upgrade,"cloud memory needs an active plan"):t.local?c.memoryHint.textContent=Ct:c.memoryHint.textContent=t.error||""}const Ct="offline — showing this device’s saved copy";function kt(e,t){const n=document.createElement("span");return n.className="mem-chip"+(t?` ${t}`:""),n.textContent=e,n}function bt(e){const t=document.createElement("li");t.className="mem-card";const n=document.createElement("div");n.className="mem-card-head",n.appendChild(kt(e.source,"src")),e.role&&n.appendChild(kt(e.role,"role")),null!=e.importance&&n.appendChild(kt(`imp ${e.importance}`,"imp")),e.sentiment&&n.appendChild(kt(e.sentiment,"sent")),e.summary&&n.appendChild(kt("summary","flag"));const o=document.createElement("span");o.className="mem-card-meta";const s=[],a=mt(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(kt(t,"pill"));t.appendChild(e)}return i.addEventListener("click",(()=>{window.getSelection&&String(window.getSelection())||t.classList.toggle("expanded")})),t}function wt(e){const t=new Map;for(const n of et.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 xt(){if(!nt())return;const e=et.entries.length;if(c.memoryList.innerHTML="",function(){if(c.memoryChips.innerHTML="",et.upgrade||et.error)return;const e=[["source","source",wt("source")],["role","role",wt("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"+(et[t]===n?" on":""),o.textContent=`${n} ${s}`,o.addEventListener("click",(()=>{et[t]=et[t]===n?"":n,xt()})),e.appendChild(o)}c.memoryChips.appendChild(e)}}(),et.loading)return void(c.memoryCount.textContent="loading…");if(et.upgrade){c.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!=et.upgrade.used?ft(et.upgrade.used):"?",s=null!=et.upgrade.limit?ft(et.upgrade.limit):"?";return n.textContent=`This account has used ${o} of ${s} tokens of synced conversation. Saved memory is still readable — only new saves are paused until there is room again. `+x,e.appendChild(t),e.appendChild(n),c.memoryList.appendChild(e),void I(e,et.upgrade.url,"memory_quota","Open subscribe page ↗")}if(et.error){c.memoryCount.textContent="";const e=document.createElement("li");return e.className="mem-empty",e.textContent=et.error,void c.memoryList.appendChild(e)}if(!e){c.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 c.memoryList.appendChild(e)}const t=et.query.trim().toLowerCase(),n=et.entries.filter((e=>(!et.source||e.source===et.source)&&(!et.role||e.role===et.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(et.entries.map((e=>e.source))).size,s=et.local?`offline · saved on this device · ${o} source${1===o?"":"s"}`:`${o} source${1===o?"":"s"}`;if(c.memoryCount.textContent=`${n.length} of ${e} shown · ${s}`+(e>=Ze?` · newest ${Ze}`:""),!n.length){const e=document.createElement("li");return e.className="mem-empty",e.textContent="Nothing matches those filters.",void c.memoryList.appendChild(e)}for(const e of n)c.memoryList.appendChild(bt(e))}async function Et(e){et.loading=!0,et.error="",et.upgrade=null,et.local=!1,xt();const t=await yt(e,Ze);et.entries=t.entries,et.error=t.error,et.upgrade=t.upgrade,et.local=!0===t.local,et.loading=!1,xt()}function St(){c.memoryOverlay&&(c.memoryOverlay.hidden=!1,document.body.classList.add("memory-open"),c.memoryOverlayQuery.value=c.memoryQuery?c.memoryQuery.value.trim():"",et.query=c.memoryOverlayQuery.value,et.source="",et.role="",xt(),Et(et.query),c.memoryOverlayQuery&&c.memoryOverlayQuery.focus())}function $t(){c.memoryOverlay&&(c.memoryOverlay.hidden=!0,document.body.classList.remove("memory-open"),c.memoryOpen&&c.memoryOpen.focus())}let Lt=null,qt="";function Mt(){return!!c.sessionOverlay&&!c.sessionOverlay.hidden}function Nt(e,t){const n=document.createElement("li");n.className="session-row",n.tabIndex=0;const o=document.createElement("span");o.className="session-title",o.textContent=e&&e.title||e&&e.id||"untitled",n.appendChild(o);const s=document.createElement("span");s.className="session-meta";const a=[],i=e&&Array.isArray(e.messages)&&e.messages.length||0;i&&a.push(`${i} msg${1===i?"":"s"}`),e&&e.updatedAt&&a.push(mt(new Date(e.updatedAt).getTime())||String(e.updatedAt)),t&&e&&e.reason&&a.push(`match: ${e.reason}`),s.textContent=a.join(" · "),n.appendChild(s);const r=()=>{Tt(),io(e.id)};return n.addEventListener("click",r),n.addEventListener("keydown",(e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),r())})),n}function At(e){const t=document.createElement("li");t.className="session-row mem-result-row",t.tabIndex=0;const n=document.createElement("span");n.className="session-title mem-result-body",n.textContent=e&&e.content||"(empty)",t.appendChild(n);const o=document.createElement("span");o.className="session-meta";const s=[];if(e&&e.scope&&s.push(e.scope),e&&e.updated){const t=mt(new Date(e.updated).getTime());s.push(t||String(e.updated))}e&&Array.isArray(e.tags)&&e.tags.length&&s.push(e.tags.slice(0,4).join(", ")),o.textContent=s.join(" · "),t.appendChild(o);const a=()=>{Tt(),St(),c.memoryOverlayQuery&&Lt&&(c.memoryOverlayQuery.value=Lt,et.query=Lt,xt(),Et(Lt))};return t.addEventListener("click",a),t.addEventListener("keydown",(e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),a())})),t}function Ht(e,t){const n=document.createElement("li");return n.className="session-section-head",n.setAttribute("role","presentation"),n.textContent=null==t?e:`${e} · ${t}`,n}async function Bt(e){const t=String(null==e?"":e).trim();if(Lt=t,c.sessionHint&&(c.sessionHint.textContent=t?`searching “${t}”…`:""),!n||"function"!=typeof n.searchSessions)return void(c.sessionHint&&(c.sessionHint.textContent="session search is unavailable in this build."));let o=null;try{o=await n.searchSessions(t,50)}catch(e){return void(c.sessionHint&&(c.sessionHint.textContent=`search failed: ${e&&e.message||e}`))}t===Lt&&(c.sessionHint&&(c.sessionHint.textContent=""),function(e,t){if(!c.sessionList)return;c.sessionList.innerHTML="";const n=e&&e.sessions||[],o=e&&e.memory||[],s=e&&e.memoryStatus||"ok",a="ok"!==s,i="memory"!==qt,r=i?n:[];if(c.sessionCount){const t=[`${r.length} session${1===r.length?"":"s"}`];a?t.push("unavailable"===s?"memory needs Node ≥ 22.5":"memory index unreadable"):t.push(`${o.length} memor${1===o.length?"y":"ies"}`),e&&Number.isInteger(e.total)&&e.total>r.length&&i&&(t[0]=`${r.length} of ${e.total} sessions`),c.sessionCount.textContent=t.join(" · ")}if(r.length||o.length){if(r.length){c.sessionList.appendChild(Ht("Sessions",r.length));for(const e of r)c.sessionList.appendChild(Nt(e,t))}if(o.length){c.sessionList.appendChild(Ht("Memory",o.length));for(const e of o)c.sessionList.appendChild(At(e))}}else{const e=document.createElement("li");if(e.className="empty",a){const t="unavailable"===s?"needs Node ≥ 22.5":"index could not be read";e.textContent=i?`no matching sessions — memory search ${t}`:`memory search ${t}`}else e.textContent=t?`nothing matches “${t}”`:"nothing to search yet — start a conversation or save a memory";c.sessionList.appendChild(e)}}(o,t))}function It(e){c.sessionOverlay&&(qt="memory"===e?"memory":"",c.sessionOverlay.hidden=!1,document.body.classList.add("memory-open"),c.sessionQuery&&(c.sessionQuery.value="",c.sessionQuery.focus()),c.sessionHint&&(c.sessionHint.textContent="memory"===qt?"memory only — clear to search everything":""),Bt(""))}function Rt(){It("memory")}function Tt(){c.sessionOverlay&&(c.sessionOverlay.hidden=!0,document.body.classList.remove("memory-open"))}let Ot=null;function Dt(){return!!c.importOverlay&&!c.importOverlay.hidden}function Ut(){c.importOverlay&&(c.importOverlay.hidden=!0,document.body.classList.remove("memory-open"),c.importSessionBtn&&c.importSessionBtn.focus())}function Ft(e){const t=document.createElement("li");t.className="import-row";const n=document.createElement("span");n.className="import-source",n.textContent=e.label||e.id,t.appendChild(n);const o=document.createElement("span");if(o.className="session-meta",e.present)if(e.unreadable)o.textContent="found, store not readable yet",t.classList.add("import-absent");else if(e.count){const t=e.messages?` · ${e.messages} msg${1===e.messages?"":"s"}`:"";o.textContent=`${e.count} session${1===e.count?"":"s"}${t}${e.verified?"":" · best-effort"}`}else o.textContent="found, no conversations";else o.textContent="not installed",t.classList.add("import-absent");return t.appendChild(o),t}async function Pt(){c.importOverlay&&(c.importOverlay.hidden=!1,document.body.classList.add("memory-open"),c.importList&&(c.importList.innerHTML=""),c.importSessionsBtn&&(c.importSessionsBtn.disabled=!0),c.importHint&&(c.importHint.textContent="scanning this machine…"),await async function(){if(!n||"function"!=typeof n.sessionsImportScan)return c.importHint&&(c.importHint.textContent="import is unavailable in this build."),null;c.importHint&&(c.importHint.textContent="scanning this machine…");try{Ot=await n.sessionsImportScan()}catch(e){return c.importHint&&(c.importHint.textContent=`scan failed: ${e&&e.message||e}`),null}return function(e){if(!c.importList)return;c.importList.innerHTML="";const t=e&&e.sources||[],n=e&&e.totals||{};if(c.importCount&&(c.importCount.textContent=`${n.sessions||0} session(s), ${n.messages||0} msg(s)`),!t.length){const e=document.createElement("li");return e.className="empty",e.textContent="no other AI tools were looked for",void c.importList.appendChild(e)}for(const e of t)c.importList.appendChild(Ft(e));const o=(n.sessions||0)>0;c.importSessionsBtn&&(c.importSessionsBtn.disabled=!o),c.importHint&&(c.importHint.textContent=o?"read-only scan — nothing is copied until you press Import sessions":"nothing importable was found; the Memory card can still import memory fragments")}(Ot),Ot}())}async function _t(){if(!n||"function"!=typeof n.sessionsImport)return;const e=c.importSessionsBtn;e&&(e.disabled=!0),c.importHint&&(c.importHint.textContent="copying sessions into AEGIS…");try{const e=await n.sessionsImport({confirm:!0,limit:500,sync:!(!c.importSync||!c.importSync.checked)});if(!e||!e.ok)return void(c.importHint&&(c.importHint.textContent=`import stopped: ${e&&e.reason||"unknown error"}`));const t=e.skippedExisting?`, ${e.skippedExisting} already here`:"";c.importHint&&(c.importHint.textContent=`imported ${e.imported} session(s)${t}.`),await Xn()}catch(e){c.importHint&&(c.importHint.textContent=`import failed: ${e&&e.message||e}`)}finally{e&&(e.disabled=!1)}}
|
|
4
4
|
// at all before this: the AGPL lived in file headers and LICENSE, the plain
|
|
5
|
-
function Dt(){return!!c.creditsOverlay&&!c.creditsOverlay.hidden}function Ft(e,t){const n=document.createElement("section");n.className="credits-section";const o=document.createElement("h3");o.textContent=e,n.appendChild(o);const s=document.createElement("ul");s.className="credits-rows";for(const e of t){const t=document.createElement("li");t.className="credits-row";const n=document.createElement("span");n.className="credits-name",n.textContent=e.name||"",t.appendChild(n);const o=document.createElement("span");if(o.className="credits-meta",o.textContent=[e.version,e.licence,e.copyright].filter(Boolean).join(" · "),t.appendChild(o),e.url){const n=document.createElement("a");n.href=e.url,n.textContent=e.url.replace(/^https?:\/\//,""),n.target="_blank",n.rel="noopener noreferrer",t.appendChild(n)}s.appendChild(t)}return n.appendChild(s),n}function Pt(e){if(!c.creditsBody)return;c.creditsBody.innerHTML="";const t=e&&"object"==typeof e?e:{},n=t.program||{};c.creditsLicenceTag&&(c.creditsLicenceTag.textContent=n.licence||"");const o=document.createElement("section");o.className="credits-section";const s=document.createElement("h3");s.textContent="This program",o.appendChild(s);const a=document.createElement("p");if(a.className="credits-line",a.textContent=`${n.name||"AGPL"} — ${n.licence||""}`,o.appendChild(a),n.copyright){const e=document.createElement("p");e.className="credits-line",e.textContent=n.copyright,o.appendChild(e)}if(n.url){const e=document.createElement("p");e.className="credits-line";const t=document.createElement("a");t.href=n.url,t.textContent="Full licence text",t.target="_blank",t.rel="noopener noreferrer",e.appendChild(t),o.appendChild(e)}if(n.source){const e=document.createElement("p");e.className="credits-line";const t=document.createElement("a");t.href=n.source,t.textContent="Corresponding source",t.target="_blank",t.rel="noopener noreferrer",e.appendChild(t),o.appendChild(e)}if(n.notice){const e=document.createElement("pre");e.className="credits-notice",e.textContent=n.notice,o.appendChild(e)}if(c.creditsBody.appendChild(o),Array.isArray(t.code)&&t.code.length&&c.creditsBody.appendChild(Ft("Vendored third-party code",t.code)),Array.isArray(t.fonts)&&t.fonts.length&&c.creditsBody.appendChild(Ft("Vendored webfonts",t.fonts)),Array.isArray(t.missing)&&t.missing.length){const e=document.createElement("p");e.className="hint",e.textContent=`Could not read: ${t.missing.join(", ")} — the in-app attribution list may be incomplete.`,c.creditsBody.appendChild(e)}}function _t(){c.creditsOverlay&&(c.creditsOverlay.hidden=!1,document.body.classList.add("memory-open"),async function(){if(!c.creditsBody)return;if(c.creditsStatus&&(c.creditsStatus.textContent="loading…"),!e||"function"!=typeof e.credits)return Pt(null),void(c.creditsStatus&&(c.creditsStatus.textContent=""));let t=null;try{t=await e.credits()}catch(e){return void(c.creditsStatus&&(c.creditsStatus.textContent=`could not read the licence files: ${e&&e.message||e}`))}c.creditsStatus&&(c.creditsStatus.textContent=""),Pt(t)}())}function Kt(){c.creditsOverlay&&(c.creditsOverlay.hidden=!0,document.body.classList.remove("memory-open"))}async function jt(t){if(!e.memoryImport)return;const n=t&&t.hint||c.memoryHint;c.memoryImportBtn.disabled=!0,n.textContent="scanning for other AI tool memory…";try{const t=await e.memoryImport({confirm:!1});if(!t||!t.totals||!t.totals.entries)return void(n.textContent=t&&t.summary?t.summary:"nothing found.");const o=(t.sources||[]).filter((e=>e.present&&e.count>0)).map((e=>`${e.label}: ${e.count}`)).join(" · ");n.textContent=`importing ${t.totals.entries} entries — ${o}`;const s=await e.memoryImport({confirm:!0,limit:1e3});if(s&&s.upgrade)return ht(n,s.upgrade,`import stopped after ${s.saved||0} entries`),void await Qt();const a=s&&s.queued?` (${s.queued} queued offline)`:"";n.textContent=s&&s.ok?`imported ${s.saved} entries${a}.`:`import stopped: ${s&&s.reason||"unknown error"}`,await Qt()}catch(e){n.textContent=`import failed: ${e&&e.message?e.message:e}`}finally{c.memoryImportBtn.disabled=!1}}async function Gt(){const t=nt()&&c.memoryOverlayEntry?c.memoryOverlayEntry:c.memoryEntry;if(!t)return;const n=t.value.trim();if(n){c.memorySaveBtn.disabled=!0,c.memoryOverlaySave&&(c.memoryOverlaySave.disabled=!0),c.memoryHint.textContent="saving…";try{const o=await e.memorySave({text:n,source:"aegis-desktop"});if(o&&o.upgrade)return gt(o.upgrade,"free plan limit reached"),void await Qt();t.value="",c.memoryHint.textContent=o&&o.queued?"saved offline — syncs when AEGIS is reachable.":"saved.",await Qt()}catch(e){c.memoryHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{c.memorySaveBtn.disabled=!1,c.memoryOverlaySave&&(c.memoryOverlaySave.disabled=!1)}}}async function Qt(){const e=c.memoryQuery?c.memoryQuery.value.trim():"";await vt(e),nt()&&await St(et.query)}function Wt(){const e=dt();return void 0===e.keyConfigured&&delete e.keyConfigured,e}function Vt(){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(Wt(),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 Yt="aegis.welcomeAiLine",zt=120,Jt=200;function Xt(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 Zt(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 en(){const e=document.getElementById("welcome-template");if(!e)return;c.messages.innerHTML="",c.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?"}(),Vt(),async function(){const e=document.getElementById("welcome-personal");if(!e)return;if(void 0===t||!t||"function"!=typeof t.chat)return;if(!(!0===de||c.modelSelect&&c.modelSelect.options&&c.modelSelect.options.length>1))return;const n=new Date,o=function(e){let t=null;try{t=JSON.parse(localStorage.getItem(Yt)||"null")}catch{t=null}return t&&"string"==typeof t.text&&t.text?t.day!==Xt(e)?null:t.text:null}(n);if(o)return e.textContent=o,e.dataset.kind="ai",void(e.hidden=!1);const s=Wt(),a=c.classSelect&&c.classSelect.value?c.classSelect.value:"aegis",i=c.modelSelect&&c.modelSelect.value?c.modelSelect.value:"",r={class:a,prompt:Zt(s),maxTokens:zt,tools:!1,singlePass:!0,effort:"low",bestEffort:!0};i&&(r.model=i);let l=null;try{l=await t.chat(r)}catch{return}const d=l&&l.choices&&l.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>Jt){const e=n.slice(0,Jt),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(Yt,JSON.stringify({day:Xt(n),text:u}))}catch{}}}();const n=document.getElementById("welcome-byok");n&&n.addEventListener("click",sn);const o=document.getElementById("welcome-cloud");o&&o.addEventListener("click",an);const s=document.getElementById("welcome-dismiss");s&&s.addEventListener("click",ln),tn()}function tn(){const e=document.getElementById("welcome-connect");if(!e)return;let t=!1;try{t="on"===localStorage.getItem(h)}catch{}const n=!0!==de,o=!0!==ue;e.hidden=t||!n&&!o,nn("welcome-cloud",!n),nn("welcome-cloud-note",!n),nn("welcome-byok",!o),nn("welcome-byok-note",!o)}function nn(e,t){const n=document.getElementById(e);n&&(n.hidden=t)}function on(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 sn(){if(rn("byok"),Array.from(c.classSelect.options).some((e=>"byok"===e.value))&&"byok"!==c.classSelect.value&&(c.classSelect.value="byok",c.classSelect.dispatchEvent(new Event("change"))),on(c.settingsList),!1===de&&c.apiKeyHint&&(c.apiKeyHint.textContent="BYOK needs an AEGIS key too — the handling fee is billed to it. Paste one above, then add your provider key below."),!1===de&&c.apiKeyInput)return c.apiKeyInput.focus(),void on(c.apiKeyInput);const e=c.settingsList?c.settingsList.querySelector('.setting-row input[type="password"]'):null;e&&e.focus()}function an(){rn("cloud"),on(c.apiKeyInput),c.apiKeyInput&&c.apiKeyInput.focus()}function rn(e){const t=c.apiKeyHint;if(!t)return;t.textContent="","byok"===e?t.appendChild(document.createTextNode("Bring your own key: everything on this machine stays free, and a local model server needs no account at all. A key relayed through AEGIS is a cloud turn, so it bills a small handling fee — paste the AEGIS key here, then add the provider key in Provider settings. No key yet? ")):t.appendChild(document.createTextNode(`Connect AEGIS Cloud: ${x} Paste your AEGIS key, then Save. Free key at `));const n=document.createElement("a");n.href=w,n.target="_blank",n.rel="noreferrer noopener",n.textContent="aegiscloud.org",t.appendChild(n),t.appendChild(document.createTextNode("."))}function ln(){try{localStorage.setItem(h,"on")}catch{}const e=document.getElementById("welcome-connect");e&&(e.hidden=!0)}const cn="aegis.keysPopupDismissed";function dn(){const e=!0===de,t=!0===ue;c.keysAegisState&&(c.keysAegisState.textContent=e?"set":"not set"),c.keysByokState&&(c.keysByokState.textContent=t?"set":"not set"),c.keysRowAegis&&c.keysRowAegis.classList.toggle("set",e),c.keysRowByok&&c.keysRowByok.classList.toggle("set",t),c.keysCount&&(c.keysCount.textContent=(e?1:0)+(t?1:0)+" / 2"),c.keysAccount&&(c.keysAccount.hidden=!he,c.keysAccount.textContent=he?`The AEGIS account key could not be set up: ${he}.`:""),c.keysAccountRetry&&(c.keysAccountRetry.hidden=!he),c.keysHint&&(c.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 un(){c.keysOverlay&&(c.keysOverlay.hidden=!0,document.body.classList.remove("keys-open"))}function mn(){try{localStorage.setItem(cn,"on")}catch{}un()}function pn(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 yn(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",pn(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=wn(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 c.messages.appendChild(a),ee(),a}function fn(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${++W}`;e.dataset.session=o,V.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 En(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 bn(t.tool):void xn(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:`${G}\n\n${n.path.hint}`,prompt:`Original request:\n${n.prompt}\n\n${n.path.hint}`,model:n.model,maxTokens:Math.min(n.maxTokens||1024,1024),tools:!1,singlePass:!0,sessionId:o,bestEffort:!0},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)";pn(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 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}),h=fmtRoll(f);h&&m.push(`session: ${h}`),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{V.delete(o);const t=e.querySelector(".flow-abort");t&&t.remove()}}(s,{...o,path:e}),s}function hn(){return R||(R=yn("assistant",""),R.classList.remove("pending"),R)}function gn(e,{cancellable:t}={}){if(c.send.disabled=e,c.prompt.disabled=e,e){R=yn("assistant",""),R.classList.add("pending");const e=document.createElement("span");e.className="typing-dots";for(let t=0;t<3;t++)e.appendChild(document.createElement("span"));R.querySelector(".body").appendChild(e);const n=document.createElement("span");if(n.className="typing-tokens",n.hidden=!0,R.appendChild(n),t){const e=document.createElement("button");e.type="button",e.className="cancel-btn",e.textContent="cancel",e.addEventListener("click",(()=>ne())),R.appendChild(e)}}else R&&(R.remove(),R=null)}const vn=72,kn=new Set(["editFile","writeFile","Edit","Write","MultiEdit"]),Cn=new Map;function bn(e){if(!e||!kn.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&&Cn.set(e.id,n)}function wn(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>vn?`${i.slice(0,vn-1)}…`:i;return`→ ${t}${r?` ${r}`:""} ${o}`}function xn(t,n,o,s){if(!t)return;let a=t.querySelector(`.${o}`);if(!a){a=document.createElement("div"),a.className=o;const e=s?t.querySelector(s):null;e?t.insertBefore(a,e):t.appendChild(a)}const i=n&&null!=n.id?Cn.get(n.id):null;if(i){Cn.delete(n.id);const t=renderDiffBlock(i,document);if(t)return a.appendChild(t),function(t,n){if(!t||!n||null==n.id||!1===n.ok)return;if("writeFile"!==n.name&&"editFile"!==n.name)return;if(!e||"function"!=typeof e.undoMutation)return;const o=document.createElement("div");o.className="diff-undo-row";const s=document.createElement("span");s.className="diff-undo-link",s.textContent="⎿ undo this edit",s.setAttribute("role","button"),s.tabIndex=0;const a=async()=>{s.removeEventListener("click",a),s.tabIndex=-1,s.textContent="⎿ undoing…";try{const t=await e.undoMutation(O,n.id);s.textContent=t&&t.ok?"⎿ "+("deleted"===t.restored?"undone — file deleted (it was new)":"undone — content restored"):`⎿ undo failed — ${t&&t.error||"unknown error"}`,s.className=t&&t.ok?"diff-undo-link diff-undo-done":"diff-undo-link diff-undo-failed"}catch(e){s.textContent=`⎿ undo failed — ${e&&e.message||e}`,s.className="diff-undo-link diff-undo-failed"}};s.addEventListener("click",a),s.addEventListener("keydown",(e=>{!e||"Enter"!==e.key&&" "!==e.key||("function"==typeof e.preventDefault&&e.preventDefault(),a())})),o.appendChild(s),t.appendChild(o)}(a,n),a}const r=document.createElement("div");return r.textContent=wn(n),a.appendChild(r),a}function Sn(e){return e.startsWith("@@")?"diff-hunk":e.startsWith("+++")||e.startsWith("---")?"diff-file":e.startsWith("+")?"diff-add":e.startsWith("-")?"diff-del":"diff-ctx"}function En(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=Sn(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":"always"===e?"Always allowed":"Allowed once",s.appendChild(o),t.respondApproval(n.id,e)})(a))),i};if(r.appendChild(l("Allow once","allow","once")),r.appendChild(l("Allow for this session","allow-session","session")),n.canPersist){const e=l("Always allow this command","allow-always","always");e.title="Stores a rule in ~/.aegiscode/permissions.json, shared with the terminal face",r.appendChild(e)}r.appendChild(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 $n(){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 Ln(){try{D=await t.listClasses()||[]}catch(e){D=[],c.modelHint.textContent=`listClasses failed: ${e&&e.message?e.message:e}`}c.classSelect.innerHTML="";for(const e of D){const t=document.createElement("option");t.value=e.class,t.textContent=e.configured?e.label:`${e.label} (not configured)`,c.classSelect.appendChild(t)}const e=localStorage.getItem(d);e&&D.some((t=>t.class===e))&&(c.classSelect.value=e),await qn(c.classSelect.value)}async function qn(e){if(c.autonomousToggleWrap&&(c.autonomousToggleWrap.hidden=e!==g),se(),ie(e),c.modelSelect.hidden=!1,c.modelSelect.disabled=!1,c.modelFree.hidden=!0,c.modelFree.value="",c.modelHint.textContent="",c.modelSelect.innerHTML="",F=new Map,"aegis"===e){const e=document.createElement("option");e.value=i,e.textContent=r,c.modelSelect.appendChild(e)}try{const n=await t.listModels(e),o=Array.isArray(n&&n.models)?n.models:[],s=Boolean(n&&n.needsKey),a=Boolean(n&&n.needsDaemon),i=!(n&&!1===n.listed),r=Boolean(n&&n.providersFailed),l=Array.isArray(n&&n.unmatchedProviders)?n.unmatchedProviders:[];c.modelFree.hidden=!("local"===e&&(a||!i));for(const e of o){F.set(e.id,e);const t=document.createElement("option");t.value=e.id,t.textContent=e.label||e.id,c.modelSelect.appendChild(t)}let d;if(re(),s)d=null;else if(a)d=`No local model server at ${n&&n.baseURL||"the configured address"} — start Ollama, or set Base URL below to llama.cpp / LM Studio, then Refresh.`;else if("local"!==e||i)if("byok"===e&&r)d="Provider catalog unreachable — your saved keys and declared models are unaffected. Refresh to try again."+(n&&n.providersError?` (${n.providersError})`:"");else if(o.length)if("byok"===e&&n&&n.needsAegisKey){const e=n&&n.fee||null;d=`${o.length} model${1===o.length?"":"s"} available — `+(e&&e.require_balance?"an AEGIS account key and a funded balance are required: the BYOK handling fee is billed there.":"an AEGIS account key is required: the BYOK handling fee is billed there.")}else d="byok"===e&&n&&n.needsProviderKey?`${o.length} model${1===o.length?"":"s"} available — add a provider key in Provider settings below to use one.`:`${o.length} model${1===o.length?"":"s"} available.`;else d="local"===e?"No models on this server yet — pull one first (ollama pull llama3.2).":"aegis"===e?"No models to pin — this class runs the pooled route on the server's own default. Use Bring your own key for a per-provider model.":"No models listed.";else d="That address answered but listed no models — not Ollama? Type the model tag in the box above and send.";"byok"===e&&!r&&l.length&&(d=`${d} Not shown: ${l.join(", ")} — declared in models.json, but not in the provider catalog. Check the provider name in Settings.`);const u=maxTokensCeiling(F.get(ae()));if(s){c.modelHint.textContent="Connect Aegis Cloud to load its models: paste your AEGIS API key in the Status card above (";const e=document.createElement("a");return e.href=w,e.target="_blank",e.rel="noreferrer noopener",e.textContent="free key at aegiscloud.org",c.modelHint.appendChild(e),void c.modelHint.appendChild(document.createTextNode("), then Save."))}c.modelHint.textContent=u<FLAT_CEILING?`${d} · max output: ${u.toLocaleString()}`:d}catch(e){F=new Map,c.modelHint.textContent=`listModels failed: ${e&&e.message?e.message:e}`,re()}}function Mn(){if(c.queueModelInput&&!c.queueModelInput.hidden){const e=c.queueModelInput.value.trim();if(e)return e}return c.queueModelSelect?c.queueModelSelect.value:""}async function An(e){if(c.queueModelSelect){if(function(e){const t=c.queueFanout&&c.queueFanout.closest("label");t&&(t.hidden="aegis"!==e)}(e),c.queueModelSelect.hidden=!1,c.queueModelSelect.disabled=!1,c.queueModelInput&&(c.queueModelInput.hidden=!0,c.queueModelInput.value=""),c.queueModelHint&&(c.queueModelHint.textContent=""),c.queueModelSelect.innerHTML="","aegis"===e){const e=document.createElement("option");e.value="",e.textContent="server default (auto)",c.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);c.queueModelInput&&(c.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,c.queueModelSelect.appendChild(t)}if(!c.queueModelHint)return;s?c.queueModelHint.textContent="Connect this class in the Model card above (API key / provider key), then Refresh.":a?c.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&&(c.queueModelHint.textContent="A provider key is required before a queued task on this model can run — add one in the Model card above."):c.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.":c.queueModelHint.textContent="That address answered but listed no models — type the model tag above."}catch(e){c.queueModelHint&&(c.queueModelHint.textContent=`listModels failed: ${e&&e.message?e.message:e}`)}}}function Nn({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 Hn(e){c.settingsHint.textContent="saving…";try{const n=String(null==e?"":e).trim()||b,o=await t.settings.set(k,{baseURL:n}),s=o&&o.baseURL||n;c.settingsHint.textContent=`saved: local model server at ${s}`,await Bn(),await qn(c.classSelect.value)}catch(e){c.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function Bn(){c.settingsList.innerHTML="";const e=[];let n=[];try{n=await t.settings.get()||[]}catch{}Array.isArray(n)&&(n=n.filter((e=>e&&!v.has(e.provider))));{const e=n.find((e=>e&&e.provider===k))||{provider:k,baseURL:"",configured:!1,keyMask:null};c.settingsList.appendChild(function(e){const t=k,n=document.createElement("div");n.className="setting-row",n.dataset.provider=t;const o=document.createElement("div");o.className="setting-name",o.textContent="Local model server",n.appendChild(o);const s=document.createElement("input");s.type="text",s.className="setting-input",s.id="local-base-url",s.autocomplete="off",s.spellcheck=!1,s.placeholder=b,s.value=e.baseURL||"",s.addEventListener("keydown",(e=>{"Enter"===e.key&&Hn(s.value)})),n.appendChild(s);const a=document.createElement("div");a.className="setting-status",a.textContent=e.baseURL?e.baseURL:`default (${b})`,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",(()=>Hn(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===C)continue;const o=`byok:${t.id}`,s=n.find((e=>e.provider===o))||{provider:o,baseURL:"",configured:!1,keyMask:null};c.settingsList.appendChild(Nn({provider:o,name:`BYOK: ${t.label||t.id}`,cfg:s,onSave:e=>On(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),c.settingsList.appendChild(e)}}catch{}try{await async function(e){if(!c.settingsList||!t.userModels)return;const n=await t.userModels.get();if(!n)return;const o=n&&n.map||{},s=(e||[]).map((e=>e&&e.id||"")).filter(Boolean),a=document.createElement("div");a.id="user-models-block";const i=document.createElement("div");i.className="setting-name",i.textContent="Your own models (BYOK)",a.appendChild(i);const r=document.createElement("div");r.className="setting-row",r.dataset.provider="byok:__user-model-add";const l=document.createElement("input");if(l.type="text",l.className="setting-input",l.id="user-model-provider",l.placeholder="provider (deepseek)",l.autocomplete="off",l.spellcheck=!1,s.length){const e=document.createElement("datalist");e.id="user-model-providers";for(const t of s){const n=document.createElement("option");n.value=t,e.appendChild(n)}r.appendChild(e),l.setAttribute("list","user-model-providers")}r.appendChild(l);const d=document.createElement("input");d.type="text",d.className="setting-input",d.id="user-model-id",d.placeholder="model id (deepseek-v4.2-preview)",d.autocomplete="off",d.spellcheck=!1,r.appendChild(d);const u=document.createElement("div");u.className="setting-actions";const m=document.createElement("button");m.type="button",m.className="ghost-btn",m.id="user-model-add",m.textContent="Add model",m.addEventListener("click",(async()=>{const e=l.value.trim(),n=d.value.trim();c.settingsHint.textContent="adding…";try{const o=await t.userModels.add(e,n);c.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 Bn(),await qn(c.classSelect.value)}catch(e){c.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=l.value.trim();if(!e)return void(c.settingsHint.textContent="type a provider id first (the CLI's /byok lists them).");if("function"!=typeof t.userModels.discover)return void(c.settingsHint.textContent="this build cannot ask a provider — type the model id.");let n;c.settingsHint.textContent=`asking ${e}…`,y.hidden=!0,y.textContent="";try{n=await t.userModels.discover(e)}catch(e){return void(c.settingsHint.textContent=`${e&&e.message?e.message:e}`)}if(!n||!n.ok)return void(c.settingsHint.textContent=`${e}: ${n&&n.error||"no answer"}`);c.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()=>{c.settingsHint.textContent=`adding ${n.count}…`;try{const e=await t.userModels.addAll(n.provider,n.ids);c.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 Bn(),await qn(c.classSelect.value)}catch(e){c.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})),r.appendChild(u),r.appendChild(y);const f=document.createElement("div");f.className="setting-status",f.id="user-model-hint",f.textContent=n.file?`saved in ${n.file} — the CLI reads the same file (/model-add)`:"saved beside your AEGIS config — the CLI reads the same file (/model-add)",r.appendChild(f),a.appendChild(r);const h=Object.keys(o).sort();for(const e of h)for(const n of o[e]){const o=document.createElement("div");o.className="setting-row",o.dataset.provider=`byok:${e}`;const i=document.createElement("div");i.className="setting-name",i.textContent=`${e} — ${n}`,o.appendChild(i);const r=document.createElement("div");r.className="setting-status",r.textContent=s.length&&!s.includes(e)?"no provider row for this id — /byok lists the ones the relay takes":"offered in the picker on this machine",o.appendChild(r);const l=document.createElement("div");l.className="setting-actions";const d=document.createElement("button");d.type="button",d.className="ghost-btn danger",d.textContent="Remove",d.addEventListener("click",(async()=>{c.settingsHint.textContent="removing…";try{const o=await t.userModels.remove(e,n);c.settingsHint.textContent=o&&!1===o.removed?`${e}:${n} was not declared.`:`removed ${e}:${n}.`,await Bn(),await qn(c.classSelect.value)}catch(e){c.settingsHint.textContent=`${e&&e.message?e.message:e}`}})),l.appendChild(d),o.appendChild(l),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)}c.settingsList.appendChild(a)}(e)}catch(e){c.settingsHint.textContent=`your own models: ${e&&e.message?e.message:e}`}try{await In()}catch(e){c.customStatus&&(c.customStatus.textContent=`custom provider: ${e&&e.message?e.message:e}`)}}async function In(){if(!c.customBaseUrl)return;let e=null,n=[];try{const n=await t.settings.get()||[],o=(Array.isArray(n)?n:[]).find((e=>e&&e.provider===`byok:${C}`));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[C])?o[C]:[]}catch{}!function(e,t){if(!c.customBaseUrl)return;const n=e||{},o=Array.isArray(t)?t:[];if(!c.customBaseUrl.value&&n.baseURL&&(c.customBaseUrl.value=n.baseURL),c.customKey&&(c.customKey.placeholder=n.configured?`key ${n.keyMask||"••••"} (blank = keep)`:"sk-…",c.customKey.value=""),c.customRemove&&(c.customRemove.disabled=!n.configured&&!n.baseURL),!c.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"),c.customStatus.textContent=s.join(" · ")}(e,n)}async function Rn(){if(!c.customBaseUrl)return;const e=String(c.customBaseUrl.value||"").trim(),n=c.customKey?String(c.customKey.value||"").trim():"",o=c.customModel?String(c.customModel.value||"").trim():"",s=e=>{c.customStatus&&(c.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:${C}`;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(C,o)}catch(e){return s(`endpoint saved, model NOT declared: ${e&&e.message?e.message:e}`),await In(),void await qn(c.classSelect.value).catch((()=>{}))}c.customModel&&(c.customModel.value=""),s(`saved ${e} with model ${o} — pick it under provider "byok", then the model.`),await In(),await Bn(),await qn(c.classSelect.value).catch((()=>{}))}async function Tn(){if(!c.customBaseUrl)return;const e=e=>{c.customStatus&&(c.customStatus.textContent=e)};e("removing…");let n=0;try{const e=await t.userModels.get(),o=e&&e.map||{},s=Array.isArray(o[C])?o[C]:[];for(const e of s)await t.userModels.remove(C,e),n+=1}catch{}try{await t.settings.remove(`byok:${C}`)}catch(t){return void e(`remove failed: ${t&&t.message?t.message:t}`)}c.customBaseUrl&&(c.customBaseUrl.value=""),e(`removed the custom endpoint${n?` and ${n} declared model(s)`:""}.`),await In(),await Bn(),await qn(c.classSelect.value).catch((()=>{}))}async function On(e,n){c.settingsHint.textContent="saving…";try{const o={};n&&(o.key=n),await t.settings.set(e,o),c.settingsHint.textContent="saved.",await Bn(),await qn(c.classSelect.value)}catch(e){c.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function Un(e){c.settingsHint.textContent="removing…";try{await t.settings.remove(e),c.settingsHint.textContent="removed.",await Bn(),await qn(c.classSelect.value)}catch(e){c.settingsHint.textContent=`remove failed: ${e&&e.message?e.message:e}`}}const Dn=["sessions","memory"];let Fn="sessions";function Pn(e){const t=Dn.includes(e)?e:"sessions";Fn=t;for(const e of Dn){const n="sessions"===e?c.paneSessions:c.paneMemory,o="sessions"===e?c.tabSessions:c.tabMemory,s=e===t;n&&(n.hidden=!s),o&&(o.setAttribute("aria-selected",s?"true":"false"),o.classList.toggle("is-active",s))}}const _n=new Set,Kn=3;function jn(e){if(!e||!e.id||!0===e.named||_n.has(e.id))return;const t=(Array.isArray(e.messages)?e.messages:[]).find((e=>e&&"user"===e.role&&e.content));if(!t)return;if(_n.add(e.id),"function"!=typeof n.nameSession)return;const o=c.classSelect?c.classSelect.value:"";n.nameSession({sessionId:e.id,prompt:t.content,class:o,model:ae()}).then((e=>{e&&Gn().catch((()=>{}))})).catch((()=>{}))}async function Gn(){c.sessionsList.innerHTML="",c.sessionsHint.textContent="";let e=[];try{const t=await n.listSessions();e=t&&t.sessions||[]}catch(e){return void(c.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 c.sessionsList.appendChild(e)}let t=Kn;for(const n of e){t>0&&n&&!0!==n.named&&!_n.has(n.id)&&(t-=1,jn(n));const e=document.createElement("li");e.className="session-row",e.tabIndex=0;const o=document.createElement("span");o.className="session-title",o.textContent=n&&n.title||n&&n.id||"untitled",e.appendChild(o);const s=document.createElement("span");s.className="session-meta";const a=n&&Array.isArray(n.messages)&&n.messages.length||0,i=n&&n.updatedAt?new Date(n.updatedAt).toLocaleTimeString():"";s.textContent=`${a} msg${1===a?"":"s"}${i?" · "+i:""}`,e.appendChild(s),e.addEventListener("click",(()=>zn(n.id))),c.sessionsList.appendChild(e)}}function Qn(e){if(!c.syncStatus)return;if(!e)return void(c.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}`),c.syncStatus.textContent=t.join(" · ")}async function Wn(){try{Qn(await n.status())}catch{Qn(null)}}function Vn(){"function"==typeof n.auto&&n.auto().then((e=>{e&&e.upgrade&&ht(c.sessionsHint,e.upgrade,"queued memory is waiting on the free-plan cap","See what Pro covers →")})).catch((()=>{}))}async function Yn(){c.syncNow.disabled=!0,c.sessionsHint.textContent="syncing…";try{const e=await n.push(),t=await n.pull();e.upgrade||t.upgrade?ht(c.sessionsHint,e.upgrade||t.upgrade,"queued memory is waiting on the free-plan cap","See what Pro covers →"):e.ok||t.ok?c.sessionsHint.textContent=`synced (pushed ${e.pushed||0}, pulled ${t.merged||0})`:c.sessionsHint.textContent=`sync failed: ${e.reason||t.reason||"unknown error"}`}catch(e){c.sessionsHint.textContent=`sync failed: ${e&&e.message?e.message:e}`}finally{c.syncNow.disabled=!1,await Wn(),await Gn()}}function zn(e){n.open(e).then((e=>{if(!e)return void(c.sessionsHint.textContent="session not found");c.messages.innerHTML="";const t=Array.isArray(e.messages)?e.messages:[];t.length||en();for(const n of t){const t="assistant"===n.role?"assistant":"system"===n.role?"system":"user";yn(t,n.content||n.text||"",void 0,"assistant"===t?e.id:void 0)}O=e.id,P.set(e.id,rollMessages(t)),K(e.id),U=replayHistory(t),c.sessionsHint.textContent=`opened ${e.id.slice(0,8)}…`})).catch((e=>{c.sessionsHint.textContent=`open failed: ${e&&e.message?e.message:e}`}))}function Jn(t){const n=O;n?e.exportSession(n,t).then((e=>{e&&e.ok?c.sessionsHint.textContent=`exported to ${e.filePath}`:e&&e.canceled||(c.sessionsHint.textContent=`export failed: ${e&&e.reason||"unknown error"}`)})).catch((e=>{c.sessionsHint.textContent=`export failed: ${e&&e.message?e.message:e}`})):c.sessionsHint.textContent="no open session to export"}function Xn(){Y(),O&&t.clearApprovals(O).catch((()=>{})),en(),c.sessionsHint.textContent="",R=null,T=null,J=null,X=null,O=null,U=[],W=0,K(null)}function Zn(e){e&&("open"===e.action&&e.sessionId?zn(e.sessionId):"new"===e.action&&(Xn(),e.prompt&&(c.prompt.value=e.prompt,c.prompt.focus())))}async function eo(){const e=c.prompt.value.trim(),o=to.length?to.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||c.send.disabled)return;const s=c.classSelect.value,a=ae();c.prompt.value="";const i=(r=to,Array.isArray(r)&&r.length?r.map((e=>`📎 ${e.name||e.path}`)).join("\n"):"");var r;const l=i?e?`${e}\n${i}`:i:e;to=[],no=[],ao();const d=++z;J=d,X=null,yn("user",l);const u=s===g&&oe(),m=le(),p=budgetFor(a,void 0,m),y=u&&parseInt(c.autonomousWorkers.value,10)||void 0;O||(O=$n());const f=O;T=f,un();const h=replayHistory(U);U.push({role:"user",content:o&&!so()?mo(e,o):l}),gn(!0,{cancellable:!0}),R&&K(f,{prompt:e,reply:"",reasoning:""}),ee({force:!0});try{await n.append(f,{role:"user",content:l})}catch{}let v="",k="",C=0;const b=[];let w=null;const x=(S=()=>{if(!R)return;if(R.classList.remove("pending"),k){const e=function(e){let t=e.querySelector(".reasoning");if(!t){t=document.createElement("div"),t.className="reasoning";const n=e.querySelector(".body");n?e.insertBefore(t,n):e.appendChild(t)}return t}(R);e.textContent!==k&&(e.textContent=k)}const t=R.querySelector(".body");t&&t.textContent!==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})),ee()},Z?Z.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=hn();return t.classList.remove("pending"),function(e,t,n){if(!e||!t)return null;const o=document.createElement("div");o.className="turn-note",o.textContent=t;const s=n?e.querySelector(n):null;s?e.insertBefore(o,s):e.appendChild(o)}(t,e.note,".body"),void ee()}if(e&&e.approval){const t=hn();return t.classList.remove("pending"),En(t,e.approval,".body"),void ee({force:!0})}if(e&&e.rounds){const n=hn();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 ee({force:!0})}if(e&&e.tool){if("run"===e.tool.phase)return void bn(e.tool);b.push(e.tool);const t=hn();return t.classList.remove("pending"),xn(t,e.tool,"tool-activity",".body"),void ee()}const n=e&&("string"==typeof e.delta?e.delta:e.content);n&&(v+=n,x())};try{const i=await t.chat({class:s,prompt:e,model:a,maxTokens:p,sessionId:f,autonomous:u,effort:m,workers:y,messages:h,attachments:o,roundsAsk:!0},E);if(i&&i.aborted){const e=new Error(i.message||"This operation was aborted");throw e.name="AbortError",e.code="ABORT_ERR",e}const r=i&&i.choices&&i.choices[0]||{},l=r.message&&r.message.content||v||"(empty response)";isPlaceholderContent(l)||U.push({role:"assistant",content:l});const d=[];i&&i.model?d.push(`model: ${i.model}`):a&&d.push(`model: ${a}`),d.push(function(e){const t=D.find((t=>t.class===e));return t?t.label:e}(s)),u?d.push(`autonomous (${m}, ${y||"auto"}w)`):m&&d.push(`effort: ${m}`);const g=turnAccounting(i&&i.usage,a,{costUsd:i&&"number"==typeof i.costUsd?i.costUsd:void 0}),C=displayTokens(g);if(null!=C)d.push(`tokens: ${C}`);else{const t=estimatedBuckets(e,l,l===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!=g.cost&&w&&d.push(fmtCost(g.cost,g.real)),"byok"===s&&null!=g.cost&&w&&d.push("your provider bill (est.) + AEGIS handling fee");const x=_(f,i&&i.usage,{model:a,costUsd:i&&"number"==typeof i.costUsd?i.costUsd:void 0,calls:i&&i.calls,prompt:e,reply:l,reasoning:l===k?"":k}),S=fmtRoll(x,{omitMoney:!w});S&&d.push(`session: ${S}`),i&&i.pooled_notice&&d.push(i.pooled_notice),yn("assistant",l,d.join(" · ")||void 0,f,b);try{await n.append(f,{role:"assistant",content:l,...j(i&&i.usage,a,g,{prompt:e,reply:l,reasoning:l===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{}Vn(),function(){const e=c.exploreToggle;return Boolean(e&&e.checked)}()&&"(empty response)"!==l&&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",(()=>{fn(Q[W%Q.length],a,e)})),a.appendChild(i),t.appendChild(n),t.appendChild(a),c.messages.appendChild(t);for(const t of Q.slice(0,2))fn(t,a,e)}({prompt:e,cls:s,model:a,maxTokens:p,parentSessionId:f})}catch(t){if(isCancellation(t,{userStopped:X===d})){const t=salvageTurn({streamedText:v,reasoningText:k}),o=t.text,s=t.reasoning,i=replayableContent(t.kind,o);U.push({role:"assistant",content:i});const r=turnAccounting(void 0,a,{}),l=_(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}`),yn("assistant",o,c.join(" · "),f,b);try{await n.append(f,{role:"assistant",content:i,...j(void 0,a,r,{prompt:e,reply:o,reasoning:s})})}catch{}Vn()}else yn("assistant",`Error: ${t&&t.message?t.message:t}`,"request failed")}finally{gn(!1),J===d&&(J=null,T=null),Gn()}}let to=[],no=[],oo=0;function so(){return c.classSelect&&"pro"===c.classSelect.value}function ao(){const e=c.attachRow,t=c.attachNote;if(!e)return;e.textContent="";const n=to.length+no.length;if(e.hidden=0===n,t&&(t.hidden=!0,t.textContent=""),n){for(const t of to){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} · ${ro(t.size)}${t.truncated?" (truncated)":""}`,n.appendChild(s),n.appendChild(io((()=>{to=to.filter((e=>e!==t)),ao()}))),e.appendChild(n)}for(const t of no){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(io((()=>{no=no.filter((e=>e!==t)),ao()}))),e.appendChild(n)}if(t&&so()){const e=to.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 io(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 ro(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 lo(t){const n=(t||"").split(/[\\/]/).pop()||t;if(to.length>=8)return no.push({path:t,name:n,reason:"at most 8 files per message"}),void ao();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 no.push({path:t,name:n,reason:o&&o.reason||"not attached"}),void ao();to.some((e=>e.path===o.attachment.path))||(to.push(o.attachment),ao())}const co=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function uo(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 mo(e,t){const n=[],o="string"==typeof e?e:"";o.trim()&&n.push({type:"text",text:o});for(const e of t||[]){const t=uo(e);"image"===e.kind&&e.dataUrl&&co.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 po(){try{me(await e.status())}catch{me(null)}"on"===localStorage.getItem(m)&&(c.autonomousToggle.checked=!0),c.autonomousToggle.addEventListener("change",(()=>{localStorage.setItem(m,c.autonomousToggle.checked?"on":"off"),se()}));const n=localStorage.getItem(p)||localStorage.getItem("aegis.autonomousEffort"),i=Array.from(c.effortSelect.options).some((e=>e.value===n));n&&i?c.effortSelect.value=n:n&&localStorage.setItem(p,c.effortSelect.value),c.effortSelect.addEventListener("change",(()=>{localStorage.setItem(p,c.effortSelect.value),ie(c.classSelect.value)}));const r=localStorage.getItem(y);r&&(c.autonomousWorkers.value=r),c.autonomousWorkers.addEventListener("change",(()=>{localStorage.setItem(y,c.autonomousWorkers.value)})),se();const l=localStorage.getItem(f);c.exploreToggle.checked="on"===l,c.exploreToggle.addEventListener("change",(()=>{localStorage.setItem(f,c.exploreToggle.checked?"on":"off"),c.exploreToggle.checked||Y()})),c.classSelect.addEventListener("change",(()=>{localStorage.setItem(d,c.classSelect.value),ie(c.classSelect.value),qn(c.classSelect.value)})),c.modelSelect.addEventListener("change",(()=>{const e=F.get(c.modelSelect.value),t=maxTokensCeiling(e),n=c.modelHint.textContent.replace(/ · max output: [\d,]+$/,"");c.modelHint.textContent=t<FLAT_CEILING?`${n} · max output: ${t.toLocaleString()}`:n,ie(c.classSelect.value),"byok"===c.classSelect.value&&e&&e.provider&&!1===e.configured&&function(e){if(!c.settingsList||!e)return;const t=c.settingsList.querySelector(`.setting-row[data-provider="byok:${e}"] input[type="password"]`);if(on(c.settingsList),t&&t.focus(),c.modelHint){const t=c.modelHint.textContent.replace(/ — no .* key saved; add it below\.$/,"");c.modelHint.textContent=`${t} — no ${e} key saved; add it below.`}}(e.provider)})),c.modelFree.addEventListener("input",(()=>{ie(c.classSelect.value)})),c.newChat.addEventListener("click",Xn),c.importSessionBtn&&c.importSessionBtn.addEventListener("click",Ot),c.importClose&&c.importClose.addEventListener("click",Rt),c.importBackdrop&&c.importBackdrop.addEventListener("click",Rt),c.importSessionsBtn&&c.importSessionsBtn.addEventListener("click",Ut),c.importMemoryBtn&&c.importMemoryBtn.addEventListener("click",(()=>jt({hint:c.importHint}))),e.onMenuNewChat&&e.onMenuNewChat(Xn),e.onMenuSearch&&e.onMenuSearch(Nt),e.onMenuSearchMemory&&e.onMenuSearchMemory(Et),
|
|
5
|
+
function Kt(){return!!c.creditsOverlay&&!c.creditsOverlay.hidden}function jt(e,t){const n=document.createElement("section");n.className="credits-section";const o=document.createElement("h3");o.textContent=e,n.appendChild(o);const s=document.createElement("ul");s.className="credits-rows";for(const e of t){const t=document.createElement("li");t.className="credits-row";const n=document.createElement("span");n.className="credits-name",n.textContent=e.name||"",t.appendChild(n);const o=document.createElement("span");if(o.className="credits-meta",o.textContent=[e.version,e.licence,e.copyright].filter(Boolean).join(" · "),t.appendChild(o),e.url){const n=document.createElement("a");n.href=e.url,n.textContent=e.url.replace(/^https?:\/\//,""),n.target="_blank",n.rel="noopener noreferrer",t.appendChild(n)}s.appendChild(t)}return n.appendChild(s),n}function Gt(e){if(!c.creditsBody)return;c.creditsBody.innerHTML="";const t=e&&"object"==typeof e?e:{},n=t.program||{};c.creditsLicenceTag&&(c.creditsLicenceTag.textContent=n.licence||"");const o=document.createElement("section");o.className="credits-section";const s=document.createElement("h3");s.textContent="This program",o.appendChild(s);const a=document.createElement("p");if(a.className="credits-line",a.textContent=`${n.name||"AGPL"} — ${n.licence||""}`,o.appendChild(a),n.copyright){const e=document.createElement("p");e.className="credits-line",e.textContent=n.copyright,o.appendChild(e)}if(n.url){const e=document.createElement("p");e.className="credits-line";const t=document.createElement("a");t.href=n.url,t.textContent="Full licence text",t.target="_blank",t.rel="noopener noreferrer",e.appendChild(t),o.appendChild(e)}if(n.source){const e=document.createElement("p");e.className="credits-line";const t=document.createElement("a");t.href=n.source,t.textContent="Corresponding source",t.target="_blank",t.rel="noopener noreferrer",e.appendChild(t),o.appendChild(e)}if(n.notice){const e=document.createElement("pre");e.className="credits-notice",e.textContent=n.notice,o.appendChild(e)}if(c.creditsBody.appendChild(o),Array.isArray(t.code)&&t.code.length&&c.creditsBody.appendChild(jt("Vendored third-party code",t.code)),Array.isArray(t.fonts)&&t.fonts.length&&c.creditsBody.appendChild(jt("Vendored webfonts",t.fonts)),Array.isArray(t.missing)&&t.missing.length){const e=document.createElement("p");e.className="hint",e.textContent=`Could not read: ${t.missing.join(", ")} — the in-app attribution list may be incomplete.`,c.creditsBody.appendChild(e)}}function Qt(){c.creditsOverlay&&(c.creditsOverlay.hidden=!1,document.body.classList.add("memory-open"),async function(){if(!c.creditsBody)return;if(c.creditsStatus&&(c.creditsStatus.textContent="loading…"),!e||"function"!=typeof e.credits)return Gt(null),void(c.creditsStatus&&(c.creditsStatus.textContent=""));let t=null;try{t=await e.credits()}catch(e){return void(c.creditsStatus&&(c.creditsStatus.textContent=`could not read the licence files: ${e&&e.message||e}`))}c.creditsStatus&&(c.creditsStatus.textContent=""),Gt(t)}())}function Wt(){c.creditsOverlay&&(c.creditsOverlay.hidden=!0,document.body.classList.remove("memory-open"))}async function Vt(t){if(!e.memoryImport)return;const n=t&&t.hint||c.memoryHint;c.memoryImportBtn.disabled=!0,n.textContent="scanning for other AI tool memory…";try{const t=await e.memoryImport({confirm:!1});if(!t||!t.totals||!t.totals.entries)return void(n.textContent=t&&t.summary?t.summary:"nothing found.");const o=(t.sources||[]).filter((e=>e.present&&e.count>0)).map((e=>`${e.label}: ${e.count}`)).join(" · ");n.textContent=`importing ${t.totals.entries} entries — ${o}`;const s=await e.memoryImport({confirm:!0,limit:1e3});if(s&&s.upgrade)return ht(n,s.upgrade,`import stopped after ${s.saved||0} entries`),void await zt();const a=s&&s.queued?` (${s.queued} queued offline)`:"";n.textContent=s&&s.ok?`imported ${s.saved} entries${a}.`:`import stopped: ${s&&s.reason||"unknown error"}`,await zt()}catch(e){n.textContent=`import failed: ${e&&e.message?e.message:e}`}finally{c.memoryImportBtn.disabled=!1}}async function Yt(){const t=nt()&&c.memoryOverlayEntry?c.memoryOverlayEntry:c.memoryEntry;if(!t)return;const n=t.value.trim();if(n){c.memorySaveBtn.disabled=!0,c.memoryOverlaySave&&(c.memoryOverlaySave.disabled=!0),c.memoryHint.textContent="saving…";try{const o=await e.memorySave({text:n,source:"aegis-desktop"});if(o&&o.upgrade)return gt(o.upgrade,"free plan limit reached"),void await zt();t.value="",c.memoryHint.textContent=o&&o.queued?"saved offline — syncs when AEGIS is reachable.":"saved.",await zt()}catch(e){c.memoryHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{c.memorySaveBtn.disabled=!1,c.memoryOverlaySave&&(c.memoryOverlaySave.disabled=!1)}}}async function zt(){const e=c.memoryQuery?c.memoryQuery.value.trim():"";await vt(e),nt()&&await Et(et.query)}function Jt(){const e=dt();return void 0===e.keyConfigured&&delete e.keyConfigured,e}function Xt(){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(Jt(),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 Zt="aegis.welcomeAiLine",en=120,tn=200;function nn(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 on(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 sn(){const e=document.getElementById("welcome-template");if(!e)return;c.messages.innerHTML="",c.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?"}(),Xt(),async function(){const e=document.getElementById("welcome-personal");if(!e)return;if(void 0===t||!t||"function"!=typeof t.chat)return;if(!(!0===de||c.modelSelect&&c.modelSelect.options&&c.modelSelect.options.length>1))return;const n=new Date,o=function(e){let t=null;try{t=JSON.parse(localStorage.getItem(Zt)||"null")}catch{t=null}return t&&"string"==typeof t.text&&t.text?t.day!==nn(e)?null:t.text:null}(n);if(o)return e.textContent=o,e.dataset.kind="ai",void(e.hidden=!1);const s=Jt(),a=c.classSelect&&c.classSelect.value?c.classSelect.value:"aegis",i=c.modelSelect&&c.modelSelect.value?c.modelSelect.value:"",r={class:a,prompt:on(s),maxTokens:en,tools:!1,singlePass:!0,effort:"low",bestEffort:!0};i&&(r.model=i);let l=null;try{l=await t.chat(r)}catch{return}const d=l&&l.choices&&l.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>tn){const e=n.slice(0,tn),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(Zt,JSON.stringify({day:nn(n),text:u}))}catch{}}}();const n=document.getElementById("welcome-byok");n&&n.addEventListener("click",cn);const o=document.getElementById("welcome-cloud");o&&o.addEventListener("click",dn);const s=document.getElementById("welcome-dismiss");s&&s.addEventListener("click",mn),an()}function an(){const e=document.getElementById("welcome-connect");if(!e)return;let t=!1;try{t="on"===localStorage.getItem(h)}catch{}const n=!0!==de,o=!0!==ue;e.hidden=t||!n&&!o,rn("welcome-cloud",!n),rn("welcome-cloud-note",!n),rn("welcome-byok",!o),rn("welcome-byok-note",!o)}function rn(e,t){const n=document.getElementById(e);n&&(n.hidden=t)}function ln(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 cn(){if(un("byok"),Array.from(c.classSelect.options).some((e=>"byok"===e.value))&&"byok"!==c.classSelect.value&&(c.classSelect.value="byok",c.classSelect.dispatchEvent(new Event("change"))),ln(c.settingsList),!1===de&&c.apiKeyHint&&(c.apiKeyHint.textContent="BYOK needs an AEGIS key too — the handling fee is billed to it. Paste one above, then add your provider key below."),!1===de&&c.apiKeyInput)return c.apiKeyInput.focus(),void ln(c.apiKeyInput);const e=c.settingsList?c.settingsList.querySelector('.setting-row input[type="password"]'):null;e&&e.focus()}function dn(){un("cloud"),ln(c.apiKeyInput),c.apiKeyInput&&c.apiKeyInput.focus()}function un(e){const t=c.apiKeyHint;if(!t)return;t.textContent="","byok"===e?t.appendChild(document.createTextNode("Bring your own key: everything on this machine stays free, and a local model server needs no account at all. A key relayed through AEGIS is a cloud turn, so it bills a small handling fee — paste the AEGIS key here, then add the provider key in Provider settings. No key yet? ")):t.appendChild(document.createTextNode(`Connect AEGIS Cloud: ${x} Paste your AEGIS key, then Save. Free key at `));const n=document.createElement("a");n.href=w,n.target="_blank",n.rel="noreferrer noopener",n.textContent="aegiscloud.org",t.appendChild(n),t.appendChild(document.createTextNode("."))}function mn(){try{localStorage.setItem(h,"on")}catch{}const e=document.getElementById("welcome-connect");e&&(e.hidden=!0)}const pn="aegis.keysPopupDismissed";function yn(){const e=!0===de,t=!0===ue;c.keysAegisState&&(c.keysAegisState.textContent=e?"set":"not set"),c.keysByokState&&(c.keysByokState.textContent=t?"set":"not set"),c.keysRowAegis&&c.keysRowAegis.classList.toggle("set",e),c.keysRowByok&&c.keysRowByok.classList.toggle("set",t),c.keysCount&&(c.keysCount.textContent=(e?1:0)+(t?1:0)+" / 2"),c.keysAccount&&(c.keysAccount.hidden=!he,c.keysAccount.textContent=he?`The AEGIS account key could not be set up: ${he}.`:""),c.keysAccountRetry&&(c.keysAccountRetry.hidden=!he),c.keysHint&&(c.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 fn(){c.keysOverlay&&(c.keysOverlay.hidden=!0,document.body.classList.remove("keys-open"))}function hn(){try{localStorage.setItem(pn,"on")}catch{}fn()}function gn(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 vn(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",gn(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=$n(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 c.messages.appendChild(a),ee(),a}function Cn(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${++W}`;e.dataset.session=o,V.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 Mn(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 Sn(t.tool):void Ln(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:`${G}\n\n${n.path.hint}`,prompt:`Original request:\n${n.prompt}\n\n${n.path.hint}`,model:n.model,maxTokens:Math.min(n.maxTokens||1024,1024),tools:!1,singlePass:!0,sessionId:o,bestEffort:!0},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)";gn(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 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}),h=fmtRoll(f);h&&m.push(`session: ${h}`),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{V.delete(o);const t=e.querySelector(".flow-abort");t&&t.remove()}}(s,{...o,path:e}),s}function kn(){return R||(R=vn("assistant",""),R.classList.remove("pending"),R)}function bn(e,{cancellable:t}={}){if(c.send.disabled=e,c.prompt.disabled=e,e){R=vn("assistant",""),R.classList.add("pending");const e=document.createElement("span");e.className="typing-dots";for(let t=0;t<3;t++)e.appendChild(document.createElement("span"));R.querySelector(".body").appendChild(e);const n=document.createElement("span");if(n.className="typing-tokens",n.hidden=!0,R.appendChild(n),t){const e=document.createElement("button");e.type="button",e.className="cancel-btn",e.textContent="cancel",e.addEventListener("click",(()=>ne())),R.appendChild(e)}}else R&&(R.remove(),R=null)}const wn=72,xn=new Set(["editFile","writeFile","Edit","Write","MultiEdit"]),En=new Map;function Sn(e){if(!e||!xn.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&&En.set(e.id,n)}function $n(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>wn?`${i.slice(0,wn-1)}…`:i;return`→ ${t}${r?` ${r}`:""} ${o}`}function Ln(t,n,o,s){if(!t)return;let a=t.querySelector(`.${o}`);if(!a){a=document.createElement("div"),a.className=o;const e=s?t.querySelector(s):null;e?t.insertBefore(a,e):t.appendChild(a)}const i=n&&null!=n.id?En.get(n.id):null;if(i){En.delete(n.id);const t=renderDiffBlock(i,document);if(t)return a.appendChild(t),function(t,n){if(!t||!n||null==n.id||!1===n.ok)return;if("writeFile"!==n.name&&"editFile"!==n.name)return;if(!e||"function"!=typeof e.undoMutation)return;const o=document.createElement("div");o.className="diff-undo-row";const s=document.createElement("span");s.className="diff-undo-link",s.textContent="⎿ undo this edit",s.setAttribute("role","button"),s.tabIndex=0;const a=async()=>{s.removeEventListener("click",a),s.tabIndex=-1,s.textContent="⎿ undoing…";try{const t=await e.undoMutation(O,n.id);s.textContent=t&&t.ok?"⎿ "+("deleted"===t.restored?"undone — file deleted (it was new)":"undone — content restored"):`⎿ undo failed — ${t&&t.error||"unknown error"}`,s.className=t&&t.ok?"diff-undo-link diff-undo-done":"diff-undo-link diff-undo-failed"}catch(e){s.textContent=`⎿ undo failed — ${e&&e.message||e}`,s.className="diff-undo-link diff-undo-failed"}};s.addEventListener("click",a),s.addEventListener("keydown",(e=>{!e||"Enter"!==e.key&&" "!==e.key||("function"==typeof e.preventDefault&&e.preventDefault(),a())})),o.appendChild(s),t.appendChild(o)}(a,n),a}const r=document.createElement("div");return r.textContent=$n(n),a.appendChild(r),a}function qn(e){return e.startsWith("@@")?"diff-hunk":e.startsWith("+++")||e.startsWith("---")?"diff-file":e.startsWith("+")?"diff-add":e.startsWith("-")?"diff-del":"diff-ctx"}function Mn(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=qn(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":"always"===e?"Always allowed":"Allowed once",s.appendChild(o),t.respondApproval(n.id,e)})(a))),i};if(r.appendChild(l("Allow once","allow","once")),r.appendChild(l("Allow for this session","allow-session","session")),n.canPersist){const e=l("Always allow this command","allow-always","always");e.title="Stores a rule in ~/.aegiscode/permissions.json, shared with the terminal face",r.appendChild(e)}r.appendChild(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 Nn(){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 An(){try{U=await t.listClasses()||[]}catch(e){U=[],c.modelHint.textContent=`listClasses failed: ${e&&e.message?e.message:e}`}c.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)`,c.classSelect.appendChild(t)}const e=localStorage.getItem(d);e&&U.some((t=>t.class===e))&&(c.classSelect.value=e),await Hn(c.classSelect.value)}async function Hn(e){if(c.autonomousToggleWrap&&(c.autonomousToggleWrap.hidden=e!==g),se(),ie(e),c.modelSelect.hidden=!1,c.modelSelect.disabled=!1,c.modelFree.hidden=!0,c.modelFree.value="",c.modelHint.textContent="",c.modelSelect.innerHTML="",F=new Map,"aegis"===e){const e=document.createElement("option");e.value=i,e.textContent=r,c.modelSelect.appendChild(e)}try{const n=await t.listModels(e),o=Array.isArray(n&&n.models)?n.models:[],s=Boolean(n&&n.needsKey),a=Boolean(n&&n.needsDaemon),i=!(n&&!1===n.listed),r=Boolean(n&&n.providersFailed),l=Array.isArray(n&&n.unmatchedProviders)?n.unmatchedProviders:[];c.modelFree.hidden=!("local"===e&&(a||!i));for(const e of o){F.set(e.id,e);const t=document.createElement("option");t.value=e.id,t.textContent=e.label||e.id,c.modelSelect.appendChild(t)}let d;if(re(),s)d=null;else if(a)d=`No local model server at ${n&&n.baseURL||"the configured address"} — start Ollama, or set Base URL below to llama.cpp / LM Studio, then Refresh.`;else if("local"!==e||i)if("byok"===e&&r)d="Provider catalog unreachable — your saved keys and declared models are unaffected. Refresh to try again."+(n&&n.providersError?` (${n.providersError})`:"");else if(o.length)if("byok"===e&&n&&n.needsAegisKey){const e=n&&n.fee||null;d=`${o.length} model${1===o.length?"":"s"} available — `+(e&&e.require_balance?"an AEGIS account key and a funded balance are required: the BYOK handling fee is billed there.":"an AEGIS account key is required: the BYOK handling fee is billed there.")}else d="byok"===e&&n&&n.needsProviderKey?`${o.length} model${1===o.length?"":"s"} available — add a provider key in Provider settings below to use one.`:`${o.length} model${1===o.length?"":"s"} available.`;else d="local"===e?"No models on this server yet — pull one first (ollama pull llama3.2).":"aegis"===e?"No models to pin — this class runs the pooled route on the server's own default. Use Bring your own key for a per-provider model.":"No models listed.";else d="That address answered but listed no models — not Ollama? Type the model tag in the box above and send.";"byok"===e&&!r&&l.length&&(d=`${d} Not shown: ${l.join(", ")} — declared in models.json, but not in the provider catalog. Check the provider name in Settings.`);const u=maxTokensCeiling(F.get(ae()));if(s){c.modelHint.textContent="Connect Aegis Cloud to load its models: paste your AEGIS API key in the Status card above (";const e=document.createElement("a");return e.href=w,e.target="_blank",e.rel="noreferrer noopener",e.textContent="free key at aegiscloud.org",c.modelHint.appendChild(e),void c.modelHint.appendChild(document.createTextNode("), then Save."))}c.modelHint.textContent=u<FLAT_CEILING?`${d} · max output: ${u.toLocaleString()}`:d}catch(e){F=new Map,c.modelHint.textContent=`listModels failed: ${e&&e.message?e.message:e}`,re()}}function Bn(){if(c.queueModelInput&&!c.queueModelInput.hidden){const e=c.queueModelInput.value.trim();if(e)return e}return c.queueModelSelect?c.queueModelSelect.value:""}async function In(e){if(c.queueModelSelect){if(function(e){const t=c.queueFanout&&c.queueFanout.closest("label");t&&(t.hidden="aegis"!==e)}(e),c.queueModelSelect.hidden=!1,c.queueModelSelect.disabled=!1,c.queueModelInput&&(c.queueModelInput.hidden=!0,c.queueModelInput.value=""),c.queueModelHint&&(c.queueModelHint.textContent=""),c.queueModelSelect.innerHTML="","aegis"===e){const e=document.createElement("option");e.value="",e.textContent="server default (auto)",c.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);c.queueModelInput&&(c.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,c.queueModelSelect.appendChild(t)}if(!c.queueModelHint)return;s?c.queueModelHint.textContent="Connect this class in the Model card above (API key / provider key), then Refresh.":a?c.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&&(c.queueModelHint.textContent="A provider key is required before a queued task on this model can run — add one in the Model card above."):c.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.":c.queueModelHint.textContent="That address answered but listed no models — type the model tag above."}catch(e){c.queueModelHint&&(c.queueModelHint.textContent=`listModels failed: ${e&&e.message?e.message:e}`)}}}function Rn({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 Tn(e){c.settingsHint.textContent="saving…";try{const n=String(null==e?"":e).trim()||b,o=await t.settings.set(C,{baseURL:n}),s=o&&o.baseURL||n;c.settingsHint.textContent=`saved: local model server at ${s}`,await On(),await Hn(c.classSelect.value)}catch(e){c.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function On(){c.settingsList.innerHTML="";const e=[];let n=[];try{n=await t.settings.get()||[]}catch{}Array.isArray(n)&&(n=n.filter((e=>e&&!v.has(e.provider))));{const e=n.find((e=>e&&e.provider===C))||{provider:C,baseURL:"",configured:!1,keyMask:null};c.settingsList.appendChild(function(e){const t=C,n=document.createElement("div");n.className="setting-row",n.dataset.provider=t;const o=document.createElement("div");o.className="setting-name",o.textContent="Local model server",n.appendChild(o);const s=document.createElement("input");s.type="text",s.className="setting-input",s.id="local-base-url",s.autocomplete="off",s.spellcheck=!1,s.placeholder=b,s.value=e.baseURL||"",s.addEventListener("keydown",(e=>{"Enter"===e.key&&Tn(s.value)})),n.appendChild(s);const a=document.createElement("div");a.className="setting-status",a.textContent=e.baseURL?e.baseURL:`default (${b})`,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",(()=>Tn(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",(()=>_n(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===k)continue;const o=`byok:${t.id}`,s=n.find((e=>e.provider===o))||{provider:o,baseURL:"",configured:!1,keyMask:null};c.settingsList.appendChild(Rn({provider:o,name:`BYOK: ${t.label||t.id}`,cfg:s,onSave:e=>Pn(o,e),onRemove:()=>_n(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),c.settingsList.appendChild(e)}}catch{}try{await async function(e){if(!c.settingsList||!t.userModels)return;const n=await t.userModels.get();if(!n)return;const o=n&&n.map||{},s=(e||[]).map((e=>e&&e.id||"")).filter(Boolean),a=document.createElement("div");a.id="user-models-block";const i=document.createElement("div");i.className="setting-name",i.textContent="Your own models (BYOK)",a.appendChild(i);const r=document.createElement("div");r.className="setting-row",r.dataset.provider="byok:__user-model-add";const l=document.createElement("input");if(l.type="text",l.className="setting-input",l.id="user-model-provider",l.placeholder="provider (deepseek)",l.autocomplete="off",l.spellcheck=!1,s.length){const e=document.createElement("datalist");e.id="user-model-providers";for(const t of s){const n=document.createElement("option");n.value=t,e.appendChild(n)}r.appendChild(e),l.setAttribute("list","user-model-providers")}r.appendChild(l);const d=document.createElement("input");d.type="text",d.className="setting-input",d.id="user-model-id",d.placeholder="model id (deepseek-v4.2-preview)",d.autocomplete="off",d.spellcheck=!1,r.appendChild(d);const u=document.createElement("div");u.className="setting-actions";const m=document.createElement("button");m.type="button",m.className="ghost-btn",m.id="user-model-add",m.textContent="Add model",m.addEventListener("click",(async()=>{const e=l.value.trim(),n=d.value.trim();c.settingsHint.textContent="adding…";try{const o=await t.userModels.add(e,n);c.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 On(),await Hn(c.classSelect.value)}catch(e){c.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=l.value.trim();if(!e)return void(c.settingsHint.textContent="type a provider id first (the CLI's /byok lists them).");if("function"!=typeof t.userModels.discover)return void(c.settingsHint.textContent="this build cannot ask a provider — type the model id.");let n;c.settingsHint.textContent=`asking ${e}…`,y.hidden=!0,y.textContent="";try{n=await t.userModels.discover(e)}catch(e){return void(c.settingsHint.textContent=`${e&&e.message?e.message:e}`)}if(!n||!n.ok)return void(c.settingsHint.textContent=`${e}: ${n&&n.error||"no answer"}`);c.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()=>{c.settingsHint.textContent=`adding ${n.count}…`;try{const e=await t.userModels.addAll(n.provider,n.ids);c.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 On(),await Hn(c.classSelect.value)}catch(e){c.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})),r.appendChild(u),r.appendChild(y);const f=document.createElement("div");f.className="setting-status",f.id="user-model-hint",f.textContent=n.file?`saved in ${n.file} — the CLI reads the same file (/model-add)`:"saved beside your AEGIS config — the CLI reads the same file (/model-add)",r.appendChild(f),a.appendChild(r);const h=Object.keys(o).sort();for(const e of h)for(const n of o[e]){const o=document.createElement("div");o.className="setting-row",o.dataset.provider=`byok:${e}`;const i=document.createElement("div");i.className="setting-name",i.textContent=`${e} — ${n}`,o.appendChild(i);const r=document.createElement("div");r.className="setting-status",r.textContent=s.length&&!s.includes(e)?"no provider row for this id — /byok lists the ones the relay takes":"offered in the picker on this machine",o.appendChild(r);const l=document.createElement("div");l.className="setting-actions";const d=document.createElement("button");d.type="button",d.className="ghost-btn danger",d.textContent="Remove",d.addEventListener("click",(async()=>{c.settingsHint.textContent="removing…";try{const o=await t.userModels.remove(e,n);c.settingsHint.textContent=o&&!1===o.removed?`${e}:${n} was not declared.`:`removed ${e}:${n}.`,await On(),await Hn(c.classSelect.value)}catch(e){c.settingsHint.textContent=`${e&&e.message?e.message:e}`}})),l.appendChild(d),o.appendChild(l),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)}c.settingsList.appendChild(a)}(e)}catch(e){c.settingsHint.textContent=`your own models: ${e&&e.message?e.message:e}`}try{await Dn()}catch(e){c.customStatus&&(c.customStatus.textContent=`custom provider: ${e&&e.message?e.message:e}`)}}async function Dn(){if(!c.customBaseUrl)return;let e=null,n=[];try{const n=await t.settings.get()||[],o=(Array.isArray(n)?n:[]).find((e=>e&&e.provider===`byok:${k}`));o&&(e={baseURL:o.baseURL||"",configured:Boolean(o.configured),keyMask:o.keyMask})}catch{}try{const e=await t.userModels.get(),o=e&&e.map||{};n=Array.isArray(o[k])?o[k]:[]}catch{}!function(e,t){if(!c.customBaseUrl)return;const n=e||{},o=Array.isArray(t)?t:[];if(!c.customBaseUrl.value&&n.baseURL&&(c.customBaseUrl.value=n.baseURL),c.customKey&&(c.customKey.placeholder=n.configured?`key ${n.keyMask||"••••"} (blank = keep)`:"sk-…",c.customKey.value=""),c.customRemove&&(c.customRemove.disabled=!n.configured&&!n.baseURL),!c.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"),c.customStatus.textContent=s.join(" · ")}(e,n)}async function Un(){if(!c.customBaseUrl)return;const e=String(c.customBaseUrl.value||"").trim(),n=c.customKey?String(c.customKey.value||"").trim():"",o=c.customModel?String(c.customModel.value||"").trim():"",s=e=>{c.customStatus&&(c.customStatus.textContent=e)};if(!e)return void s("an address is required — aegis1 dials the endpoint you name, and refuses a custom call that names none.");if(!/^https:\/\//i.test(e))return void s("refused: only an https:// endpoint is dialed — aegis1 rejects a plain-http or scheme-less base URL for this provider.");if(!o)return void s("a model id is required — the `custom` provider pins no default, so nothing would be selectable in the picker.");s("saving…");const a=`byok:${k}`;try{const o={};o.baseURL=e,n&&(o.key=n),await t.settings.set(a,o)}catch(e){return void s(`endpoint not saved: ${e&&e.message?e.message:e}`)}try{await t.userModels.add(k,o)}catch(e){return s(`endpoint saved, model NOT declared: ${e&&e.message?e.message:e}`),await Dn(),void await Hn(c.classSelect.value).catch((()=>{}))}c.customModel&&(c.customModel.value=""),s(`saved ${e} with model ${o} — pick it under provider "byok", then the model.`),await Dn(),await On(),await Hn(c.classSelect.value).catch((()=>{}))}async function Fn(){if(!c.customBaseUrl)return;const e=e=>{c.customStatus&&(c.customStatus.textContent=e)};e("removing…");let n=0;try{const e=await t.userModels.get(),o=e&&e.map||{},s=Array.isArray(o[k])?o[k]:[];for(const e of s)await t.userModels.remove(k,e),n+=1}catch{}try{await t.settings.remove(`byok:${k}`)}catch(t){return void e(`remove failed: ${t&&t.message?t.message:t}`)}c.customBaseUrl&&(c.customBaseUrl.value=""),e(`removed the custom endpoint${n?` and ${n} declared model(s)`:""}.`),await Dn(),await On(),await Hn(c.classSelect.value).catch((()=>{}))}async function Pn(e,n){c.settingsHint.textContent="saving…";try{const o={};n&&(o.key=n),await t.settings.set(e,o),c.settingsHint.textContent="saved.",await On(),await Hn(c.classSelect.value)}catch(e){c.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function _n(e){c.settingsHint.textContent="removing…";try{await t.settings.remove(e),c.settingsHint.textContent="removed.",await On(),await Hn(c.classSelect.value)}catch(e){c.settingsHint.textContent=`remove failed: ${e&&e.message?e.message:e}`}}const Kn=["sessions","memory"];let jn="sessions";function Gn(e){const t=Kn.includes(e)?e:"sessions";jn=t;for(const e of Kn){const n="sessions"===e?c.paneSessions:c.paneMemory,o="sessions"===e?c.tabSessions:c.tabMemory,s=e===t;n&&(n.hidden=!s),o&&(o.setAttribute("aria-selected",s?"true":"false"),o.classList.toggle("is-active",s))}}const Qn=new Set,Wn=3;function Vn(e){if(!e||!e.id||!0===e.named||Qn.has(e.id))return;const t=(Array.isArray(e.messages)?e.messages:[]).find((e=>e&&"user"===e.role&&e.content));if(!t)return;if(Qn.add(e.id),"function"!=typeof n.nameSession)return;const o=c.classSelect?c.classSelect.value:"";n.nameSession({sessionId:e.id,prompt:t.content,class:o,model:ae()}).then((e=>{e&&Xn().catch((()=>{}))})).catch((()=>{}))}let Yn=[],zn=null;const Jn="undefined"!=typeof window&&window.aegisLibrary||null;async function Xn(){c.sessionsHint.textContent="";let e=[];try{const t=await n.listSessions();e=t&&t.sessions||[]}catch(e){return c.sessionsList.innerHTML="",void(c.sessionsHint.textContent=`list failed: ${e&&e.message?e.message:e}`)}Yn=e;let t=Wn;for(const n of e){if(t<=0)break;n&&!0!==n.named&&!Qn.has(n.id)&&(t-=1,Vn(n))}Zn()}function Zn(){if(!c.sessionsList)return;const e=c.sessionsFilter?c.sessionsFilter.value:"",t=Yn,n=Jn?Jn.filterSessions(e,t):t;if(c.sessionsCount&&(c.sessionsCount.textContent=Jn?Jn.countLabel(n.length,t.length):""),c.sessionsList.innerHTML="",!t.length)return void c.sessionsList.appendChild(eo("no conversations yet"));if(!n.length)return void c.sessionsList.appendChild(eo(`nothing matches “${String(e).trim()}”`));const o=Date.now(),s=Jn?Jn.groupSessions(n,o):[{key:"all",label:"",sessions:n}];for(const e of s){if(e.label){const t=document.createElement("li");t.className="library-group",t.setAttribute("role","presentation"),t.textContent=e.label,c.sessionsList.appendChild(t)}for(const t of e.sessions)c.sessionsList.appendChild(to(t,o))}}function eo(e){const t=document.createElement("li");return t.className="empty",t.textContent=e,t}function to(t,o){const s=document.createElement("li");if(s.className="session-row",s.tabIndex=0,s.dataset.sessionId=t&&t.id||"",t&&t.id&&t.id===O&&s.classList.add("is-current"),zn&&t&&t.id===zn)return s.classList.add("is-renaming"),s.appendChild(function(e){const t=document.createElement("input");return t.type="text",t.className="session-rename",t.value=e&&e.title||"",t.setAttribute("aria-label","New name for this conversation"),t.addEventListener("click",(e=>e.stopPropagation())),t.addEventListener("keydown",(o=>{o.stopPropagation(),"Enter"===o.key?(o.preventDefault(),async function(e,t){const o=String(null==t?"":t).trim();if(zn=null,!o||o===(e&&e.title||""))return void Zn();if("function"!=typeof n.rename)return c.sessionsHint.textContent="rename is unavailable in this build.",void Zn();const s=Yn.find((t=>t&&t.id===e.id));s&&(s.title=o,s.named=!0),Zn();try{await n.rename(e.id,o),c.sessionsHint.textContent=`renamed to “${o}”`}catch(e){c.sessionsHint.textContent=`rename failed: ${e&&e.message?e.message:e}`}await Xn()}(e,t.value)):"Escape"===o.key&&(o.preventDefault(),zn=null,Zn())})),t.addEventListener("blur",(()=>{zn===(e&&e.id)&&(zn=null,Zn())})),setTimeout((()=>{try{t.focus(),t.select()}catch{}}),0),t}(t)),s;const a=document.createElement("span");a.className="session-title",a.textContent=Jn?Jn.sessionTitle(t):t&&t.title||t&&t.id||"untitled",s.appendChild(a);const i=document.createElement("span");i.className="session-meta",i.textContent=Jn?Jn.sessionMeta(t,o):"",s.appendChild(i);const r=document.createElement("span");r.className="session-actions";for(const[o,s,a]of[["Rename","Rename this conversation",()=>function(e){e&&e.id&&(zn=e.id,Zn())}(t)],["Export","Save this conversation as Markdown",()=>async function(t){if(t&&t.id)if("function"==typeof e.exportSession)try{const n=await e.exportSession(t.id,"markdown");n&&n.ok?c.sessionsHint.textContent=`exported to ${n.filePath}`:n&&n.canceled?c.sessionsHint.textContent="":c.sessionsHint.textContent=`export failed: ${n&&n.reason||"unknown error"}`}catch(e){c.sessionsHint.textContent=`export failed: ${e&&e.message?e.message:e}`}else c.sessionsHint.textContent="export is unavailable in this build."}(t)],["Delete","Delete this conversation",()=>async function(e){if(!e||!e.id)return;const t=Jn?Jn.sessionTitle(e):e.title||e.id;if("function"!=typeof confirm||confirm(`Delete “${t}”?\n\nThis removes the conversation from this device. It cannot be undone.`)){try{await n.delete(e.id)}catch(e){return void(c.sessionsHint.textContent=`delete failed: ${e&&e.message?e.message:e}`)}O===e.id&&lo(),c.sessionsHint.textContent=`deleted “${t}”`,await Xn()}}(t)]]){const e=document.createElement("button");e.type="button",e.className="session-action",e.textContent=o,e.title=s,e.setAttribute("aria-label",`${s}`),e.addEventListener("click",(e=>{e.stopPropagation(),a()})),r.appendChild(e)}return s.appendChild(r),s.addEventListener("click",(()=>io(t.id))),s.addEventListener("keydown",(e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),io(t.id))})),s}function no(e){if(!c.syncStatus)return;if(!e)return void(c.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}`),c.syncStatus.textContent=t.join(" · ")}async function oo(){try{no(await n.status())}catch{no(null)}}function so(){"function"==typeof n.auto&&n.auto().then((e=>{e&&e.upgrade&&ht(c.sessionsHint,e.upgrade,"queued memory is waiting on the free-plan cap","See what Pro covers →")})).catch((()=>{}))}async function ao(){c.syncNow.disabled=!0,c.sessionsHint.textContent="syncing…";try{const e=await n.push(),t=await n.pull();e.upgrade||t.upgrade?ht(c.sessionsHint,e.upgrade||t.upgrade,"queued memory is waiting on the free-plan cap","See what Pro covers →"):e.ok||t.ok?c.sessionsHint.textContent=`synced (pushed ${e.pushed||0}, pulled ${t.merged||0})`:c.sessionsHint.textContent=`sync failed: ${e.reason||t.reason||"unknown error"}`}catch(e){c.sessionsHint.textContent=`sync failed: ${e&&e.message?e.message:e}`}finally{c.syncNow.disabled=!1,await oo(),await Xn()}}function io(e){n.open(e).then((e=>{if(!e)return void(c.sessionsHint.textContent="session not found");c.messages.innerHTML="";const t=Array.isArray(e.messages)?e.messages:[];t.length||sn();for(const n of t){const t="assistant"===n.role?"assistant":"system"===n.role?"system":"user";vn(t,n.content||n.text||"",void 0,"assistant"===t?e.id:void 0)}O=e.id,P.set(e.id,rollMessages(t)),K(e.id),D=replayHistory(t),c.sessionsHint.textContent=`opened ${e.id.slice(0,8)}…`})).catch((e=>{c.sessionsHint.textContent=`open failed: ${e&&e.message?e.message:e}`}))}function ro(t){const n=O;n?e.exportSession(n,t).then((e=>{e&&e.ok?c.sessionsHint.textContent=`exported to ${e.filePath}`:e&&e.canceled||(c.sessionsHint.textContent=`export failed: ${e&&e.reason||"unknown error"}`)})).catch((e=>{c.sessionsHint.textContent=`export failed: ${e&&e.message?e.message:e}`})):c.sessionsHint.textContent="no open session to export"}function lo(){Y(),O&&t.clearApprovals(O).catch((()=>{})),sn(),c.sessionsHint.textContent="",R=null,T=null,J=null,X=null,O=null,D=[],W=0,K(null)}function co(e){e&&("open"===e.action&&e.sessionId?io(e.sessionId):"new"===e.action&&(lo(),e.prompt&&(c.prompt.value=e.prompt,c.prompt.focus())))}async function uo(){const e=c.prompt.value.trim(),o=mo.length?mo.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||c.send.disabled)return;const s=c.classSelect.value,a=ae();c.prompt.value="";const i=(r=mo,Array.isArray(r)&&r.length?r.map((e=>`📎 ${e.name||e.path}`)).join("\n"):"");var r;const l=i?e?`${e}\n${i}`:i:e;mo=[],po=[],ho();const d=++z;J=d,X=null,vn("user",l);const u=s===g&&oe(),m=le(),p=budgetFor(a,void 0,m),y=u&&parseInt(c.autonomousWorkers.value,10)||void 0;O||(O=Nn());const f=O;T=f,fn();const h=replayHistory(D);D.push({role:"user",content:o&&!fo()?wo(e,o):l}),bn(!0,{cancellable:!0}),R&&K(f,{prompt:e,reply:"",reasoning:""}),ee({force:!0});try{await n.append(f,{role:"user",content:l})}catch{}let v="",C="",k=0;const b=[];let w=null;const x=(E=()=>{if(!R)return;if(R.classList.remove("pending"),C){const e=function(e){let t=e.querySelector(".reasoning");if(!t){t=document.createElement("div"),t.className="reasoning";const n=e.querySelector(".body");n?e.insertBefore(t,n):e.appendChild(t)}return t}(R);e.textContent!==C&&(e.textContent=C)}const t=R.querySelector(".body");t&&t.textContent!==v&&(t.textContent=v);const n=v.length+C.length+4*k;liveMeterDue(w,n)&&(w=n,K(f,{prompt:e,reply:v,reasoning:C,measuredReasoningTokens:k})),ee()},Z?Z.paint(E):E);var E;const S=e=>{if(e&&"number"==typeof e.thinkingTokens&&e.thinkingTokens>0)return k+=e.thinkingTokens,void x();if(e&&"string"==typeof e.reasoning&&e.reasoning)return C+=e.reasoning,void x();if(e&&"string"==typeof e.note&&e.note){const t=kn();return t.classList.remove("pending"),function(e,t,n){if(!e||!t)return null;const o=document.createElement("div");o.className="turn-note",o.textContent=t;const s=n?e.querySelector(n):null;s?e.insertBefore(o,s):e.appendChild(o)}(t,e.note,".body"),void ee()}if(e&&e.approval){const t=kn();return t.classList.remove("pending"),Mn(t,e.approval,".body"),void ee({force:!0})}if(e&&e.rounds){const n=kn();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 ee({force:!0})}if(e&&e.tool){if("run"===e.tool.phase)return void Sn(e.tool);b.push(e.tool);const t=kn();return t.classList.remove("pending"),Ln(t,e.tool,"tool-activity",".body"),void ee()}const n=e&&("string"==typeof e.delta?e.delta:e.content);n&&(v+=n,x())};try{const i=await t.chat({class:s,prompt:e,model:a,maxTokens:p,sessionId:f,autonomous:u,effort:m,workers:y,messages:h,attachments:o,roundsAsk:!0},S);if(i&&i.aborted){const e=new Error(i.message||"This operation was aborted");throw e.name="AbortError",e.code="ABORT_ERR",e}const r=i&&i.choices&&i.choices[0]||{},l=r.message&&r.message.content||v||"(empty response)";isPlaceholderContent(l)||D.push({role:"assistant",content:l});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 g=turnAccounting(i&&i.usage,a,{costUsd:i&&"number"==typeof i.costUsd?i.costUsd:void 0}),k=displayTokens(g);if(null!=k)d.push(`tokens: ${k}`);else{const t=estimatedBuckets(e,l,l===C?"":C);t&&t.output>0&&d.push(`~${t.output} tokens`)}const w=feeBillable(function(){const e="undefined"!=typeof state?state:null;return e&&e.entitlement?e.entitlement:null}());null!=g.cost&&w&&d.push(fmtCost(g.cost,g.real)),"byok"===s&&null!=g.cost&&w&&d.push("your provider bill (est.) + AEGIS handling fee");const x=_(f,i&&i.usage,{model:a,costUsd:i&&"number"==typeof i.costUsd?i.costUsd:void 0,calls:i&&i.calls,prompt:e,reply:l,reasoning:l===C?"":C}),E=fmtRoll(x,{omitMoney:!w});E&&d.push(`session: ${E}`),i&&i.pooled_notice&&d.push(i.pooled_notice),vn("assistant",l,d.join(" · ")||void 0,f,b);try{await n.append(f,{role:"assistant",content:l,...j(i&&i.usage,a,g,{prompt:e,reply:l,reasoning:l===C?"":C,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&&Xn().catch((()=>{}))})).catch((()=>{}))}catch{}so(),function(){const e=c.exploreToggle;return Boolean(e&&e.checked)}()&&"(empty response)"!==l&&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",(()=>{Cn(Q[W%Q.length],a,e)})),a.appendChild(i),t.appendChild(n),t.appendChild(a),c.messages.appendChild(t);for(const t of Q.slice(0,2))Cn(t,a,e)}({prompt:e,cls:s,model:a,maxTokens:p,parentSessionId:f})}catch(t){if(isCancellation(t,{userStopped:X===d})){const t=salvageTurn({streamedText:v,reasoningText:C}),o=t.text,s=t.reasoning,i=replayableContent(t.kind,o);D.push({role:"assistant",content:i});const r=turnAccounting(void 0,a,{}),l=_(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}`),vn("assistant",o,c.join(" · "),f,b);try{await n.append(f,{role:"assistant",content:i,...j(void 0,a,r,{prompt:e,reply:o,reasoning:s})})}catch{}so()}else vn("assistant",`Error: ${t&&t.message?t.message:t}`,"request failed")}finally{bn(!1),J===d&&(J=null,T=null),Xn()}}let mo=[],po=[],yo=0;function fo(){return c.classSelect&&"pro"===c.classSelect.value}function ho(){const e=c.attachRow,t=c.attachNote;if(!e)return;e.textContent="";const n=mo.length+po.length;if(e.hidden=0===n,t&&(t.hidden=!0,t.textContent=""),n){for(const t of mo){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} · ${vo(t.size)}${t.truncated?" (truncated)":""}`,n.appendChild(s),n.appendChild(go((()=>{mo=mo.filter((e=>e!==t)),ho()}))),e.appendChild(n)}for(const t of po){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(go((()=>{po=po.filter((e=>e!==t)),ho()}))),e.appendChild(n)}if(t&&fo()){const e=mo.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 go(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 vo(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 Co(t){const n=(t||"").split(/[\\/]/).pop()||t;if(mo.length>=8)return po.push({path:t,name:n,reason:"at most 8 files per message"}),void ho();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 po.push({path:t,name:n,reason:o&&o.reason||"not attached"}),void ho();mo.some((e=>e.path===o.attachment.path))||(mo.push(o.attachment),ho())}const ko=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function bo(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 wo(e,t){const n=[],o="string"==typeof e?e:"";o.trim()&&n.push({type:"text",text:o});for(const e of t||[]){const t=bo(e);"image"===e.kind&&e.dataUrl&&ko.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 xo(){try{me(await e.status())}catch{me(null)}"on"===localStorage.getItem(m)&&(c.autonomousToggle.checked=!0),c.autonomousToggle.addEventListener("change",(()=>{localStorage.setItem(m,c.autonomousToggle.checked?"on":"off"),se()}));const n=localStorage.getItem(p)||localStorage.getItem("aegis.autonomousEffort"),i=Array.from(c.effortSelect.options).some((e=>e.value===n));n&&i?c.effortSelect.value=n:n&&localStorage.setItem(p,c.effortSelect.value),c.effortSelect.addEventListener("change",(()=>{localStorage.setItem(p,c.effortSelect.value),ie(c.classSelect.value)}));const r=localStorage.getItem(y);r&&(c.autonomousWorkers.value=r),c.autonomousWorkers.addEventListener("change",(()=>{localStorage.setItem(y,c.autonomousWorkers.value)})),se();const l=localStorage.getItem(f);c.exploreToggle.checked="on"===l,c.exploreToggle.addEventListener("change",(()=>{localStorage.setItem(f,c.exploreToggle.checked?"on":"off"),c.exploreToggle.checked||Y()})),c.classSelect.addEventListener("change",(()=>{localStorage.setItem(d,c.classSelect.value),ie(c.classSelect.value),Hn(c.classSelect.value)})),c.modelSelect.addEventListener("change",(()=>{const e=F.get(c.modelSelect.value),t=maxTokensCeiling(e),n=c.modelHint.textContent.replace(/ · max output: [\d,]+$/,"");c.modelHint.textContent=t<FLAT_CEILING?`${n} · max output: ${t.toLocaleString()}`:n,ie(c.classSelect.value),"byok"===c.classSelect.value&&e&&e.provider&&!1===e.configured&&function(e){if(!c.settingsList||!e)return;const t=c.settingsList.querySelector(`.setting-row[data-provider="byok:${e}"] input[type="password"]`);if(ln(c.settingsList),t&&t.focus(),c.modelHint){const t=c.modelHint.textContent.replace(/ — no .* key saved; add it below\.$/,"");c.modelHint.textContent=`${t} — no ${e} key saved; add it below.`}}(e.provider)})),c.modelFree.addEventListener("input",(()=>{ie(c.classSelect.value)})),c.newChat.addEventListener("click",lo),c.importSessionBtn&&c.importSessionBtn.addEventListener("click",Pt),c.importClose&&c.importClose.addEventListener("click",Ut),c.importBackdrop&&c.importBackdrop.addEventListener("click",Ut),c.importSessionsBtn&&c.importSessionsBtn.addEventListener("click",_t),c.importMemoryBtn&&c.importMemoryBtn.addEventListener("click",(()=>Vt({hint:c.importHint}))),e.onMenuNewChat&&e.onMenuNewChat(lo),e.onMenuSearch&&e.onMenuSearch((()=>It(""))),e.onMenuSearchMemory&&e.onMenuSearchMemory(Rt),
|
|
6
6
|
// Help > Credits & licence… — the AGPL, the program notice and every vendored
|
|
7
|
-
e.onMenuCredits&&e.onMenuCredits(_t),e.onMenuFingerprint&&e.onMenuFingerprint((()=>{st&&"function"==typeof st.open&&st.open()})),e.onMenuGoogleDrive&&e.onMenuGoogleDrive((()=>{st&&"function"==typeof st.open&&st.open({focus:"drive"})})),e.onMenuExportMarkdown&&e.onMenuExportMarkdown((()=>Jn("markdown"))),e.onMenuExportJson&&e.onMenuExportJson((()=>Jn("json"))),e.onDeepLink&&e.onDeepLink(Zn),e.onQuickLauncherPush&&e.onQuickLauncherPush(ze),c.sessionsRefresh.addEventListener("click",Gn),c.syncNow.addEventListener("click",Yn),c.sessionsExport.addEventListener("click",(()=>Jn("markdown"))),c.apiKeySave.addEventListener("click",we),c.apiKeyVerify.addEventListener("click",xe),c.apiKeyInput.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),we())})),c.customSave&&c.customSave.addEventListener("click",Rn),c.customRemove&&c.customRemove.addEventListener("click",Tn);for(const e of[c.customBaseUrl,c.customKey,c.customModel])e&&e.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),Rn())}));c.upgradePlan.addEventListener("click",(()=>Ce("upgrade"))),c.topupBtn.addEventListener("click",(()=>Ce("topup"))),attachScrollLift({panes:document.querySelectorAll(".messages, .side, .memory-scroll"),target:document.body,requestFrame:e=>window.requestAnimationFrame(e)}),c.quickLauncherSave.addEventListener("click",Ee),c.quickLauncherShortcut.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),Ee())})),c.confirmMode&&c.confirmMode.addEventListener("change",(()=>qe(c.confirmMode.checked))),c.planMode&&c.planMode.addEventListener("change",(()=>async function(t){if(c.planMode){c.planMode.disabled=!0;try{Me(await e.setPermissionMode(t))}catch(e){c.planMode.checked=!t,c.planModeHint&&(c.planModeHint.textContent=`save failed: ${e&&e.message?e.message:e}`)}finally{c.planMode.disabled=!1}}}(c.planMode.checked))),c.permRulesForm&&c.permRulesForm.addEventListener("submit",(t=>{t.preventDefault(),async function(t,n){if(!e.permRulesAdd)return;const o=String(null==n?"":n).trim();if(o){c.permRulesAdd&&(c.permRulesAdd.disabled=!0);try{const n=await e.permRulesAdd(t,o);if(n&&!0===n.ok){Ne(n),c.permRulesInput&&(c.permRulesInput.value="");const e=!1===n.added?"already stored":"stored";c.permRulesStatus&&(c.permRulesStatus.textContent=n.warning?`${e}: ${o} — ${n.warning}`:`${e}: ${o}`)}else c.permRulesStatus&&(c.permRulesStatus.textContent=`not stored: ${n&&n.reason||"the store refused it"}`)}catch(e){c.permRulesStatus&&(c.permRulesStatus.textContent=`add failed: ${e&&e.message?e.message:e}`)}finally{c.permRulesAdd&&(c.permRulesAdd.disabled=!1)}}else c.permRulesStatus&&(c.permRulesStatus.textContent="type a rule first")}(c.permRulesListSelect?c.permRulesListSelect.value:"allow",c.permRulesInput&&c.permRulesInput.value)})),c.sandboxMode&&c.sandboxMode.addEventListener("change",(()=>{const e=c.sandboxNetwork&&c.sandboxNetwork.checked?"open":"restricted";Te(c.sandboxMode.value,e)})),c.sandboxNetwork&&c.sandboxNetwork.addEventListener("change",(()=>{Te(c.sandboxMode?c.sandboxMode.value:"workspace-write",c.sandboxNetwork.checked?"open":"restricted")})),c.autoMode&&c.autoMode.addEventListener("click",(()=>{c.confirmMode&&qe(!c.confirmMode.checked)})),c.composer.addEventListener("submit",(e=>{e.preventDefault(),eo()})),c.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"))&&(oo+=1,document.body.classList.add("is-dropping"))})),window.addEventListener("dragleave",(()=>{oo=Math.max(0,oo-1),0===oo&&document.body.classList.remove("is-dropping")})),window.addEventListener("dragover",(e=>{e.dataTransfer&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")})),window.addEventListener("drop",(t=>{oo=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 lo(n):(no.push({name:t.name||"file",reason:"no path available"}),ao())}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=c.prompt;if(!t)return;const n="number"==typeof t.selectionStart?t.selectionStart:t.value.length,o="number"==typeof t.selectionEnd?t.selectionEnd:t.value.length,s=t.value.slice(0,n),a=t.value.slice(o),i=s&&!/\s$/.test(s)?" ":"";t.value=`${s}${i}${e}${a}`;const r=(s+i+e).length;try{t.setSelectionRange(r,r)}catch{}t.focus()}(s))}(t).catch((()=>{}))})),document.addEventListener("dragover",(e=>e.preventDefault())),document.addEventListener("drop",(e=>e.preventDefault())),c.classSelect&&c.classSelect.addEventListener("change",ao),ao()),c.prompt.addEventListener("keydown",(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),c.composer.requestSubmit())})),c.tabSessions&&c.tabSessions.addEventListener("click",(()=>Pn("sessions"))),c.tabMemory&&c.tabMemory.addEventListener("click",(()=>Pn("memory"))),c.memorySearchForm.addEventListener("submit",(e=>{e.preventDefault(),vt(c.memoryQuery.value.trim())})),c.memorySaveBtn.addEventListener("click",Gt),c.memoryImportBtn.addEventListener("click",jt),c.sessionClose&&c.sessionClose.addEventListener("click",Ht),c.sessionBackdrop&&c.sessionBackdrop.addEventListener("click",Ht),c.sessionClear&&c.sessionClear.addEventListener("click",(()=>{c.sessionQuery&&(c.sessionQuery.value=""),At(""),c.sessionQuery&&c.sessionQuery.focus()})),c.sessionFilters&&c.sessionFilters.addEventListener("submit",(e=>{e.preventDefault(),At(c.sessionQuery?c.sessionQuery.value:"")})),c.sessionQuery&&c.sessionQuery.addEventListener("input",(()=>{At(c.sessionQuery.value)})),c.creditsClose&&c.creditsClose.addEventListener("click",Kt),c.creditsBackdrop&&c.creditsBackdrop.addEventListener("click",Kt),c.memoryOpen&&c.memoryOpen.addEventListener("click",Et),c.memoryClose&&c.memoryClose.addEventListener("click",$t),c.memoryBackdrop&&c.memoryBackdrop.addEventListener("click",$t),c.memoryOverlaySave&&c.memoryOverlaySave.addEventListener("click",Gt),c.memoryFilters&&c.memoryFilters.addEventListener("submit",(e=>{e.preventDefault(),et.query=c.memoryOverlayQuery.value.trim(),St(et.query)})),c.memoryFiltersClear&&c.memoryFiltersClear.addEventListener("click",(()=>{c.memoryOverlayQuery.value="",et.query="",et.source="",et.role="",xt()})),c.keysClose&&c.keysClose.addEventListener("click",un),c.keysBackdrop&&c.keysBackdrop.addEventListener("click",un),c.keysDismiss&&c.keysDismiss.addEventListener("click",mn),c.keysGotoAegis&&c.keysGotoAegis.addEventListener("click",(()=>{un(),on(c.apiKeyInput),c.apiKeyInput&&c.apiKeyInput.focus(),c.apiKeyHint&&(c.apiKeyHint.textContent=`Missing: ${function(){const e=[];return!0!==de&&e.push("the AEGIS key"),!0!==ue&&e.push("your provider (BYOK) key"),e.join(" and ")}()}. This is the AEGIS account key — the same one the CLI reads from ~/.aegiscode/.env, so pasting it here configures both.`)})),c.keysGotoByok&&c.keysGotoByok.addEventListener("click",(()=>{un(),sn()})),s&&(c.queueEnqueue&&c.queueEnqueue.addEventListener("click",Ke),c.queueDrain&&c.queueDrain.addEventListener("click",(()=>je("one"))),c.queueProceed&&c.queueProceed.addEventListener("click",(()=>je("all"))),c.queueStop&&c.queueStop.addEventListener("click",Ge),"function"==typeof s.onProgress&&s.onProgress(Ye),c.queueClassSelect&&c.queueClassSelect.addEventListener("change",(()=>{localStorage.setItem(u,c.queueClassSelect.value),An(c.queueClassSelect.value)})),await _e(),await async function(){if(!c.queueClassSelect)return;let e=[];try{e=await t.listClasses()||[]}catch(t){e=[],c.queueModelHint&&(c.queueModelHint.textContent=`listClasses failed: ${t&&t.message?t.message:t}`)}c.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)`,c.queueClassSelect.appendChild(e)}const n=localStorage.getItem(u);n&&e.some((e=>e.class===n))&&(c.queueClassSelect.value=n),await An(c.queueClassSelect.value)}()),a&&(c.queueAuto&&c.queueAuto.addEventListener("change",(()=>Ve(c.queueAuto.checked))),c.queueAutoInterval&&c.queueAutoInterval.addEventListener("change",(()=>{c.queueAuto&&c.queueAuto.checked&&Ve(!0)})),await async function(){if(!a||"function"!=typeof a.status)return null;try{const e=await a.status();return We(e),e}catch(e){return c.queueAutoHint&&(c.queueAutoHint.textContent=`automation status unavailable: ${e&&e.message?e.message:e}`),null}}()),Z=createTranscriptView({messages:c.messages,requestFrame:e=>requestAnimationFrame(e)}),Z.attachScrollVeto();let h=null;window.__aegisSmoke=Object.freeze({isScrolledUp:()=>Z.isScrolledUp(),metrics:()=>Z.metrics(),escapeDecision:()=>h&&"function"==typeof h.lastDecision?h.lastDecision():null,stopOutcome:()=>te}),h=bindEscapeInterrupt({doc:document,isOverlayOpen:tt,onOverlayEscape:()=>{if(qt())Ht();else if(It())Rt();else if(Dt())Kt();else if(ot())un();else{if(st&&"function"==typeof st.close)try{return void st.close()}catch(e){}$t()}},hasPendingTurn:()=>!!T,stopTurn:ne}),c.accountBanner&&e.onAccountStatus&&(e.onAccountStatus(ge),e.accountStatus().then(ge).catch((e=>console.warn("account status unavailable",e))),c.accountRetryBtn.addEventListener("click",(()=>ve(c.accountRetryBtn))),c.keysAccountRetry&&c.keysAccountRetry.addEventListener("click",(()=>ve(c.keysAccountRetry)))),c.updateBanner&&e.onUpdateStatus&&(e.onUpdateStatus(fe),e.updateStatus().then(fe).catch((()=>{})),c.updateDownloadBtn.addEventListener("click",(()=>{c.updateDownloadBtn.disabled=!0,Promise.resolve(e.downloadUpdate()).then((e=>{e&&e.status&&fe(e)})).catch((()=>{})).finally((()=>{c.updateDownloadBtn.disabled=!1}))})),c.updateRestartBtn.addEventListener("click",(()=>{e.quitAndInstallUpdate()})),c.updateRetryBtn&&e.checkForUpdates&&c.updateRetryBtn.addEventListener("click",(()=>{c.updateRetryBtn.disabled=!0,Promise.resolve(e.checkForUpdates()).then(fe).catch((()=>{})).finally((()=>{c.updateRetryBtn.disabled=!1}))})),c.updateLaterBtn.addEventListener("click",(()=>{ye=pe&&pe.status,c.updateBanner.hidden=!0}))),c.messages.querySelector(".msg, .chatflow")||en(),await Ln(),await Bn(),await async function(){if(o)try{Se(await o.status())}catch(e){c.quickLauncherHint.textContent=`status failed: ${e&&e.message?e.message:e}`}}(),await async function(){if(c.confirmMode&&e.getConfirmMode)try{$e(await e.getConfirmMode())}catch(e){c.confirmModeHint.textContent=`status failed: ${e&&e.message?e.message:e}`}}(),await async function(){if(c.planMode&&e.getPermissionMode)try{Me(await e.getPermissionMode())}catch(e){c.planModeHint&&(c.planModeHint.textContent=`status failed: ${e&&e.message?e.message:e}`)}}(),await async function(){if(c.permRulesList&&e.permRulesList)try{Ne(await e.permRulesList())}catch(e){Ne({ok:!1,reason:e&&e.message||String(e)})}}(),await Re(),await Gn(),await Wn(),ke(),Pn("sessions"),c.memoryQuietFloor&&(c.memoryQuietFloor.textContent=String(Xe)),vt("");try{!function(){if(window.aegisProviderToolbar&&c.ptList)if(at=window.aegisProviderToolbar.mount({list:c.ptList,count:c.ptCount,search:c.ptSearch,hint:c.ptHint,onSelect:lt}),c.ptRefresh&&c.ptRefresh.addEventListener("click",(()=>{rt(!0)})),"function"==typeof IntersectionObserver&&c.ptList.closest("section")){const e=new IntersectionObserver((t=>{t.some((e=>e.isIntersecting))&&(e.disconnect(),rt(!1))}));e.observe(c.ptList.closest("section"))}else rt(!1)}()}catch(e){c.ptHint&&(c.ptHint.textContent=`provider list unavailable: ${e&&e.message||e}`)}if(c.companionDismiss&&c.companionDismiss.addEventListener("click",(()=>{localStorage.setItem(ct,JSON.stringify({day:window.aegisCompanion?window.aegisCompanion.dayKey(new Date):"",id:c.companionCard.dataset.messageId||""})),c.companionCard.hidden=!0})),ut(),window.aegisFingerprint)try{st=window.aegisFingerprint.mount({api:e,getSessionId:()=>O}),st.refresh().catch((()=>{}))}catch(e){const t=c.fpCardStatus;t&&(t.textContent=`authorship panel unavailable: ${e&&e.message||e}`)}}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",po):po()}();
|
|
7
|
+
e.onMenuCredits&&e.onMenuCredits(Qt),e.onMenuFingerprint&&e.onMenuFingerprint((()=>{st&&"function"==typeof st.open&&st.open()})),e.onMenuGoogleDrive&&e.onMenuGoogleDrive((()=>{st&&"function"==typeof st.open&&st.open({focus:"drive"})})),e.onMenuExportMarkdown&&e.onMenuExportMarkdown((()=>ro("markdown"))),e.onMenuExportJson&&e.onMenuExportJson((()=>ro("json"))),e.onDeepLink&&e.onDeepLink(co),e.onQuickLauncherPush&&e.onQuickLauncherPush(ze),c.sessionsRefresh.addEventListener("click",Xn),c.sessionsFilter&&(c.sessionsFilter.addEventListener("input",(()=>Zn())),c.sessionsFilter.addEventListener("keydown",(e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),c.sessionsFilter.value="",Zn())}))),c.syncNow.addEventListener("click",ao),c.sessionsExport.addEventListener("click",(()=>ro("markdown"))),c.apiKeySave.addEventListener("click",we),c.apiKeyVerify.addEventListener("click",xe),c.apiKeyInput.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),we())})),c.customSave&&c.customSave.addEventListener("click",Un),c.customRemove&&c.customRemove.addEventListener("click",Fn);for(const e of[c.customBaseUrl,c.customKey,c.customModel])e&&e.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),Un())}));c.upgradePlan.addEventListener("click",(()=>ke("upgrade"))),c.topupBtn.addEventListener("click",(()=>ke("topup"))),attachScrollLift({panes:document.querySelectorAll(".messages, .side, .memory-scroll"),target:document.body,requestFrame:e=>window.requestAnimationFrame(e)}),c.quickLauncherSave.addEventListener("click",Se),c.quickLauncherShortcut.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),Se())})),c.confirmMode&&c.confirmMode.addEventListener("change",(()=>qe(c.confirmMode.checked))),c.planMode&&c.planMode.addEventListener("change",(()=>async function(t){if(c.planMode){c.planMode.disabled=!0;try{Me(await e.setPermissionMode(t))}catch(e){c.planMode.checked=!t,c.planModeHint&&(c.planModeHint.textContent=`save failed: ${e&&e.message?e.message:e}`)}finally{c.planMode.disabled=!1}}}(c.planMode.checked))),c.permRulesForm&&c.permRulesForm.addEventListener("submit",(t=>{t.preventDefault(),async function(t,n){if(!e.permRulesAdd)return;const o=String(null==n?"":n).trim();if(o){c.permRulesAdd&&(c.permRulesAdd.disabled=!0);try{const n=await e.permRulesAdd(t,o);if(n&&!0===n.ok){Ae(n),c.permRulesInput&&(c.permRulesInput.value="");const e=!1===n.added?"already stored":"stored";c.permRulesStatus&&(c.permRulesStatus.textContent=n.warning?`${e}: ${o} — ${n.warning}`:`${e}: ${o}`)}else c.permRulesStatus&&(c.permRulesStatus.textContent=`not stored: ${n&&n.reason||"the store refused it"}`)}catch(e){c.permRulesStatus&&(c.permRulesStatus.textContent=`add failed: ${e&&e.message?e.message:e}`)}finally{c.permRulesAdd&&(c.permRulesAdd.disabled=!1)}}else c.permRulesStatus&&(c.permRulesStatus.textContent="type a rule first")}(c.permRulesListSelect?c.permRulesListSelect.value:"allow",c.permRulesInput&&c.permRulesInput.value)})),c.sandboxMode&&c.sandboxMode.addEventListener("change",(()=>{const e=c.sandboxNetwork&&c.sandboxNetwork.checked?"open":"restricted";Te(c.sandboxMode.value,e)})),c.sandboxNetwork&&c.sandboxNetwork.addEventListener("change",(()=>{Te(c.sandboxMode?c.sandboxMode.value:"workspace-write",c.sandboxNetwork.checked?"open":"restricted")})),c.autoMode&&c.autoMode.addEventListener("click",(()=>{c.confirmMode&&qe(!c.confirmMode.checked)})),c.composer.addEventListener("submit",(e=>{e.preventDefault(),uo()})),c.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"))&&(yo+=1,document.body.classList.add("is-dropping"))})),window.addEventListener("dragleave",(()=>{yo=Math.max(0,yo-1),0===yo&&document.body.classList.remove("is-dropping")})),window.addEventListener("dragover",(e=>{e.dataTransfer&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")})),window.addEventListener("drop",(t=>{yo=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 Co(n):(po.push({name:t.name||"file",reason:"no path available"}),ho())}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=c.prompt;if(!t)return;const n="number"==typeof t.selectionStart?t.selectionStart:t.value.length,o="number"==typeof t.selectionEnd?t.selectionEnd:t.value.length,s=t.value.slice(0,n),a=t.value.slice(o),i=s&&!/\s$/.test(s)?" ":"";t.value=`${s}${i}${e}${a}`;const r=(s+i+e).length;try{t.setSelectionRange(r,r)}catch{}t.focus()}(s))}(t).catch((()=>{}))})),document.addEventListener("dragover",(e=>e.preventDefault())),document.addEventListener("drop",(e=>e.preventDefault())),c.classSelect&&c.classSelect.addEventListener("change",ho),ho()),c.prompt.addEventListener("keydown",(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),c.composer.requestSubmit())})),c.tabSessions&&c.tabSessions.addEventListener("click",(()=>Gn("sessions"))),c.tabMemory&&c.tabMemory.addEventListener("click",(()=>Gn("memory"))),c.memorySearchForm.addEventListener("submit",(e=>{e.preventDefault(),vt(c.memoryQuery.value.trim())})),c.memorySaveBtn.addEventListener("click",Yt),c.memoryImportBtn.addEventListener("click",Vt),c.sessionClose&&c.sessionClose.addEventListener("click",Tt),c.sessionBackdrop&&c.sessionBackdrop.addEventListener("click",Tt),c.sessionClear&&c.sessionClear.addEventListener("click",(()=>{c.sessionQuery&&(c.sessionQuery.value=""),qt="",c.sessionHint&&(c.sessionHint.textContent=""),Bt(""),c.sessionQuery&&c.sessionQuery.focus()})),c.sessionFilters&&c.sessionFilters.addEventListener("submit",(e=>{e.preventDefault(),Bt(c.sessionQuery?c.sessionQuery.value:"")})),c.sessionQuery&&c.sessionQuery.addEventListener("input",(()=>{Bt(c.sessionQuery.value)})),c.creditsClose&&c.creditsClose.addEventListener("click",Wt),c.creditsBackdrop&&c.creditsBackdrop.addEventListener("click",Wt),c.memoryOpen&&c.memoryOpen.addEventListener("click",St),c.memoryClose&&c.memoryClose.addEventListener("click",$t),c.memoryBackdrop&&c.memoryBackdrop.addEventListener("click",$t),c.memoryOverlaySave&&c.memoryOverlaySave.addEventListener("click",Yt),c.memoryFilters&&c.memoryFilters.addEventListener("submit",(e=>{e.preventDefault(),et.query=c.memoryOverlayQuery.value.trim(),Et(et.query)})),c.memoryFiltersClear&&c.memoryFiltersClear.addEventListener("click",(()=>{c.memoryOverlayQuery.value="",et.query="",et.source="",et.role="",xt()})),c.keysClose&&c.keysClose.addEventListener("click",fn),c.keysBackdrop&&c.keysBackdrop.addEventListener("click",fn),c.keysDismiss&&c.keysDismiss.addEventListener("click",hn),c.keysGotoAegis&&c.keysGotoAegis.addEventListener("click",(()=>{fn(),ln(c.apiKeyInput),c.apiKeyInput&&c.apiKeyInput.focus(),c.apiKeyHint&&(c.apiKeyHint.textContent=`Missing: ${function(){const e=[];return!0!==de&&e.push("the AEGIS key"),!0!==ue&&e.push("your provider (BYOK) key"),e.join(" and ")}()}. This is the AEGIS account key — the same one the CLI reads from ~/.aegiscode/.env, so pasting it here configures both.`)})),c.keysGotoByok&&c.keysGotoByok.addEventListener("click",(()=>{fn(),cn()})),s&&(c.queueEnqueue&&c.queueEnqueue.addEventListener("click",Ke),c.queueDrain&&c.queueDrain.addEventListener("click",(()=>je("one"))),c.queueProceed&&c.queueProceed.addEventListener("click",(()=>je("all"))),c.queueStop&&c.queueStop.addEventListener("click",Ge),"function"==typeof s.onProgress&&s.onProgress(Ye),c.queueClassSelect&&c.queueClassSelect.addEventListener("change",(()=>{localStorage.setItem(u,c.queueClassSelect.value),In(c.queueClassSelect.value)})),await _e(),await async function(){if(!c.queueClassSelect)return;let e=[];try{e=await t.listClasses()||[]}catch(t){e=[],c.queueModelHint&&(c.queueModelHint.textContent=`listClasses failed: ${t&&t.message?t.message:t}`)}c.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)`,c.queueClassSelect.appendChild(e)}const n=localStorage.getItem(u);n&&e.some((e=>e.class===n))&&(c.queueClassSelect.value=n),await In(c.queueClassSelect.value)}()),a&&(c.queueAuto&&c.queueAuto.addEventListener("change",(()=>Ve(c.queueAuto.checked))),c.queueAutoInterval&&c.queueAutoInterval.addEventListener("change",(()=>{c.queueAuto&&c.queueAuto.checked&&Ve(!0)})),await async function(){if(!a||"function"!=typeof a.status)return null;try{const e=await a.status();return We(e),e}catch(e){return c.queueAutoHint&&(c.queueAutoHint.textContent=`automation status unavailable: ${e&&e.message?e.message:e}`),null}}()),Z=createTranscriptView({messages:c.messages,requestFrame:e=>requestAnimationFrame(e)}),Z.attachScrollVeto();let h=null;window.__aegisSmoke=Object.freeze({isScrolledUp:()=>Z.isScrolledUp(),metrics:()=>Z.metrics(),escapeDecision:()=>h&&"function"==typeof h.lastDecision?h.lastDecision():null,stopOutcome:()=>te}),h=bindEscapeInterrupt({doc:document,isOverlayOpen:tt,onOverlayEscape:()=>{if(Mt())Tt();else if(Dt())Ut();else if(Kt())Wt();else if(ot())fn();else{if(st&&"function"==typeof st.close)try{return void st.close()}catch(e){}$t()}},hasPendingTurn:()=>!!T,stopTurn:ne}),c.accountBanner&&e.onAccountStatus&&(e.onAccountStatus(ge),e.accountStatus().then(ge).catch((e=>console.warn("account status unavailable",e))),c.accountRetryBtn.addEventListener("click",(()=>ve(c.accountRetryBtn))),c.keysAccountRetry&&c.keysAccountRetry.addEventListener("click",(()=>ve(c.keysAccountRetry)))),c.updateBanner&&e.onUpdateStatus&&(e.onUpdateStatus(fe),e.updateStatus().then(fe).catch((()=>{})),c.updateDownloadBtn.addEventListener("click",(()=>{c.updateDownloadBtn.disabled=!0,Promise.resolve(e.downloadUpdate()).then((e=>{e&&e.status&&fe(e)})).catch((()=>{})).finally((()=>{c.updateDownloadBtn.disabled=!1}))})),c.updateRestartBtn.addEventListener("click",(()=>{e.quitAndInstallUpdate()})),c.updateRetryBtn&&e.checkForUpdates&&c.updateRetryBtn.addEventListener("click",(()=>{c.updateRetryBtn.disabled=!0,Promise.resolve(e.checkForUpdates()).then(fe).catch((()=>{})).finally((()=>{c.updateRetryBtn.disabled=!1}))})),c.updateLaterBtn.addEventListener("click",(()=>{ye=pe&&pe.status,c.updateBanner.hidden=!0}))),c.messages.querySelector(".msg, .chatflow")||sn(),await An(),await On(),await async function(){if(o)try{Ee(await o.status())}catch(e){c.quickLauncherHint.textContent=`status failed: ${e&&e.message?e.message:e}`}}(),await async function(){if(c.confirmMode&&e.getConfirmMode)try{$e(await e.getConfirmMode())}catch(e){c.confirmModeHint.textContent=`status failed: ${e&&e.message?e.message:e}`}}(),await async function(){if(c.planMode&&e.getPermissionMode)try{Me(await e.getPermissionMode())}catch(e){c.planModeHint&&(c.planModeHint.textContent=`status failed: ${e&&e.message?e.message:e}`)}}(),await async function(){if(c.permRulesList&&e.permRulesList)try{Ae(await e.permRulesList())}catch(e){Ae({ok:!1,reason:e&&e.message||String(e)})}}(),await Re(),await Xn(),await oo(),Ce(),Gn("sessions"),c.memoryQuietFloor&&(c.memoryQuietFloor.textContent=String(Xe)),vt("");try{!function(){if(window.aegisProviderToolbar&&c.ptList)if(at=window.aegisProviderToolbar.mount({list:c.ptList,count:c.ptCount,search:c.ptSearch,hint:c.ptHint,onSelect:lt}),c.ptRefresh&&c.ptRefresh.addEventListener("click",(()=>{rt(!0)})),"function"==typeof IntersectionObserver&&c.ptList.closest("section")){const e=new IntersectionObserver((t=>{t.some((e=>e.isIntersecting))&&(e.disconnect(),rt(!1))}));e.observe(c.ptList.closest("section"))}else rt(!1)}()}catch(e){c.ptHint&&(c.ptHint.textContent=`provider list unavailable: ${e&&e.message||e}`)}if(c.companionDismiss&&c.companionDismiss.addEventListener("click",(()=>{localStorage.setItem(ct,JSON.stringify({day:window.aegisCompanion?window.aegisCompanion.dayKey(new Date):"",id:c.companionCard.dataset.messageId||""})),c.companionCard.hidden=!0})),ut(),window.aegisFingerprint)try{st=window.aegisFingerprint.mount({api:e,getSessionId:()=>O}),st.refresh().catch((()=>{}))}catch(e){const t=c.fpCardStatus;t&&(t.textContent=`authorship panel unavailable: ${e&&e.message||e}`)}}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",xo):xo()}();
|