aegisone 1.0.38 → 1.0.40
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/LICENSING.md +186 -0
- package/README.md +2 -2
- package/bin/aegis.js +1 -1
- package/package.json +3 -2
- package/scripts/predist.mjs +1 -1
- package/src/child.js +1 -1
- package/src/permissions.js +1 -1
- package/vendor/cli/package.json +4 -2
- package/vendor/cli/src/app.js +1 -1
- package/vendor/cli/src/chatflow.js +1 -1
- package/vendor/cli/src/commands.js +3 -1
- package/vendor/cli/src/config.js +1 -1
- package/vendor/cli/src/engine.js +1 -1
- package/vendor/cli/src/history.js +1 -1
- package/vendor/cli/src/models.js +1 -1
- package/vendor/cli/src/overlays.js +1 -1
- package/vendor/cli/src/panels.js +1 -1
- package/vendor/cli/vendor/client/brain-catalog.js +1 -1
- package/vendor/cli/vendor/client/byok-catalog.js +1 -1
- package/vendor/cli/vendor/client/credits.js +45 -0
- package/vendor/cli/vendor/client/foreign-sessions.js +3 -0
- package/vendor/cli/vendor/client/naming.js +1 -1
- package/vendor/cli/vendor/client/prefs.js +1 -1
- package/vendor/cli/vendor/client/session-search.js +3 -0
- package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/integrity.js +42 -2
- package/vendor/cli/vendor/desktop/lib/local/perm-rules.js +206 -0
- package/vendor/cli/vendor/desktop/lib/local/perm-store.js +298 -0
- package/vendor/cli/vendor/desktop/lib/local/perm-write.js +199 -0
- package/vendor/cli/vendor/desktop/lib/local/pro-sessions.js +3 -0
- package/vendor/cli/vendor/desktop/lib/local/sandbox-appcontainer.js +242 -0
- package/vendor/cli/vendor/desktop/lib/local/sandbox-bwrap.js +316 -0
- package/vendor/cli/vendor/desktop/lib/local/sandbox-seatbelt.js +380 -0
- package/vendor/cli/vendor/desktop/lib/local/sandbox.js +493 -0
- package/vendor/cli/vendor/desktop/lib/local/shell.js +155 -20
- package/vendor/cli/vendor/desktop/lib/local/tools.js +29 -4
- package/vendor/cli/vendor/desktop/lib/settings.js +1 -1
- package/vendor/cli/vendor/desktop/main.js +774 -37
- package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/cli/vendor/mcp/admission.js +3 -0
- package/vendor/cli/vendor/mcp/server.js +1 -1
- package/vendor/cli/vendor/one/src/child.js +1 -1
- package/vendor/cli/vendor/one/src/permissions.js +1 -1
- package/vendor/desktop/bin/aegis.js +1 -1
- package/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/lib/local/integrity.js +42 -2
- package/vendor/desktop/lib/local/perm-rules.js +206 -0
- package/vendor/desktop/lib/local/perm-store.js +298 -0
- package/vendor/desktop/lib/local/perm-write.js +199 -0
- package/vendor/desktop/lib/local/pro-sessions.js +3 -0
- package/vendor/desktop/lib/local/sandbox-appcontainer.js +242 -0
- package/vendor/desktop/lib/local/sandbox-bwrap.js +316 -0
- package/vendor/desktop/lib/local/sandbox-seatbelt.js +380 -0
- package/vendor/desktop/lib/local/sandbox.js +493 -0
- package/vendor/desktop/lib/local/shell.js +155 -20
- package/vendor/desktop/lib/local/tools.js +29 -4
- package/vendor/desktop/lib/settings.js +1 -1
- package/vendor/desktop/lib/sync/memory-store.js +3 -0
- package/vendor/desktop/main.js +774 -37
- package/vendor/desktop/package.json +20 -7
- package/vendor/desktop/preload.js +1 -1
- package/vendor/desktop/renderer/app.js +5 -1
- package/vendor/desktop/renderer/index.html +221 -5
- package/vendor/desktop/renderer/provider-mark.js +1 -1
- package/vendor/desktop/renderer/provider-toolbar.js +1 -1
- package/vendor/desktop/renderer/providers.js +1 -1
- package/vendor/desktop/renderer/style.css +223 -6
- package/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/desktop/vendor/brain-catalog.js +1 -1
- package/vendor/desktop/vendor/byok-catalog.js +1 -1
- package/vendor/desktop/vendor/credits.js +45 -0
- package/vendor/desktop/vendor/faces/cli/package.json +3 -2
- package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/chatflow.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/commands.js +3 -1
- package/vendor/desktop/vendor/faces/cli/src/config.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/engine.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/history.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/models.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/overlays.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/panels.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/brain-catalog.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/credits.js +45 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-sessions.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/session-search.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
- 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-rules.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-store.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-write.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/pro-sessions.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox-appcontainer.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox-bwrap.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox-seatbelt.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/shell.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +4 -2
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/admission.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/server.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/child.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/permissions.js +1 -1
- package/vendor/desktop/vendor/foreign-sessions.js +3 -0
- package/vendor/desktop/vendor/naming.js +1 -1
- package/vendor/desktop/vendor/prefs.js +1 -1
- package/vendor/desktop/vendor/sandbox/provenance.json +20 -0
- package/vendor/desktop/vendor/sandbox/x64-linux/bwrap +0 -0
- package/vendor/desktop/vendor/session-search.js +3 -0
|
@@ -1,3 +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;if(!e||!t)throw document.body.textContent="This page must run inside the AEGIS Electron host (window.aegis/window.models missing).",new Error("window.aegis/window.models unavailable — not running under Electron");const i={updateBanner:"update-banner",updateBannerText:"update-banner-text",updateDownloadBtn:"update-download-btn",updateRestartBtn:"update-restart-btn",updateRetryBtn:"update-retry-btn",updateLaterBtn:"update-later-btn",accountBanner:"account-banner",accountBannerText:"account-banner-text",accountRetryBtn:"account-retry-btn",keysAccount:"keys-account",keysAccountRetry:"keys-account-retry",connDot:"conn-dot",connText:"conn-text",app:"st-app",client:"st-client",base:"st-base",key:"st-key",plan:"st-plan",balance:"st-balance",upgradePlan:"upgrade-plan",topupBtn:"topup-btn",topupAmount:"topup-amount",billingHint:"billing-hint",apiKeyInput:"api-key-input",apiKeySave:"api-key-save",apiKeyVerify:"api-key-verify",apiKeyHint:"api-key-hint",classSelect:"class-select",modelSelect:"model-select",providerMark:"provider-mark",ptSearch:"pt-search",ptRefresh:"pt-refresh",ptList:"pt-list",ptCount:"pt-count",ptHint:"pt-hint",companionCard:"companion-card",companionText:"companion-text",companionDismiss:"companion-dismiss",modelFree:"model-input",budgetHint:"budget-hint",autonomousToggle:"autonomous-toggle",autonomousToggleWrap:"autonomous-toggle-wrap",autonomousControls:"autonomous-controls",effortSelect:"effort-select",autonomousWorkers:"autonomous-workers",modelHint:"model-hint",settingsList:"settings-list",settingsHint:"settings-hint",customBaseUrl:"custom-base-url",customKey:"custom-key",customModel:"custom-model",customSave:"custom-save",customRemove:"custom-remove",customStatus:"custom-status",quickLauncherEnabled:"quick-launcher-enabled",quickLauncherShortcut:"quick-launcher-shortcut",quickLauncherSave:"quick-launcher-save",quickLauncherHint:"quick-launcher-hint",confirmMode:"confirm-mode-toggle",confirmModeHint:"confirm-mode-hint",autoMode:"auto-mode-toggle",autoModeLabel:"auto-mode-label",autoModeHint:"auto-mode-hint",sessionsRefresh:"sessions-refresh",sessionsExport:"sessions-export",sessionsList:"sessions-list",sessionsHint:"sessions-hint",syncNow:"sync-now",syncStatus:"sync-status",sessionMeter:"session-meter",newChat:"new-chat",memorySearchForm:"memory-search-form",memoryQuery:"memory-query",memoryResults:"memory-results",memoryEntry:"memory-entry",memorySaveBtn:"memory-save-btn",memoryImportBtn:"memory-import-btn",memoryHint:"memory-hint",memoryOpen:"memory-open",memoryBox:"memory-box",memoryQuiet:"memory-quiet",memoryQuietFloor:"memory-quiet-floor",paneTabs:"pane-tabs",tabSessions:"tab-sessions",tabMemory:"tab-memory",paneSessions:"pane-sessions",paneMemory:"pane-memory",memoryOverlay:"memory-overlay",memoryBackdrop:"memory-backdrop",memoryClose:"memory-close",memoryFilters:"memory-filters",memoryOverlayQuery:"memory-overlay-query",memoryFiltersClear:"memory-filters-clear",memoryChips:"memory-chips",memoryList:"memory-list",memoryCount:"memory-count",memoryOverlayEntry:"memory-overlay-entry",memoryOverlaySave:"memory-overlay-save",fpCardStatus:"fp-card-status",fpOpen:"fp-open",fpOverlay:"fp-overlay",messages:"messages",composer:"composer",prompt:"prompt",send:"send",attachRow:"attach-row",attachNote:"attach-note",dropVeil:"drop-veil",exploreToggle:"explore-toggle",queueTask:"queue-task",queueClassSelect:"queue-class-select",queueModelSelect:"queue-model-select",queueModelInput:"queue-model-input",queueModelHint:"queue-model-hint",queueCwd:"queue-cwd",queueCommit:"queue-commit",queueEnqueue:"queue-enqueue",queueDrain:"queue-drain",queueProceed:"queue-proceed",queueStop:"queue-stop",queueList:"queue-list",queueHint:"queue-hint",queueFanout:"queue-fanout",queueFanoutLabel:"queue-fanout-label",queueAuto:"queue-auto",queueAutoLabel:"queue-auto-label",queueAutoInterval:"queue-auto-interval",queueAutoHint:"queue-auto-hint",queueBoundary:"queue-boundary",queueUpgrade:"queue-upgrade",keysOverlay:"keys-overlay",keysBackdrop:"keys-backdrop",keysClose:"keys-close",keysCount:"keys-count",keysRowAegis:"keys-row-aegis",keysRowByok:"keys-row-byok",keysAegisState:"keys-aegis-state",keysByokState:"keys-byok-state",keysGotoAegis:"keys-goto-aegis",keysGotoByok:"keys-goto-byok",keysHint:"keys-hint",keysDismiss:"keys-dismiss"},r={};for(const[e,t]of Object.entries(i))Object.defineProperty(r,e,{get:()=>document.getElementById(t),enumerable:!0,configurable:!0});const l="aegis.class",c="aegis.queueClass",d="aegis.autonomous",u="aegis.effort",m="aegis.autonomousWorkers",p="aegis.explore",y="aegis.welcomeConnectDismissed",h="aegis",f=new Set(["__aegis","aegis"]),g="local",v="custom",k="http://localhost:11434",C="https://aegiscloud.org/key?s=desktop&c=key_prompt",b="The autonomous queue keeps running after you close the laptop.",w="https://aegiscloud.org",x=/^[a-z0-9][a-z0-9_-]{0,63}$/;function S(e,t){const n=new URL(`${w}/go/${e}`);n.searchParams.set("s","desktop");const o=null==t?"":String(t).trim().toLowerCase();return x.test(o)&&n.searchParams.set("c",o),n.toString()}function E(e){return S("upgrade",e)}function $(e){return S("topup",e)}const q={welcome_cloud:"welcome",queue_cap:"queue",memory_quota:"memory",status_card:"status",topup_bank:"topup"},L="upgrade_prompt_rendered",A="upgrade_prompt_clicked";let M=!1;function N(e,t){try{const n=q[t];if(!n)return;const o=window.aegis;if(!o||"function"!=typeof o.telemetryEvent)return;const s=o.telemetryEvent(e,{campaign:t,surface:n});s&&"function"==typeof s.catch&&s.catch((()=>{}))}catch(e){if(!M){M=!0;try{console.debug("telemetry: prompt event failed (suppressed)",e)}catch{}}}}function H(e,t,n,o){const s=document.createElement("a");return s.href=function(e,t){const n="topup_bank"===t?$(t):E(t);if(!e)return n;let o;try{o=new URL(e,w)}catch{return e}return o.origin!==w||o.searchParams.get("s")||o.searchParams.get("utm_source")?e:/topup/.test(o.pathname)?$(t):n}(t,n),s.target="_blank",s.rel="noreferrer noopener",s.textContent=o,s.addEventListener("click",(()=>N(A,n))),e.appendChild(s),!1===e.isConnected||e.hidden||N(L,n),s}let I=null,B=null,T=null,R=[],U=[],O=new Map;const D=new Map;function F(e,t,n={}){const o=e||"",s=rollTurn(function(e){const t=e||"";return D.has(t)||D.set(t,emptyRoll()),D.get(t)}(o),t,n);return D.set(o,s),K(o),s}function K(e,t){const n=r.sessionMeter,o=t?function(e){const t="string"==typeof e.reply?e.reply:"",n="string"==typeof e.reasoning?e.reasoning:"",o="number"==typeof e.measuredReasoningTokens&&e.measuredReasoningTokens>0?e.measuredReasoningTokens:0;if(!t&&!n&&!o)return"↓0 tokens";let s=0;try{const o=estimatedBuckets(e.prompt,t,n);o&&"number"==typeof o.output&&o.output>0&&(s=o.output)}catch(e){}if(!s){let e=0;for(const o of[t,n]){let t=0;for(;t<o.length;)t+=o.codePointAt(t)>65535?2:1,e+=1}s=Math.ceil(e/4)}return s+=o,s?`↓${o>0?"≥":""}${Math.round(s)} tokens`:""}(t):"",s=t?function(){if(!I)return null;let e=I.querySelector(".typing-tokens");return e||(e=document.createElement("span"),e.className="typing-tokens",e.hidden=!0,I.appendChild(e)),e}():null;if(s&&(s.textContent=o,s.hidden=!o),!n)return;if(T!==e)return void(n.hidden=!0);let a=D.get(e||"");t&&(a=rollTurn(a||emptyRoll(),void 0,{prompt:t.prompt,reply:t.reply,reasoning:t.reasoning,measuredReasoningTokens:t.measuredReasoningTokens}));const i=a?fmtRoll(a):"";return n.textContent=i,n.hidden=!i,n.classList.toggle("live",!!t&&!!i),i&&(n.title="This session, counted the way the CLI counts it — every turn rolled into one running total"),a}function P(e,t,n,o){const s=ledgerRow(e,n,{model:t,costUsd:n&&n.real&&"number"==typeof n.cost?n.cost:void 0,calls:o&&o.calls,prompt:o&&o.prompt,reply:o&&o.reply,reasoning:o&&o.reasoning}),a=s?Object.assign({},s):{};return t&&(a.model=t),a}const _="You are the exploratory half of a chat assistant. The user is reading the main answer elsewhere, so never restate it. Be concrete and brief: one lead line naming the path, then 3-5 tight bullets. Never pad.",j=[{key:"alternate",badge:"A",title:"Alternative angle",hint:"Answer the request from a genuinely different angle: another method, school of thought or genre. Name the angle in one line, then 3-5 bullets of how it actually plays out. Do not restate the main answer."},{key:"discovery",badge:"B",title:"Unexpected discovery",hint:"Act as a scout, not an assistant. Surface ONE non-obvious connection, adjacent field or surprise finding the user did not ask for but which reframes the request. One line naming the discovery, then 2-4 bullets on why it matters and how to test it. Flag uncertainty honestly."},{key:"genre",badge:"C",title:"New genre",hint:"Recast the request in an unfamiliar genre or discipline — pick one that fits oddly well (e.g. field biology, contract law, ecology, jazz, logistics, restoration). Name the genre in one line, then 3-5 bullets of what that discipline would do first."}];let G=0;const Q=new Set;function W(){for(const e of Q)try{t.cancel(e)}catch{}Q.clear()}let V=0,Y=null,z=null,J=null;function X(e){return!!J&&J.follow(e)}let Z=null;function ee(){if(!B)return!1;if(!stopAppliesTo(Y,z))return!1;z=Y;const e=B;Z={sessionId:e,at:Date.now(),state:"requested"};try{const n=t.cancel(e);n&&"function"==typeof n.then&&n.then((t=>{Z={sessionId:e,at:Date.now(),state:"settled",accepted:!t||!1!==t.ok,result:void 0===t?null:t}}),(t=>{Z={sessionId:e,at:Date.now(),state:"rejected",accepted:!1,error:t&&t.message||String(t)}}))}catch(t){Z={sessionId:e,at:Date.now(),state:"threw",accepted:!1,error:t&&t.message||String(t)}}if(I){const e=I.querySelector(".cancel-btn");e&&(e.disabled=!0,e.textContent="stopping…")}return!0}function te(){const e=r.autonomousToggle;return Boolean(e&&e.checked)}function ne(){if(!r.autonomousControls)return;const e=r.autonomousToggleWrap&&!r.autonomousToggleWrap.hidden;r.autonomousControls.hidden=!(e&&te())}function oe(){if(r.modelFree&&!r.modelFree.hidden){const e=r.modelFree.value.trim();if(e)return e}return r.modelSelect.value}function se(e,t){const n=void 0===t?oe():t;r.budgetHint&&(r.budgetHint.textContent=function(e,t){const n=ie(),o=n,s=n;return e===h?`budget: ${{low:16384,medium:32768,high:65536,max:65536}[o].toLocaleString()} tokens from effort (${s}), summed across the worker fan-out by the Aegis Cloud pool — no max_tokens is sent.`:DEEPSEEK_REASONING_MODEL_RE.test(String(t||""))?`budget: ${EFFORT_TOKEN_BUDGET[o].toLocaleString()} tokens from effort (${s}) — this model reasons against its own output budget, and the length of the answer is not predictable from the prompt.`:`no token cap is sent (effort: ${s}) — output length cannot be predicted from the prompt, so this app states no max_tokens and the provider's own limit applies.`}(e,n)),ae()}function ae(){r.providerMark&&window.aegisProviderMark&&window.aegisProviderMark.paint(r.providerMark,oe())}function ie(){const e=r.effortSelect&&r.effortSelect.value;return"low"===e||"medium"===e||"max"===e?e:"high"}function re(e,t){r.connDot.classList.toggle("ok",Boolean(e)),r.connText.textContent=t}let le=null,ce=!1;function de(e){if(!e)return le=null,ce=!1,void re(!1,"IPC unavailable");le=Boolean(e.keyConfigured),ce=Boolean(e.providerConfigured),r.app.textContent=e.appVersion?`v${e.appVersion}`:"–",r.client.textContent=e.clientVersion||"–",r.base.textContent=e.apiBase||"–",r.key.textContent=e.keyConfigured?e.keyMask:"not set",re(e.keyConfigured,e.keyConfigured?"key configured":"no API key"),qt(),Ct(),function(){const e=document.getElementById("keys-overlay");if(!e)return;let t=!1;try{t="on"===localStorage.getItem(Bt)}catch{}t||null===le?e.hidden=!0:(Tt(),Boolean(B)?Rt():!0!==le||!0!==ce?r.keysOverlay&&(Tt(),r.keysOverlay.hidden&&(r.keysOverlay.hidden=!1,document.body.classList.add("keys-open"))):Rt())}()}let ue=null,me=null;function pe(e){if(!r.updateBanner)return;ue=e;try{tt()}catch{}const t=e&&e.status;if(!t||"idle"===t||"disabled"===t||"checking"===t||"up-to-date"===t||"unavailable"===t||t===me)return void(r.updateBanner.hidden=!0);let n="",o=!1,s=!1,a=!1;const i=e.version?`v${e.version} `:"";if("available"===t)n=e.command?e.commandIsSentence?`Update ${i}available. ${e.command}`:`Update ${i}available — run: ${e.command}`:`Update ${i}available.`,o=!!e.canDownload,o&&(n=`Update ${i}available.`);else if("downloading"===t)n=`Downloading update${"number"==typeof e.progress?` (${Math.round(e.progress)}%)`:""}…`;else if("downloaded"===t)n=`Update ${i}downloaded — restart to install.`,s=!0;else{if("error"!==t)return void(r.updateBanner.hidden=!0);n=`Update check failed: ${e.error||"unknown error"}`,e.transient&&(n+=" — will retry automatically."),a=!0}r.updateBannerText.textContent=n,r.updateDownloadBtn.hidden=!o,r.updateRestartBtn.hidden=!s,r.updateRetryBtn&&(r.updateRetryBtn.hidden=!a),r.updateBanner.hidden=!1}let ye=null;function he(e){ye=e&&"no-key"===e.status?e.reason:null,Tt(),r.accountBanner&&(ye?(r.accountBannerText.textContent=`No AEGIS account key on this machine: ${ye}.`,r.accountBanner.hidden=!1):r.accountBanner.hidden=!0)}function fe(t){t.disabled=!0,e.registerAccount().then((e=>{if(he(e),!e)return ke()})).catch((e=>he({status:"no-key",reason:String(e&&e.message||e)}))).finally((()=>{t.disabled=!1}))}async function ge(){try{const t=await e.verifyApiKey();t&&t.ok?r.plan.textContent=t.valid?t.plan||"active":"invalid key":r.plan.textContent="unavailable"}catch{r.plan.textContent="unavailable"}try{const t=await e.tokenBankBalance();r.balance.textContent=t&&null!=t.balance_eur?`€${t.balance_eur}`:"–"}catch{r.balance.textContent="unavailable"}}async function ve(t){const n=Math.round(Number(r.topupAmount&&r.topupAmount.value)||10),o="topup"===t?r.topupBtn:r.upgradePlan;if(o&&(o.disabled=!0),"topup"===t&&!1===le)return o&&(o.disabled=!1),void(r.billingHint.textContent="add your AEGIS API key above — a top-up is credited to your account");r.billingHint.textContent="topup"===t?`creating a €${n} top-up…`:"creating checkout…";try{const o="topup"===t?await e.tokenBankTopup(n):await e.billingCheckout();if(!o||!0!==o.ok||!o.url)return void function(e,t){const n="topup"===t?"top-up":"upgrade";if(401!==e.status&&403!==e.status)return e.upgrade?(r.billingHint.textContent=`free plan cap reached — ${n} lifts it. `,void H(r.billingHint,e.upgrade.url,"topup"===t?"topup_bank":"status_card","See plans →")):void(e.setupRequired?r.billingHint.textContent="checkout is not configured on the server yet (no Stripe price id)":r.billingHint.textContent=`${n} failed: ${e.reason||"the server returned no checkout URL"}`);r.billingHint.textContent=`add your AEGIS API key above — a ${n} needs an account`}(o||{},t);r.billingHint.textContent="opening checkout…";const s=await e.openExternal(o.url);if(s&&!1===s.ok)return void(r.billingHint.textContent=`could not open the checkout page: ${s.reason||"unknown reason"}`);r.billingHint.textContent="topup"===t?"checkout opened in your browser — the bank is credited when Stripe confirms":"checkout opened in your browser — your plan updates when Stripe confirms"}catch(e){r.billingHint.textContent=`billing failed: ${e&&e.message?e.message:e}`}finally{o&&(o.disabled=!1)}}async function ke(){try{de(await e.status())}catch{de(null)}await Xt(),await ge()}async function Ce(){const t=r.apiKeyInput.value.trim();r.apiKeySave.disabled=!0,r.apiKeyVerify.disabled=!0,r.apiKeyHint.textContent="saving…";try{const n=await e.setApiKey(t);if(!n||!n.ok)throw new Error(n&&n.error||"save failed");r.apiKeyInput.value="",r.apiKeyHint.textContent=t?`saved (${n.keyMask?n.keyMask:"configured"})`:"key cleared",await ke()}catch(e){r.apiKeyHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{r.apiKeySave.disabled=!1,r.apiKeyVerify.disabled=!1}}async function be(){r.apiKeyVerify.disabled=!0,r.apiKeyHint.textContent="verifying…";try{const t=await e.verifyApiKey();if(!t||!t.ok)throw new Error(t&&t.error||"verify failed");r.apiKeyHint.textContent=t.valid?`valid (${t.plan||"active"})`:"invalid key"}catch(e){r.apiKeyHint.textContent=`verify failed: ${e&&e.message?e.message:e}`}finally{r.apiKeyVerify.disabled=!1}}function we(e){if(!e)return;r.quickLauncherEnabled.checked=Boolean(e.enabled),r.quickLauncherShortcut.value=e.shortcut||"",r.quickLauncherShortcut.placeholder=e.shortcut||"CmdOrCtrl+Shift+Space";const t=[];e.packaged&&t.push("always on in this packaged build"),t.push(e.active?`active — press ${e.shortcut} anywhere`:"inactive"),e.reason&&t.push(e.reason),r.quickLauncherHint.textContent=t.join(" · ")}async function xe(){if(o){r.quickLauncherSave.disabled=!0,r.quickLauncherHint.textContent="saving…";try{we(await o.setConfig({enabled:r.quickLauncherEnabled.checked,shortcut:r.quickLauncherShortcut.value.trim()}))}catch(e){r.quickLauncherHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{r.quickLauncherSave.disabled=!1}}}function Se(e){if(!r.confirmMode||!e)return;const t=!1!==e.enabled;r.confirmMode.checked=t,r.confirmModeHint.textContent=t?"On — exec, writeFile and editFile ask for your approval before they run.":"Off — the agent runs exec, writeFile and editFile without asking.",Ee(t)}function Ee(e){if(!r.autoMode)return;const t=!e;r.autoMode.setAttribute("aria-pressed",t?"true":"false"),r.autoMode.classList.toggle("is-auto",t),r.autoModeLabel&&(r.autoModeLabel.textContent=t?"auto mode":"ask before tools"),r.autoModeHint&&(r.autoModeHint.textContent=t?"on — tools run without asking. Click to require approval.":"off — click for auto mode, or use Settings → Tool approvals.")}async function $e(t){if(r.confirmMode){r.confirmMode.disabled=!0,r.autoMode&&(r.autoMode.disabled=!0);try{Se(await e.setConfirmMode(t))}catch(e){r.confirmMode.checked=!t,r.confirmModeHint.textContent=`save failed: ${e&&e.message?e.message:e}`,Ee(r.confirmMode.checked)}finally{r.confirmMode.disabled=!1,r.autoMode&&(r.autoMode.disabled=!1)}}}let qe="",Le=!1;function Ae(e){qe=e||"",r.queueHint&&(r.queueHint.textContent=qe)}function Me(e){const t=document.createElement("li");t.className="session-row",t.dataset.status=e.status;const n=document.createElement("span");n.className="session-title";const o=String(e.task||"").replace(/\s+/g," ").trim();var s;n.textContent=`#${e.id} ${s=e.status,"done"===s?"✓":"error"===s?"✗":"running"===s?"…":"·"} ${o.length>90?`${o.slice(0,89)}…`:o}`,t.appendChild(n);const a=document.createElement("span");if(a.className="session-meta",a.textContent=function(e){const t=[e.status];if(e.model&&t.push(e.model),t.push(!1===e.singlePass||!0===e.autonomous?"fan-out":"single pass"),"error"===e.status)t.push(e.error?String(e.error):"failed — no reason recorded");else if("done"===e.status){const n=(e.result&&e.result.output?String(e.result.output):"").replace(/\s+/g," ").trim();n&&t.push(n.length>140?`${n.slice(0,139)}…`:n);const o=e.result&&Array.isArray(e.result.files)?e.result.files:[];o.length&&t.push(`touched ${o.length} file${1===o.length?"":"s"}`)}else"running"===e.status?t.push(e.startedAt?`started ${nt(e.startedAt)}`:"working"):(e.attempts&&t.push(`${e.attempts} attempt${1===e.attempts?"":"s"}`),e.created&&t.push(nt(e.created)));return t.join(" · ")}(e),t.appendChild(a),"done"===e.status||"error"===e.status){const n=document.createElement("button");n.type="button",n.className="ghost-btn",n.textContent="Retry",n.title="Put this task back in line and run it again",n.addEventListener("click",(()=>Re("retry",e.id))),t.appendChild(n)}if("running"!==e.status){const n=document.createElement("button");n.type="button",n.className="ghost-btn",n.textContent="Remove",n.addEventListener("click",(()=>Re("remove",e.id))),t.appendChild(n)}return t}function Ne(e){if(!r.queueList||!e||"object"!=typeof e)return;Le=Boolean(e.draining),r.queueCwd&&!r.queueCwd.value&&(r.queueCwd.value=e.defaultCwd||""),r.queueEnqueue&&(r.queueEnqueue.disabled=Le),r.queueDrain&&(r.queueDrain.disabled=Le),r.queueProceed&&(r.queueProceed.disabled=Le),r.queueStop&&(r.queueStop.hidden=!Le);const t=Array.isArray(e.items)?e.items:[];if(r.queueList.innerHTML="",t.length)for(const e of t)r.queueList.appendChild(Me(e));else{const e=document.createElement("li");e.className="empty",e.textContent="queue is empty",r.queueList.appendChild(e)}const n=[];e.running?n.push(`running #${e.running.id}`):Le&&n.push("draining…"),n.push(`${e.pending||0} pending`),e.defaultModel&&n.push(`Aegis Cloud · ${e.defaultModel}`),Le&&e.stopping&&n.push("stopping after this task"),function(e){const t=e&&e.entitlement?e.entitlement:null,n=Boolean(t&&t.source&&"unresolved"!==t.source),o=Boolean(t&&t.entitled);if(r.queueFanout&&(r.queueFanout.disabled=!o,o||(r.queueFanout.checked=!1)),r.queueBoundary&&(r.queueBoundary.textContent=n?o?t.pro?`${t.tierName||"Pro"} — the cloud drain and the fan-out are unlocked.`:"Balance on your account — the cloud drain and the fan-out are unlocked.":t.refusal||"":""),r.queueUpgrade&&(r.queueUpgrade.innerHTML="",n&&!o)){const e="balance"===t.wall;H(r.queueUpgrade,t.upgradeUrl,t.campaign,e?"Top up your balance ↗":"See what Pro covers ↗")}}(e),r.queueHint&&(r.queueHint.textContent=[qe,n.join(" · ")].filter(Boolean).join(" · "))}async function He(){if(!s||!r.queueList)return null;try{const e=await s.list();return Ne(e),e}catch(e){return Ae(`queue list failed: ${e&&e.message?e.message:e}`),null}}async function Ie(){if(!s||!r.queueTask)return;const e=r.queueTask.value.trim();if(e){r.queueEnqueue&&(r.queueEnqueue.disabled=!0),Ae("queueing…");try{const t=await s.enqueue({task:e,cwd:r.queueCwd?r.queueCwd.value.trim():"",class:r.queueClassSelect?r.queueClassSelect.value:void 0,model:en(),commit:!!r.queueCommit&&r.queueCommit.checked});t&&t.ok?(r.queueTask.value="",Ae(`queued #${t.item.id}`)):Ae(t&&t.reason||"enqueue failed"),Ne(t)}catch(e){Ae(`enqueue failed: ${e&&e.message?e.message:e}`)}finally{r.queueEnqueue&&(r.queueEnqueue.disabled=Le)}}else Ae("type a task first")}async function Be(e){if(s){Le=!0,Ae("one"===e?"running one task…":"draining the queue…"),r.queueDrain&&(r.queueDrain.disabled=!0),r.queueProceed&&(r.queueProceed.disabled=!0),r.queueEnqueue&&(r.queueEnqueue.disabled=!0),r.queueStop&&(r.queueStop.hidden=!1);try{const t=await("one"===e?s.drain():s.proceed());Ae(function(e){if(!e||"object"!=typeof e)return"the drain did not answer";if(e.locked){const t=e.holder&&e.holder.pid;return"another drain is already running"+(t?` (pid ${t})`:"")}if(!1===e.ok)return e.reason||"the drain did not run";const t=Array.isArray(e.ran)?e.ran:[];if(!t.length)return e.stopped?"stopped before the next task":"nothing pending";const n=t.filter((e=>!e.ok)),o=[`ran ${t.length} — ${t.length-n.length} done`];return n.length&&o.push(`failed #${n.map((e=>e.id)).join(", #")}`),e.stopped&&o.push("stopped"),o.join(" · ")}(t)),Ne(t)}catch(e){Le=!1,r.queueDrain&&(r.queueDrain.disabled=!1),r.queueProceed&&(r.queueProceed.disabled=!1),r.queueEnqueue&&(r.queueEnqueue.disabled=!1),r.queueStop&&(r.queueStop.hidden=!0),Ae(`drain failed: ${e&&e.message?e.message:e}`)}}}async function Te(){if(s){r.queueStop&&(r.queueStop.disabled=!0),Ae("stopping…");try{const e=await s.stop(),t=e&&e.cancelled&&e.cancelled.ok;qe=t?"stopped the running task":"stop requested",Ne(e)}catch(e){Ae(`stop failed: ${e&&e.message?e.message:e}`)}finally{r.queueStop&&(r.queueStop.disabled=!1)}}}async function Re(e,t){if(s){Ae(`${e} #${t}…`);try{const n=await s[e](t);n&&!1===n.ok?Ae(n.reason||`${e} failed`):Ae(`${"retry"===e?"re-queued":"removed"} #${t}`),Ne(n)}catch(t){Ae(`${e} failed: ${t&&t.message?t.message:t}`)}}}function Ue(e){e&&"object"==typeof e&&e.drain&&function(e){if(!r.queueAuto||!e||"object"!=typeof e)return;const t=!0===e.enabled;if(r.queueAuto.checked=t,r.queueAutoInterval){r.queueAutoInterval.disabled=!t;const n=Number(e.intervalMs);Number.isFinite(n)&&(r.queueAutoInterval.value=String(n))}if(r.queueAutoLabel&&(r.queueAutoLabel.textContent=t?`drain automatically · ${function(e){const t=Number(e);if(!Number.isFinite(t)||t<=0)return"every interval";if(t<6e4)return`every ${Math.round(t/1e3)}s`;const n=t/6e4;return Number.isInteger(n)?`every ${n} min`:`every ${n.toFixed(1)} min`}(e.intervalMs)}`:"drain automatically"),!r.queueAutoHint)return;if(!t)return void(r.queueAutoHint.textContent="off — Run one / Drain all are the only triggers");const n=[];e.busy?n.push("a drain is running"):e.armed&&n.push("armed"),e.ticks&&n.push(`${e.ticks} tick${1===e.ticks?"":"s"}`),e.drains&&n.push(`${e.drains} drained`);const o=e.lastSkip&&e.lastSkip.reason;o?n.push(`last check skipped: ${function(e,t={}){if("empty"===e)return"queue is empty";if("busy"===e)return"the previous drain is still running";if("locked"===e){const e=t.holder&&t.holder.pid;return e?`another drain holds the lock (pid ${e})`:"another drain holds the lock"}return"disabled"===e?"switched off":"no queue access"===e?"this window has no queue access":String(e)}(o,e.lastSkip)}`):e.ticks||n.push("first check one interval after arming"),r.queueAutoHint.textContent=n.join(" · ")}(e.drain)}async function Oe(e){if(!a||"function"!=typeof a.setDrain)return;const t={enabled:Boolean(e)};r.queueAutoInterval&&r.queueAutoInterval.value&&(t.intervalMs=Number(r.queueAutoInterval.value));try{const e=await a.setDrain(t);e&&!1===e.ok&&r.queueAutoHint&&(r.queueAutoHint.textContent=e.error||"could not save that"),Ue(e)}catch(e){r.queueAutoHint&&(r.queueAutoHint.textContent=`could not save that: ${e&&e.message?e.message:e}`)}}function De(e){if(!e||"object"!=typeof e)return;const t=null==e.taskId?"":`#${e.taskId} `;if("start"===e.type)Ae(`${t}running${e.model?` on ${e.model}`:""}…`);else if("tool"===e.type&&e.tool)Ae(`${t}${Wt(e.tool)}`);else if("finish"===e.type)Ae(`${t}${e.ok?"done":"failed"} — refreshing`),He();else if("recovered"===e.type){const t=Array.isArray(e.ids)?e.ids:[];Ae(`recovered ${t.length} stalled task${1===t.length?"":"s"}`)}else"locked"===e.type?Ae("another drain is already running"):"queued"===e.type&&Ae(`queued phase ${e.phase}`)}function Fe(e){const t=e&&e.prompt,o=e&&e.response;if(!t||!o)return;T||(T=Jt());const s=T,a=e&&e.model||"",i=e&&e.class||"",r=i||a?[i?i.toUpperCase():"",a].filter(Boolean).join(" · "):void 0;Dt("user",t),Dt("assistant",o,r,s),R.push({role:"user",content:t}),R.push({role:"assistant",content:o}),n.append(s,{role:"user",content:t}).catch((()=>{})),n.append(s,{role:"assistant",content:o}).catch((()=>{}))}const Ke=10,Pe=6,_e=50,je={entries:[],query:"",source:"",role:"",error:"",upgrade:null,loading:!1};function Ge(){if(Qe())return!0;if(We())return!0;if(Ve&&"function"==typeof Ve.isOpen)try{return!!Ve.isOpen()}catch(e){return!1}return!1}function Qe(){return!!r.memoryOverlay&&!r.memoryOverlay.hidden}function We(){return!!r.keysOverlay&&!r.keysOverlay.hidden}let Ve=null,Ye=null,ze=!1;async function Je(e){if(!Ye)return;if(ze&&!e)return;r.ptHint&&(r.ptHint.textContent="listing providers…");const n=await async function(){let e=[];try{e=await t.listClasses()||[]}catch(e){return r.ptHint.textContent=`listClasses failed: ${e&&e.message?e.message:e}`,[]}const n=[];for(const o of e){if(!o||!o.class)continue;let e=null;try{e=await t.listModels(o.class)}catch(t){e={models:[],error:t&&t.message||String(t)}}n.push({class:o.class,classLabel:o.label,classConfigured:Boolean(o.configured),list:e})}return n}();ze=!0,Ye.set(n)}function Xe(e){e&&e.class&&Array.from(r.classSelect.options).some((t=>t.value===e.class))&&(r.classSelect.value=e.class,localStorage.setItem(l,e.class),se(e.class),Zt(e.class).then((()=>{e.model&&Array.from(r.modelSelect.options).some((t=>t.value===e.model))&&(r.modelSelect.value=e.model,r.modelSelect.dispatchEvent(new Event("change")))})))}const Ze="aegis.companion.dismissed";function et(){const e={keyConfigured:null===le?void 0:le};return Array.isArray(je.entries)&&je.entries.length&&(e.memoryCount=je.entries.length),ue&&"downloaded"===ue.status&&ue.version&&(e.updatePending=String(ue.version)),U.length&&r.modelSelect&&r.modelSelect.options.length>1&&(e.modelCount=r.modelSelect.options.length),e}function tt(){if(!window.aegisCompanion||!r.companionCard||!r.companionText)return;const e=new Date;let t=null;try{t=JSON.parse(localStorage.getItem(Ze)||"null")}catch{t=null}if(window.aegisCompanion.dismissedToday(t,e))return void(r.companionCard.hidden=!0);const n=window.aegisCompanion.pickMessage(et(),e);n&&n.text?(r.companionText.textContent=n.text,r.companionCard.dataset.kind=n.kind,r.companionCard.dataset.messageId=n.id,r.companionCard.hidden=!1):r.companionCard.hidden=!0}function nt(e){if(!Number.isFinite(e))return"";const t=Math.round((Date.now()-e)/1e3);if(t<45)return"just now";const n=Math.round(t/60);if(n<60)return`${n}m ago`;const o=Math.round(n/60);if(o<24)return`${o}h ago`;const s=Math.round(o/24);if(s<30)return`${s}d ago`;const a=Math.round(s/30);return a<12?`${a}mo ago`:`${Math.round(a/12)}y ago`}function ot(e){const t=e&&"object"==typeof e?e:{},n=e=>Array.isArray(e)?e.filter((e=>null!=e&&""!==e)):[],o=e=>"string"==typeof e?e:"",s=e=>Number.isFinite(Number(e))?Number(e):null,a=o(t.content)||o(t.text)||o(t.entry);return{id:null!=t.id?String(t.id):"",content:a,source:o(t.source)||"(unknown source)",role:o(t.role),tags:n(t.tags),entities:n(t.entities),session:o(t.session),sentiment:o(t.sentiment),importance:s(t.importance),tokenCount:s(t.tokenCount),summary:!0===t.summary,createdAt:s(t.createdAt),timestamp:o(t.timestamp)}}async function st(t,n){try{const o=t?await e.memorySearch(t,n):await e.memoryList(n),s=o&&(o.entries||o.results),a=Array.isArray(s)?s.map(ot):[];return o&&o.upgrade?{entries:a,error:"",upgrade:o.upgrade}:{entries:a,error:"",upgrade:null}}catch(e){const t=e&&e.status,n=e&&e.data&&e.data.error;return 402===t||"free_session_limit_reached"===n?{entries:[],error:"",upgrade:{url:e.data&&e.data.upgradeUrl||E("memory_quota"),used:e.data&&(null!=e.data.tokensUsed?e.data.tokensUsed:e.data.sessionsUsed),limit:e.data&&(null!=e.data.tokenLimit?e.data.tokenLimit:e.data.freeSessionLimit)}}:{entries:[],error:`search failed: ${e&&e.message?e.message:e}`,upgrade:null}}}function at(e){if(null==e||isNaN(e))return"?";const t=Number(e);return t>=1e6?`${(t/1e6).toFixed(t%1e6==0?0:1)}M`:t>=1e4?`${Math.round(t/1e3)}k`:t.toLocaleString("en-US")}function it(e,t,n,o,s){if(!e)return;const a=null!=t.used?at(t.used):"?",i=null!=t.limit?at(t.limit):"?";e.textContent=`${n||"sync limit reached"} — ${a} of ${i} tokens synced. Nothing was lost. ${b} `,H(e,t.url,s||"memory_quota",o||"See what Pro covers →")}function rt(e,t){it(r.memoryHint,e,t)}async function lt(e){r.memoryHint.textContent="searching…";const t=await st(e,Ke);(function(e,t,n,o=!1){r.memoryResults.innerHTML="";const s=Array.isArray(e)?e:[],a=function(e,t,n,o){return!o||!(!t&&!n)||e.some((e=>function(e){return e&&null!=e.importance?e.importance:5}(e)>=Pe))}(s,t,n,o),i=!!o&&!t&&!n&&s.length>0&&!a;if(function(e){const t=!!e.hasAny,n=!!e.hasBox,o=!!e.quietNotice;r.tabMemory&&(r.tabMemory.hidden=!(t||n||o)),r.memoryBox&&(r.memoryBox.hidden=!n),r.memoryQuiet&&(r.memoryQuiet.hidden=!o),r.tabMemory&&r.tabMemory.hidden&&"memory"===mn&&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",r.memoryResults.appendChild(e),void H(e,n.url,"memory_quota","Free plan limit reached — see what Pro covers →")}if(t){const e=document.createElement("li");return e.className="empty",e.textContent=t,void r.memoryResults.appendChild(e)}if(!s.length){const e=document.createElement("li");return e.className="empty",e.textContent="no memory entries",void r.memoryResults.appendChild(e)}for(const e of s){const t=document.createElement("li"),n=document.createElement("span");n.className="mem-side-src",n.textContent=e.source;const o=document.createElement("span");o.className="mem-side-body",o.textContent=e.content||"(empty)",t.appendChild(n),t.appendChild(o),r.memoryResults.appendChild(t)}}})(t.entries,t.error,t.upgrade,""===e),t.upgrade?rt(t.upgrade,"cloud memory needs an active plan"):r.memoryHint.textContent=t.error||""}function ct(e,t){const n=document.createElement("span");return n.className="mem-chip"+(t?` ${t}`:""),n.textContent=e,n}function dt(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=nt(e.createdAt);a?s.push(a):e.timestamp&&s.push(e.timestamp),e.session&&s.push(`session ${e.session}`),null!=e.tokenCount&&s.push(`${e.tokenCount} tokens`),o.textContent=s.join(" · "),n.appendChild(o),t.appendChild(n);const i=document.createElement("p");i.className="mem-card-body",i.textContent=e.content||"(empty)",t.appendChild(i);const r=[...e.tags,...e.entities];if(r.length){const e=document.createElement("div");e.className="mem-card-pills";for(const t of r)e.appendChild(ct(t,"pill"));t.appendChild(e)}return i.addEventListener("click",(()=>{window.getSelection&&String(window.getSelection())||t.classList.toggle("expanded")})),t}function ut(e){const t=new Map;for(const n of je.entries){const o=n[e];o&&t.set(o,(t.get(o)||0)+1)}return[...t.entries()].sort(((e,t)=>t[1]-e[1]))}function mt(){if(!Qe())return;const e=je.entries.length;if(r.memoryList.innerHTML="",function(){if(r.memoryChips.innerHTML="",je.upgrade||je.error)return;const e=[["source","source",ut("source")],["role","role",ut("role")]];for(const[t,n,o]of e){if(o.length<2)continue;const e=document.createElement("div");e.className="mem-chip-group";const s=document.createElement("span");s.className="mem-chip-label",s.textContent=n,e.appendChild(s);for(const[n,s]of o){const o=document.createElement("button");o.type="button",o.className="mem-chip btn"+(je[t]===n?" on":""),o.textContent=`${n} ${s}`,o.addEventListener("click",(()=>{je[t]=je[t]===n?"":n,mt()})),e.appendChild(o)}r.memoryChips.appendChild(e)}}(),je.loading)return void(r.memoryCount.textContent="loading…");if(je.upgrade){r.memoryCount.textContent="";const e=document.createElement("li");e.className="mem-empty mem-upgrade";const t=document.createElement("strong");t.textContent="Cloud memory is paused on the free plan";const n=document.createElement("span"),o=null!=je.upgrade.used?at(je.upgrade.used):"?",s=null!=je.upgrade.limit?at(je.upgrade.limit):"?";return n.textContent=`This account has used ${o} of ${s} tokens of synced conversation. Saved memory is still readable — only new saves are paused until there is room again. `+b,e.appendChild(t),e.appendChild(n),r.memoryList.appendChild(e),void H(e,je.upgrade.url,"memory_quota","Open subscribe page ↗")}if(je.error){r.memoryCount.textContent="";const e=document.createElement("li");return e.className="mem-empty",e.textContent=je.error,void r.memoryList.appendChild(e)}if(!e){r.memoryCount.textContent="0 entries";const e=document.createElement("li");return e.className="mem-empty",e.textContent="No memory entries yet — save a note below, or import from other AI tools.",void r.memoryList.appendChild(e)}const t=je.query.trim().toLowerCase(),n=je.entries.filter((e=>(!je.source||e.source===je.source)&&(!je.role||e.role===je.role)&&(!t||function(e,t){return[e.content,e.source,e.role,e.session,e.sentiment,...e.tags,...e.entities].join("\n").toLowerCase().includes(String(null==t?"":t).toLowerCase())}(e,t)))),o=new Set(je.entries.map((e=>e.source))).size;if(r.memoryCount.textContent=`${n.length} of ${e} shown · ${o} source${1===o?"":"s"}`+(e>=_e?` · newest ${_e}`:""),!n.length){const e=document.createElement("li");return e.className="mem-empty",e.textContent="Nothing matches those filters.",void r.memoryList.appendChild(e)}for(const e of n)r.memoryList.appendChild(dt(e))}async function pt(e){je.loading=!0,je.error="",je.upgrade=null,mt();const t=await st(e,_e);je.entries=t.entries,je.error=t.error,je.upgrade=t.upgrade,je.loading=!1,mt()}function yt(){r.memoryOverlay&&(r.memoryOverlay.hidden=!1,document.body.classList.add("memory-open"),r.memoryOverlayQuery.value=r.memoryQuery?r.memoryQuery.value.trim():"",je.query=r.memoryOverlayQuery.value,je.source="",je.role="",mt(),pt(je.query),r.memoryOverlayQuery&&r.memoryOverlayQuery.focus())}function ht(){r.memoryOverlay&&(r.memoryOverlay.hidden=!0,document.body.classList.remove("memory-open"),r.memoryOpen&&r.memoryOpen.focus())}async function ft(){if(e.memoryImport){r.memoryImportBtn.disabled=!0,r.memoryHint.textContent="scanning for other AI tool memory…";try{const t=await e.memoryImport({confirm:!1});if(!t||!t.totals||!t.totals.entries)return void(r.memoryHint.textContent=t&&t.summary?t.summary:"nothing found.");const n=(t.sources||[]).filter((e=>e.present&&e.count>0)).map((e=>`${e.label}: ${e.count}`)).join(" · ");r.memoryHint.textContent=`importing ${t.totals.entries} entries — ${n}`;const o=await e.memoryImport({confirm:!0,limit:1e3});if(o&&o.upgrade)return rt(o.upgrade,`import stopped after ${o.saved||0} entries`),void await vt();const s=o&&o.queued?` (${o.queued} queued offline)`:"";r.memoryHint.textContent=o&&o.ok?`imported ${o.saved} entries${s}.`:`import stopped: ${o&&o.reason||"unknown error"}`,await vt()}catch(e){r.memoryHint.textContent=`import failed: ${e&&e.message?e.message:e}`}finally{r.memoryImportBtn.disabled=!1}}}async function gt(){const t=Qe()&&r.memoryOverlayEntry?r.memoryOverlayEntry:r.memoryEntry;if(!t)return;const n=t.value.trim();if(n){r.memorySaveBtn.disabled=!0,r.memoryOverlaySave&&(r.memoryOverlaySave.disabled=!0),r.memoryHint.textContent="saving…";try{const o=await e.memorySave({text:n,source:"aegis-desktop"});if(o&&o.upgrade)return rt(o.upgrade,"free plan limit reached"),void await vt();t.value="",r.memoryHint.textContent=o&&o.queued?"saved offline — syncs when AEGIS is reachable.":"saved.",await vt()}catch(e){r.memoryHint.textContent=`save failed: ${e&&e.message?e.message:e}`}finally{r.memorySaveBtn.disabled=!1,r.memoryOverlaySave&&(r.memoryOverlaySave.disabled=!1)}}}async function vt(){const e=r.memoryQuery?r.memoryQuery.value.trim():"";await lt(e),Qe()&&await pt(je.query)}function kt(){const e=et();return void 0===e.keyConfigured&&delete e.keyConfigured,e}function Ct(){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(kt(),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 bt="aegis.welcomeAiLine",wt=120,xt=200;function St(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 Et(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 $t(){const e=document.getElementById("welcome-template");if(!e)return;r.messages.innerHTML="",r.messages.appendChild(e.content.cloneNode(!0)),function(){const e=document.getElementById("chat-greeting");if(!e)return;const t=(new Date).getHours();e.textContent=t>=5&&t<12?"Good morning":t>=12&&t<17?"Good afternoon":t>=17&&t<22?"Good evening":"Working late?"}(),Ct(),async function(){const e=document.getElementById("welcome-personal");if(!e)return;if(void 0===t||!t||"function"!=typeof t.chat)return;if(!(!0===le||r.modelSelect&&r.modelSelect.options&&r.modelSelect.options.length>1))return;const n=new Date,o=function(e){let t=null;try{t=JSON.parse(localStorage.getItem(bt)||"null")}catch{t=null}return t&&"string"==typeof t.text&&t.text?t.day!==St(e)?null:t.text:null}(n);if(o)return e.textContent=o,e.dataset.kind="ai",void(e.hidden=!1);const s=kt(),a=r.classSelect&&r.classSelect.value?r.classSelect.value:"aegis",i=r.modelSelect&&r.modelSelect.value?r.modelSelect.value:"",l={class:a,prompt:Et(s),maxTokens:wt,tools:!1,singlePass:!0,effort:"low",bestEffort:!0};i&&(l.model=i);let c=null;try{c=await t.chat(l)}catch{return}const d=c&&c.choices&&c.choices[0]||{},u=function(e){let t,n=String(null==e?"":e).trim();if(!n)return"";n=n.replace(/^(assistant|greeting|response)\s*:\s*/i,"");do{t=n,n=n.replace(/^(?:sure|certainly|of course|absolutely|okay|ok|got it|no problem|here(?:'s| is)\b[^.!?:]*)\s*[.!?:,—–-]\s*/i,"")}while(n!==t&&n);const o=n.match(/^["'“”'']([\s\S]+)["'“”'']$/);o&&(n=o[1].trim()),n=n.replace(/\s+/g," ");const s=n.match(/^[\s\S]*?[.!?](?=\s|$)/);if(s&&(n=s[0].trim()),n.length>xt){const e=n.slice(0,xt),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(bt,JSON.stringify({day:St(n),text:u}))}catch{}}}();const n=document.getElementById("welcome-byok");n&&n.addEventListener("click",Mt);const o=document.getElementById("welcome-cloud");o&&o.addEventListener("click",Nt);const s=document.getElementById("welcome-dismiss");s&&s.addEventListener("click",It),qt()}function qt(){const e=document.getElementById("welcome-connect");if(!e)return;let t=!1;try{t="on"===localStorage.getItem(y)}catch{}const n=!0!==le,o=!0!==ce;e.hidden=t||!n&&!o,Lt("welcome-cloud",!n),Lt("welcome-cloud-note",!n),Lt("welcome-byok",!o),Lt("welcome-byok-note",!o)}function Lt(e,t){const n=document.getElementById(e);n&&(n.hidden=t)}function At(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 Mt(){if(Ht("byok"),Array.from(r.classSelect.options).some((e=>"byok"===e.value))&&"byok"!==r.classSelect.value&&(r.classSelect.value="byok",r.classSelect.dispatchEvent(new Event("change"))),At(r.settingsList),!1===le&&r.apiKeyHint&&(r.apiKeyHint.textContent="BYOK needs an AEGIS key too — the handling fee is billed to it. Paste one above, then add your provider key below."),!1===le&&r.apiKeyInput)return r.apiKeyInput.focus(),void At(r.apiKeyInput);const e=r.settingsList?r.settingsList.querySelector('.setting-row input[type="password"]'):null;e&&e.focus()}function Nt(){Ht("cloud"),At(r.apiKeyInput),r.apiKeyInput&&r.apiKeyInput.focus()}function Ht(e){const t=r.apiKeyHint;if(!t)return;t.textContent="","byok"===e?t.appendChild(document.createTextNode("Bring your own key: everything on this machine stays free, and a local model server needs no account at all. A key relayed through AEGIS is a cloud turn, so it bills a small handling fee — paste the AEGIS key here, then add the provider key in Provider settings. No key yet? ")):t.appendChild(document.createTextNode(`Connect AEGIS Cloud: ${b} Paste your AEGIS key, then Save. Free key at `));const n=document.createElement("a");n.href=C,n.target="_blank",n.rel="noreferrer noopener",n.textContent="aegiscloud.org",t.appendChild(n),t.appendChild(document.createTextNode("."))}function It(){try{localStorage.setItem(y,"on")}catch{}const e=document.getElementById("welcome-connect");e&&(e.hidden=!0)}const Bt="aegis.keysPopupDismissed";function Tt(){const e=!0===le,t=!0===ce;r.keysAegisState&&(r.keysAegisState.textContent=e?"set":"not set"),r.keysByokState&&(r.keysByokState.textContent=t?"set":"not set"),r.keysRowAegis&&r.keysRowAegis.classList.toggle("set",e),r.keysRowByok&&r.keysRowByok.classList.toggle("set",t),r.keysCount&&(r.keysCount.textContent=(e?1:0)+(t?1:0)+" / 2"),r.keysAccount&&(r.keysAccount.hidden=!ye,r.keysAccount.textContent=ye?`The AEGIS account key could not be set up: ${ye}.`:""),r.keysAccountRetry&&(r.keysAccountRetry.hidden=!ye),r.keysHint&&(r.keysHint.textContent=e&&t?"Both keys are on this machine — both surfaces run.":`Missing: ${[e?null:"the AEGIS key",t?null:"your provider (BYOK) key"].filter(Boolean).join(" and ")}. Add it above, then both AEGIS Desktop and the aegiscode CLI run.`)}function Rt(){r.keysOverlay&&(r.keysOverlay.hidden=!0,document.body.classList.remove("keys-open"))}function Ut(){try{localStorage.setItem(Bt,"on")}catch{}Rt()}function Ot(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 Dt(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",Ot(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=Wt(t),e.appendChild(n)}a.appendChild(e)}if(a.appendChild(i),n){const e=document.createElement("div");e.className="meta",e.textContent=n,a.appendChild(e)}if("assistant"===e&&o){const e=document.createElement("button");e.type="button",e.className="copy-btn",e.textContent="copy",e.addEventListener("click",(()=>async function(e,t){try{await navigator.clipboard.writeText(e),t&&(t.textContent="copied!")}catch(e){t&&(t.textContent="copy failed")}finally{t&&setTimeout((()=>{t.textContent="copy"}),1500)}}(t,e))),a.appendChild(e)}return r.messages.appendChild(a),X(),a}function Ft(e,n,o){const s=document.createElement("article");s.className="flow-card pending",s.dataset.path=e.key;const a=document.createElement("div");a.className="flow-head";const i=document.createElement("span");i.className="flow-badge",i.textContent=e.badge;const r=document.createElement("span");r.className="flow-title",r.textContent=e.title;const l=document.createElement("span");l.className="flow-state",l.textContent="queued",a.appendChild(i),a.appendChild(r),a.appendChild(l);const c=document.createElement("div");c.className="flow-body",c.textContent="…";const d=document.createElement("div");d.className="flow-meta";const u=document.createElement("button");u.type="button",u.className="ghost-btn flow-abort",u.textContent="stop",u.addEventListener("click",(()=>{s.dataset.session&&t.cancel(s.dataset.session),l.textContent="stopped",s.classList.remove("pending"),s.classList.add("stopped"),u.remove()})),s.appendChild(a),s.appendChild(c),s.appendChild(d),s.appendChild(u);const m=n.querySelector(".flow-add");return m?n.insertBefore(s,m):n.appendChild(s),async function(e,n){const o=`${n.parentSessionId}::flow${++G}`;e.dataset.session=o,Q.add(o);const s=e.querySelector(".flow-body"),a=e.querySelector(".flow-state"),i=e.querySelector(".flow-meta");let r="";const l=t=>{if(t&&t.approval)return e.classList.contains("pending")&&(e.classList.remove("pending"),a.textContent="needs approval"),void zt(e,t.approval,".flow-body");if(t&&t.tool)return e.classList.contains("pending")&&(e.classList.remove("pending"),a.textContent="streaming…"),"run"===t.tool.phase?void Qt(t.tool):void Vt(e,t.tool,"flow-tools",".flow-body");const n=t&&("string"==typeof t.delta?t.delta:t.content);n&&(e.classList.contains("pending")&&(e.classList.remove("pending"),a.textContent="streaming…"),r+=n,s.textContent=r,function(e){return e.parentElement}(e)&&function(e){const t=e.nextElementSibling;return!t||t.classList.contains("flow-add")}(e)&&e.scrollIntoView({block:"nearest",inline:"end"}))};try{const c=await t.chat({class:n.cls,system:`${_}\n\n${n.path.hint}`,prompt:`Original request:\n${n.prompt}\n\n${n.path.hint}`,model:n.model,maxTokens:Math.min(n.maxTokens||1024,1024),tools:!1,singlePass:!0,sessionId:o,bestEffort:!0},l),d=c&&c.choices&&c.choices[0]||{};if(c&&c.bestEffortFailed)throw new Error(c.message||"the provider did not answer");if(c&&c.aborted){const e=new Error(c.message||"This operation was aborted");throw e.name="AbortError",e.code="ABORT_ERR",e}const u=d.message&&d.message.content||r||"(no path found)";Ot(s,"assistant",u),e.classList.remove("pending"),e.classList.add("done"),a.textContent="done";const m=[n.path.title];c&&c.model?m.push(c.model):n.model&&m.push(n.model);const p=turnAccounting(c&&c.usage,n.model,{costUsd:c&&"number"==typeof c.costUsd?c.costUsd:void 0}),y=displayTokens(p);null!=y&&m.push(`${y} tokens`),null!=p.cost&&m.push(fmtCost(p.cost,p.real));const h=F(n.parentSessionId,c&&c.usage,{model:n.model,costUsd:c&&"number"==typeof c.costUsd?c.costUsd:void 0,calls:c&&c.calls,turns:0,prompt:`Original request:\n${n.prompt}\n\n${n.path.hint}`,reply:u}),f=fmtRoll(h);f&&m.push(`session: ${f}`),i.textContent=m.join(" · ")}catch(t){const o=t&&t.message?t.message:String(t);e.classList.remove("pending"),e.classList.add("stopped"),a.textContent="stopped",s.textContent=r||`Path unavailable: ${o}`,i.textContent=n.path.title}finally{Q.delete(o);const t=e.querySelector(".flow-abort");t&&t.remove()}}(s,{...o,path:e}),s}function Kt(){return I||(I=Dt("assistant",""),I.classList.remove("pending"),I)}function Pt(e,{cancellable:t}={}){if(r.send.disabled=e,r.prompt.disabled=e,e){I=Dt("assistant",""),I.classList.add("pending");const e=document.createElement("span");e.className="typing-dots";for(let t=0;t<3;t++)e.appendChild(document.createElement("span"));I.querySelector(".body").appendChild(e);const n=document.createElement("span");if(n.className="typing-tokens",n.hidden=!0,I.appendChild(n),t){const e=document.createElement("button");e.type="button",e.className="cancel-btn",e.textContent="cancel",e.addEventListener("click",(()=>ee())),I.appendChild(e)}}else I&&(I.remove(),I=null)}const _t=72,jt=new Set(["editFile","writeFile","Edit","Write","MultiEdit"]),Gt=new Map;function Qt(e){if(!e||!jt.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&&Gt.set(e.id,n)}function Wt(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>_t?`${i.slice(0,_t-1)}…`:i;return`→ ${t}${r?` ${r}`:""} ${o}`}function Vt(e,t,n,o){if(!e)return;let s=e.querySelector(`.${n}`);if(!s){s=document.createElement("div"),s.className=n;const t=o?e.querySelector(o):null;t?e.insertBefore(s,t):e.appendChild(s)}const a=t&&null!=t.id?Gt.get(t.id):null;if(a){Gt.delete(t.id);const e=renderDiffBlock(a,document);if(e)return s.appendChild(e),s}const i=document.createElement("div");return i.textContent=Wt(t),s.appendChild(i),s}function Yt(e){return e.startsWith("@@")?"diff-hunk":e.startsWith("+++")||e.startsWith("---")?"diff-file":e.startsWith("+")?"diff-add":e.startsWith("-")?"diff-del":"diff-ctx"}function zt(e,n,o){if(!e||!n)return;const s=document.createElement("div");s.className="approval-card",s.dataset.approvalId=n.id;const a=document.createElement("div");a.className="approval-title",a.textContent=`${n.tool} wants to run — review before it executes`,s.appendChild(a);const i=function(e,t){const n=t||{};return"exec"===e?n.description?`${n.command} — ${n.description}`:n.command||"":n.file_path||""}(n.tool,n.args);if(i){const e=document.createElement("div");e.className="approval-summary",e.textContent=i,s.appendChild(e)}if(n.diff){const e=document.createElement("pre");e.className="approval-diff";for(const t of n.diff.split("\n")){const n=document.createElement("div");n.className=Yt(t),n.textContent=t,e.appendChild(n)}s.appendChild(e)}const r=document.createElement("div");r.className="approval-actions";const l=(e,o,a)=>{const i=document.createElement("button");return i.type="button",i.className=`approval-btn ${o}`,i.textContent=e,i.addEventListener("click",(()=>(e=>{for(const e of r.querySelectorAll("button"))e.disabled=!0;s.classList.add("resolved");const o=document.createElement("div");o.className="approval-decision",o.textContent="deny"===e?"Denied":"session"===e?"Allowed for this session":"Allowed once",s.appendChild(o),t.respondApproval(n.id,e)})(a))),i};r.appendChild(l("Allow once","allow","once")),r.appendChild(l("Allow for this session","allow-session","session")),r.appendChild(l("Deny","deny","deny")),s.appendChild(r);let c=e.querySelector(".approval-slot");if(!c){c=document.createElement("div"),c.className="approval-slot";const t=o?e.querySelector(o):null;t?e.insertBefore(c,t):e.appendChild(c)}return c.appendChild(s),s}function Jt(){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 Xt(){try{U=await t.listClasses()||[]}catch(e){U=[],r.modelHint.textContent=`listClasses failed: ${e&&e.message?e.message:e}`}r.classSelect.innerHTML="";for(const e of U){const t=document.createElement("option");t.value=e.class,t.textContent=e.configured?e.label:`${e.label} (not configured)`,r.classSelect.appendChild(t)}const e=localStorage.getItem(l);e&&U.some((t=>t.class===e))&&(r.classSelect.value=e),await Zt(r.classSelect.value)}async function Zt(e){if(r.autonomousToggleWrap&&(r.autonomousToggleWrap.hidden=e!==h),ne(),se(e),r.modelSelect.hidden=!1,r.modelSelect.disabled=!1,r.modelFree.hidden=!0,r.modelFree.value="",r.modelHint.textContent="",r.modelSelect.innerHTML="",O=new Map,"aegis"===e){const e=document.createElement("option");e.value="",e.textContent="server default (auto)",r.modelSelect.appendChild(e)}try{const n=await t.listModels(e),o=Array.isArray(n&&n.models)?n.models:[],s=Boolean(n&&n.needsKey),a=Boolean(n&&n.needsDaemon),i=!(n&&!1===n.listed),l=Boolean(n&&n.providersFailed),c=Array.isArray(n&&n.unmatchedProviders)?n.unmatchedProviders:[];r.modelFree.hidden=!("local"===e&&(a||!i));for(const e of o){O.set(e.id,e);const t=document.createElement("option");t.value=e.id,t.textContent=e.label||e.id,r.modelSelect.appendChild(t)}let d;if(ae(),s)d=null;else if(a)d=`No local model server at ${n&&n.baseURL||"the configured address"} — start Ollama, or set Base URL below to llama.cpp / LM Studio, then Refresh.`;else if("local"!==e||i)if("byok"===e&&l)d="Provider catalog unreachable — your saved keys and declared models are unaffected. Refresh to try again."+(n&&n.providersError?` (${n.providersError})`:"");else if(o.length)if("byok"===e&&n&&n.needsAegisKey){const e=n&&n.fee||null;d=`${o.length} model${1===o.length?"":"s"} available — `+(e&&e.require_balance?"an AEGIS account key and a funded balance are required: the BYOK handling fee is billed there.":"an AEGIS account key is required: the BYOK handling fee is billed there.")}else d="byok"===e&&n&&n.needsProviderKey?`${o.length} model${1===o.length?"":"s"} available — add a provider key in Provider settings below to use one.`:`${o.length} model${1===o.length?"":"s"} available.`;else d="local"===e?"No models on this server yet — pull one first (ollama pull llama3.2).":"aegis"===e?"No models to pin — this class runs the pooled route on the server's own default. Use Bring your own key for a per-provider model.":"No models listed.";else d="That address answered but listed no models — not Ollama? Type the model tag in the box above and send.";"byok"===e&&!l&&c.length&&(d=`${d} Not shown: ${c.join(", ")} — declared in models.json, but not in the provider catalog. Check the provider name in Settings.`);const u=maxTokensCeiling(O.get(oe()));if(s){r.modelHint.textContent="Connect Aegis Cloud to load its models: paste your AEGIS API key in the Status card above (";const e=document.createElement("a");return e.href=C,e.target="_blank",e.rel="noreferrer noopener",e.textContent="free key at aegiscloud.org",r.modelHint.appendChild(e),void r.modelHint.appendChild(document.createTextNode("), then Save."))}r.modelHint.textContent=u<FLAT_CEILING?`${d} · max output: ${u.toLocaleString()}`:d}catch(e){O=new Map,r.modelHint.textContent=`listModels failed: ${e&&e.message?e.message:e}`,ae()}}function en(){if(r.queueModelInput&&!r.queueModelInput.hidden){const e=r.queueModelInput.value.trim();if(e)return e}return r.queueModelSelect?r.queueModelSelect.value:""}async function tn(e){if(r.queueModelSelect){if(function(e){const t=r.queueFanout&&r.queueFanout.closest("label");t&&(t.hidden="aegis"!==e)}(e),r.queueModelSelect.hidden=!1,r.queueModelSelect.disabled=!1,r.queueModelInput&&(r.queueModelInput.hidden=!0,r.queueModelInput.value=""),r.queueModelHint&&(r.queueModelHint.textContent=""),r.queueModelSelect.innerHTML="","aegis"===e){const e=document.createElement("option");e.value="",e.textContent="server default (auto)",r.queueModelSelect.appendChild(e)}try{const n=await t.listModels(e),o=Array.isArray(n&&n.models)?n.models:[],s=Boolean(n&&n.needsKey),a=Boolean(n&&n.needsDaemon),i=!(n&&!1===n.listed);r.queueModelInput&&(r.queueModelInput.hidden=!("local"===e&&(a||!i)));for(const e of o){const t=document.createElement("option");t.value=e.id,t.textContent=e.label||e.id,r.queueModelSelect.appendChild(t)}if(!r.queueModelHint)return;s?r.queueModelHint.textContent="Connect this class in the Model card above (API key / provider key), then Refresh.":a?r.queueModelHint.textContent=`No local model server at ${n&&n.baseURL||"the configured address"} — start it, then reopen this picker.`:"local"!==e||i?o.length?"byok"===e&&n&&n.needsProviderKey&&(r.queueModelHint.textContent="A provider key is required before a queued task on this model can run — add one in the Model card above."):r.queueModelHint.textContent="local"===e?"No models on this server yet — pull one first (ollama pull llama3.2).":"aegis"===e?"No models to pin — this runs the pooled route on the server's own default.":"No models listed.":r.queueModelHint.textContent="That address answered but listed no models — type the model tag above."}catch(e){r.queueModelHint&&(r.queueModelHint.textContent=`listModels failed: ${e&&e.message?e.message:e}`)}}}function 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 on(e){r.settingsHint.textContent="saving…";try{const n=String(null==e?"":e).trim()||k,o=await t.settings.set(g,{baseURL:n}),s=o&&o.baseURL||n;r.settingsHint.textContent=`saved: local model server at ${s}`,await sn(),await Zt(r.classSelect.value)}catch(e){r.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function sn(){r.settingsList.innerHTML="";const e=[];let n=[];try{n=await t.settings.get()||[]}catch{}Array.isArray(n)&&(n=n.filter((e=>e&&!f.has(e.provider))));{const e=n.find((e=>e&&e.provider===g))||{provider:g,baseURL:"",configured:!1,keyMask:null};r.settingsList.appendChild(function(e){const t=g,n=document.createElement("div");n.className="setting-row",n.dataset.provider=t;const o=document.createElement("div");o.className="setting-name",o.textContent="Local model server",n.appendChild(o);const s=document.createElement("input");s.type="text",s.className="setting-input",s.id="local-base-url",s.autocomplete="off",s.spellcheck=!1,s.placeholder=k,s.value=e.baseURL||"",s.addEventListener("keydown",(e=>{"Enter"===e.key&&on(s.value)})),n.appendChild(s);const a=document.createElement("div");a.className="setting-status",a.textContent=e.baseURL?e.baseURL:`default (${k})`,n.appendChild(a);const i=document.createElement("div");i.className="setting-actions";const r=document.createElement("button");r.type="button",r.className="ghost-btn",r.textContent="Save",r.addEventListener("click",(()=>on(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",(()=>dn(t))),i.appendChild(l),n.appendChild(i),n}(e))}try{const o=await t.listModels("byok"),s=Array.isArray(o&&o.providers)?o.providers:[];for(const t of s){if(!t||!t.id)continue;if(e.push({id:t.id,label:t.label||t.id}),t.id===v)continue;const o=`byok:${t.id}`,s=n.find((e=>e.provider===o))||{provider:o,baseURL:"",configured:!1,keyMask:null};r.settingsList.appendChild(nn({provider:o,name:`BYOK: ${t.label||t.id}`,cfg:s,onSave:e=>cn(o,e),onRemove:()=>dn(o)}))}const a=o&&o.fee;if(a&&!a.disabled&&(Number(a.in_usd_per_1k)>0||Number(a.out_usd_per_1k)>0)){const e=document.createElement("div");e.className="setting-row",e.id="byok-fee-note";const t=document.createElement("div");t.className="setting-name";const n=e=>`${Number(e).toFixed(4)}`;t.textContent=`BYOK handling fee: ${n(a.in_usd_per_1k)} / 1k in, ${n(a.out_usd_per_1k)} / 1k out — billed to your AEGIS account on top of your own provider bill. This is the published rate, not a personal quote — Unlimited subscribers pay no handling fee at all, and neither do users on the free 1-month Unlimited trial.`,e.appendChild(t),r.settingsList.appendChild(e)}}catch{}try{await async function(e){if(!r.settingsList||!t.userModels)return;const n=await t.userModels.get();if(!n)return;const o=n&&n.map||{},s=(e||[]).map((e=>e&&e.id||"")).filter(Boolean),a=document.createElement("div");a.id="user-models-block";const i=document.createElement("div");i.className="setting-name",i.textContent="Your own models (BYOK)",a.appendChild(i);const l=document.createElement("div");l.className="setting-row",l.dataset.provider="byok:__user-model-add";const c=document.createElement("input");if(c.type="text",c.className="setting-input",c.id="user-model-provider",c.placeholder="provider (deepseek)",c.autocomplete="off",c.spellcheck=!1,s.length){const e=document.createElement("datalist");e.id="user-model-providers";for(const t of s){const n=document.createElement("option");n.value=t,e.appendChild(n)}l.appendChild(e),c.setAttribute("list","user-model-providers")}l.appendChild(c);const d=document.createElement("input");d.type="text",d.className="setting-input",d.id="user-model-id",d.placeholder="model id (deepseek-v4.2-preview)",d.autocomplete="off",d.spellcheck=!1,l.appendChild(d);const u=document.createElement("div");u.className="setting-actions";const m=document.createElement("button");m.type="button",m.className="ghost-btn",m.id="user-model-add",m.textContent="Add model",m.addEventListener("click",(async()=>{const e=c.value.trim(),n=d.value.trim();r.settingsHint.textContent="adding…";try{const o=await t.userModels.add(e,n);r.settingsHint.textContent=o&&!1===o.added?`${o.provider}:${o.model} was already declared.`:`added ${o.provider}:${o.model} — /models and the picker now offer it.`,await sn(),await Zt(r.classSelect.value)}catch(e){r.settingsHint.textContent=`${e&&e.message?e.message:e}`}})),u.appendChild(m);const p=document.createElement("button");p.type="button",p.className="ghost-btn",p.id="user-model-discover",p.textContent="List from provider",u.appendChild(p);const y=document.createElement("div");y.className="setting-status",y.id="user-model-discovered",y.hidden=!0,p.addEventListener("click",(async()=>{const e=c.value.trim();if(!e)return void(r.settingsHint.textContent="type a provider id first (the CLI's /byok lists them).");if("function"!=typeof t.userModels.discover)return void(r.settingsHint.textContent="this build cannot ask a provider — type the model id.");let n;r.settingsHint.textContent=`asking ${e}…`,y.hidden=!0,y.textContent="";try{n=await t.userModels.discover(e)}catch(e){return void(r.settingsHint.textContent=`${e&&e.message?e.message:e}`)}if(!n||!n.ok)return void(r.settingsHint.textContent=`${e}: ${n&&n.error||"no answer"}`);r.settingsHint.textContent=`${n.provider} serves ${n.count} chat model id(s) — pick one and Add model, or add them all.`;const o=document.createElement("select");o.className="setting-input",o.id="user-model-discovered-list";for(const e of n.ids){const t=document.createElement("option");t.value=e,t.textContent=n.declared&&n.declared.includes(e)?`${e} — declared`:e,o.appendChild(t)}if(o.addEventListener("change",(()=>{d.value=o.value})),n.ids.length){d.value=n.ids[0],y.appendChild(o);const e=document.createElement("button");e.type="button",e.className="ghost-btn",e.id="user-model-add-all",e.textContent=`Add all ${n.count}`,e.addEventListener("click",(async()=>{r.settingsHint.textContent=`adding ${n.count}…`;try{const e=await t.userModels.addAll(n.provider,n.ids);r.settingsHint.textContent=`added ${e.added} of ${n.ids.length}`+(e.already&&e.already.length?` (${e.already.length} were already declared)`:"")+(e.failed&&e.failed.length?` — ${e.failed.length} refused`:"")+".",await sn(),await Zt(r.classSelect.value)}catch(e){r.settingsHint.textContent=`${e&&e.message?e.message:e}`}})),y.appendChild(e)}else y.textContent="the vendor answered with no chat models — type an id above.";if(n.others&&n.others.length){const e=document.createElement("div");e.textContent=`${n.others.length} non-chat id(s) left out: ${n.others.slice(0,6).join(", ")}`,y.appendChild(e)}y.hidden=!1})),l.appendChild(u),l.appendChild(y);const h=document.createElement("div");h.className="setting-status",h.id="user-model-hint",h.textContent=n.file?`saved in ${n.file} — the CLI reads the same file (/model-add)`:"saved beside your AEGIS config — the CLI reads the same file (/model-add)",l.appendChild(h),a.appendChild(l);const f=Object.keys(o).sort();for(const e of f)for(const n of o[e]){const o=document.createElement("div");o.className="setting-row",o.dataset.provider=`byok:${e}`;const i=document.createElement("div");i.className="setting-name",i.textContent=`${e} — ${n}`,o.appendChild(i);const l=document.createElement("div");l.className="setting-status",l.textContent=s.length&&!s.includes(e)?"no provider row for this id — /byok lists the ones the relay takes":"offered in the picker on this machine",o.appendChild(l);const c=document.createElement("div");c.className="setting-actions";const d=document.createElement("button");d.type="button",d.className="ghost-btn danger",d.textContent="Remove",d.addEventListener("click",(async()=>{r.settingsHint.textContent="removing…";try{const o=await t.userModels.remove(e,n);r.settingsHint.textContent=o&&!1===o.removed?`${e}:${n} was not declared.`:`removed ${e}:${n}.`,await sn(),await Zt(r.classSelect.value)}catch(e){r.settingsHint.textContent=`${e&&e.message?e.message:e}`}})),c.appendChild(d),o.appendChild(c),a.appendChild(o)}const g=n&&n.invalid||[];for(const e of g){const t=document.createElement("div");t.className="setting-row";const n=document.createElement("div");n.className="setting-name",n.textContent=`${e.provider||"models.json"}: ${null==e.model?"":String(e.model)}`.trim(),t.appendChild(n);const o=document.createElement("div");o.className="setting-status",o.textContent=`skipped — ${e.reason}`,t.appendChild(o),a.appendChild(t)}r.settingsList.appendChild(a)}(e)}catch(e){r.settingsHint.textContent=`your own models: ${e&&e.message?e.message:e}`}try{await an()}catch(e){r.customStatus&&(r.customStatus.textContent=`custom provider: ${e&&e.message?e.message:e}`)}}async function an(){if(!r.customBaseUrl)return;let e=null,n=[];try{const n=await t.settings.get()||[],o=(Array.isArray(n)?n:[]).find((e=>e&&e.provider===`byok:${v}`));o&&(e={baseURL:o.baseURL||"",configured:Boolean(o.configured),keyMask:o.keyMask})}catch{}try{const e=await t.userModels.get(),o=e&&e.map||{};n=Array.isArray(o[v])?o[v]:[]}catch{}!function(e,t){if(!r.customBaseUrl)return;const n=e||{},o=Array.isArray(t)?t:[];if(!r.customBaseUrl.value&&n.baseURL&&(r.customBaseUrl.value=n.baseURL),r.customKey&&(r.customKey.placeholder=n.configured?`key ${n.keyMask||"••••"} (blank = keep)`:"sk-…",r.customKey.value=""),r.customRemove&&(r.customRemove.disabled=!n.configured&&!n.baseURL),!r.customStatus)return;const s=[];n.baseURL?s.push(`endpoint ${n.baseURL}`):s.push("no endpoint saved"),s.push(n.configured?`key ${n.keyMask||"saved"}`:"no key"),s.push(o.length?`model${1===o.length?"":"s"} ${o.join(", ")}`:"no model declared"),r.customStatus.textContent=s.join(" · ")}(e,n)}async function rn(){if(!r.customBaseUrl)return;const e=String(r.customBaseUrl.value||"").trim(),n=r.customKey?String(r.customKey.value||"").trim():"",o=r.customModel?String(r.customModel.value||"").trim():"",s=e=>{r.customStatus&&(r.customStatus.textContent=e)};if(!e)return void s("an address is required — aegis1 dials the endpoint you name, and refuses a custom call that names none.");if(!/^https:\/\//i.test(e))return void s("refused: only an https:// endpoint is dialed — aegis1 rejects a plain-http or scheme-less base URL for this provider.");if(!o)return void s("a model id is required — the `custom` provider pins no default, so nothing would be selectable in the picker.");s("saving…");const a=`byok:${v}`;try{const o={};o.baseURL=e,n&&(o.key=n),await t.settings.set(a,o)}catch(e){return void s(`endpoint not saved: ${e&&e.message?e.message:e}`)}try{await t.userModels.add(v,o)}catch(e){return s(`endpoint saved, model NOT declared: ${e&&e.message?e.message:e}`),await an(),void await Zt(r.classSelect.value).catch((()=>{}))}r.customModel&&(r.customModel.value=""),s(`saved ${e} with model ${o} — pick it under provider "byok", then the model.`),await an(),await sn(),await Zt(r.classSelect.value).catch((()=>{}))}async function ln(){if(!r.customBaseUrl)return;const e=e=>{r.customStatus&&(r.customStatus.textContent=e)};e("removing…");let n=0;try{const e=await t.userModels.get(),o=e&&e.map||{},s=Array.isArray(o[v])?o[v]:[];for(const e of s)await t.userModels.remove(v,e),n+=1}catch{}try{await t.settings.remove(`byok:${v}`)}catch(t){return void e(`remove failed: ${t&&t.message?t.message:t}`)}r.customBaseUrl&&(r.customBaseUrl.value=""),e(`removed the custom endpoint${n?` and ${n} declared model(s)`:""}.`),await an(),await sn(),await Zt(r.classSelect.value).catch((()=>{}))}async function cn(e,n){r.settingsHint.textContent="saving…";try{const o={};n&&(o.key=n),await t.settings.set(e,o),r.settingsHint.textContent="saved.",await sn(),await Zt(r.classSelect.value)}catch(e){r.settingsHint.textContent=`save failed: ${e&&e.message?e.message:e}`}}async function dn(e){r.settingsHint.textContent="removing…";try{await t.settings.remove(e),r.settingsHint.textContent="removed.",await sn(),await Zt(r.classSelect.value)}catch(e){r.settingsHint.textContent=`remove failed: ${e&&e.message?e.message:e}`}}const un=["sessions","memory"];let mn="sessions";function pn(e){const t=un.includes(e)?e:"sessions";mn=t;for(const e of un){const n="sessions"===e?r.paneSessions:r.paneMemory,o="sessions"===e?r.tabSessions:r.tabMemory,s=e===t;n&&(n.hidden=!s),o&&(o.setAttribute("aria-selected",s?"true":"false"),o.classList.toggle("is-active",s))}}async function yn(){r.sessionsList.innerHTML="",r.sessionsHint.textContent="";let e=[];try{const t=await n.listSessions();e=t&&t.sessions||[]}catch(e){return void(r.sessionsHint.textContent=`list failed: ${e&&e.message?e.message:e}`)}if(!e.length){const e=document.createElement("li");return e.className="empty",e.textContent="no sessions yet",void r.sessionsList.appendChild(e)}for(const t of e){const e=document.createElement("li");e.className="session-row",e.tabIndex=0;const n=document.createElement("span");n.className="session-title",n.textContent=t&&t.title||t&&t.id||"untitled",e.appendChild(n);const o=document.createElement("span");o.className="session-meta";const s=t&&Array.isArray(t.messages)&&t.messages.length||0,a=t&&t.updatedAt?new Date(t.updatedAt).toLocaleTimeString():"";o.textContent=`${s} msg${1===s?"":"s"}${a?" · "+a:""}`,e.appendChild(o),e.addEventListener("click",(()=>kn(t.id))),r.sessionsList.appendChild(e)}}function hn(e){if(!r.syncStatus)return;if(!e)return void(r.syncStatus.textContent="");const t=[e.cloud?"cloud sync on":"cloud sync off (no key)",`${e.pending} pending`];e.lastSyncAt&&t.push(`last synced ${new Date(e.lastSyncAt).toLocaleTimeString()}`),e.retry&&e.retry.lastError&&t.push(`last sync attempt failed: ${e.retry.lastError}`),r.syncStatus.textContent=t.join(" · ")}async function fn(){try{hn(await n.status())}catch{hn(null)}}function gn(){"function"==typeof n.auto&&n.auto().then((e=>{e&&e.upgrade&&it(r.sessionsHint,e.upgrade,"queued memory is waiting on the free-plan cap","See what Pro covers →")})).catch((()=>{}))}async function vn(){r.syncNow.disabled=!0,r.sessionsHint.textContent="syncing…";try{const e=await n.push(),t=await n.pull();e.upgrade||t.upgrade?it(r.sessionsHint,e.upgrade||t.upgrade,"queued memory is waiting on the free-plan cap","See what Pro covers →"):e.ok||t.ok?r.sessionsHint.textContent=`synced (pushed ${e.pushed||0}, pulled ${t.merged||0})`:r.sessionsHint.textContent=`sync failed: ${e.reason||t.reason||"unknown error"}`}catch(e){r.sessionsHint.textContent=`sync failed: ${e&&e.message?e.message:e}`}finally{r.syncNow.disabled=!1,await fn(),await yn()}}function kn(e){n.open(e).then((e=>{if(!e)return void(r.sessionsHint.textContent="session not found");r.messages.innerHTML="";const t=Array.isArray(e.messages)?e.messages:[];t.length||$t();for(const n of t){const t="assistant"===n.role?"assistant":"system"===n.role?"system":"user";Dt(t,n.content||n.text||"",void 0,"assistant"===t?e.id:void 0)}T=e.id,D.set(e.id,rollMessages(t)),K(e.id),R=replayHistory(t),r.sessionsHint.textContent=`opened ${e.id.slice(0,8)}…`})).catch((e=>{r.sessionsHint.textContent=`open failed: ${e&&e.message?e.message:e}`}))}function Cn(t){const n=T;n?e.exportSession(n,t).then((e=>{e&&e.ok?r.sessionsHint.textContent=`exported to ${e.filePath}`:e&&e.canceled||(r.sessionsHint.textContent=`export failed: ${e&&e.reason||"unknown error"}`)})).catch((e=>{r.sessionsHint.textContent=`export failed: ${e&&e.message?e.message:e}`})):r.sessionsHint.textContent="no open session to export"}function bn(){W(),T&&t.clearApprovals(T).catch((()=>{})),$t(),r.sessionsHint.textContent="",I=null,B=null,Y=null,z=null,T=null,R=[],G=0,K(null)}function wn(e){e&&("open"===e.action&&e.sessionId?kn(e.sessionId):"new"===e.action&&(bn(),e.prompt&&(r.prompt.value=e.prompt,r.prompt.focus())))}async function xn(){const e=r.prompt.value.trim(),o=Sn.length?Sn.map((e=>({kind:e.kind,path:e.path,name:e.name,size:e.size,mime:e.mime,dataUrl:e.dataUrl,text:e.text,truncated:e.truncated}))):void 0;if(!e&&!o||r.send.disabled)return;const s=r.classSelect.value,a=oe();r.prompt.value="";const i=(l=Sn,Array.isArray(l)&&l.length?l.map((e=>`📎 ${e.name||e.path}`)).join("\n"):"");var l;const c=i?e?`${e}\n${i}`:i:e;Sn=[],En=[],Ln();const d=++V;Y=d,z=null,Dt("user",c);const u=s===h&&te(),m=ie(),p=budgetFor(a,void 0,m),y=u&&parseInt(r.autonomousWorkers.value,10)||void 0;T||(T=Jt());const f=T;B=f,Rt();const g=replayHistory(R);R.push({role:"user",content:o&&!qn()?Bn(e,o):c}),Pt(!0,{cancellable:!0}),I&&K(f,{prompt:e,reply:"",reasoning:""}),X({force:!0});try{await n.append(f,{role:"user",content:c})}catch{}let v="",k="",C=0;const b=[];let w=null;const x=(S=()=>{if(!I)return;if(I.classList.remove("pending"),k){const e=function(e){let t=e.querySelector(".reasoning");if(!t){t=document.createElement("div"),t.className="reasoning";const n=e.querySelector(".body");n?e.insertBefore(t,n):e.appendChild(t)}return t}(I);e.textContent!==k&&(e.textContent=k)}const t=I.querySelector(".body");t&&t.textContent!==v&&(t.textContent=v);const n=v.length+k.length+4*C;liveMeterDue(w,n)&&(w=n,K(f,{prompt:e,reply:v,reasoning:k,measuredReasoningTokens:C})),X()},J?J.paint(S):S);var S;const E=e=>{if(e&&"number"==typeof e.thinkingTokens&&e.thinkingTokens>0)return C+=e.thinkingTokens,void x();if(e&&"string"==typeof e.reasoning&&e.reasoning)return k+=e.reasoning,void x();if(e&&"string"==typeof e.note&&e.note){const t=Kt();return t.classList.remove("pending"),function(e,t,n){if(!e||!t)return null;const o=document.createElement("div");o.className="turn-note",o.textContent=t;const s=n?e.querySelector(n):null;s?e.insertBefore(o,s):e.appendChild(o)}(t,e.note,".body"),void X()}if(e&&e.approval){const t=Kt();return t.classList.remove("pending"),zt(t,e.approval,".body"),void X({force:!0})}if(e&&e.rounds){const n=Kt();return n.classList.remove("pending"),function(e,n,o){if(!e||!n||!n.id)return null;const s=Number(n.spent)||0,a=Number(n.size)||s,i=Number(n.extensions)||1,r=Number(n.max)||8,l=document.createElement("div");l.className="approval-card rounds-card",l.dataset.roundsAskId=n.id;const c=document.createElement("div");c.className="approval-title",c.textContent="Round limit reached — keep going?",l.appendChild(c);const d=document.createElement("div");d.className="approval-summary",d.textContent=`This turn has used all ${s} tool rounds allowed for it. ${a} more continue the SAME turn — no restart, no repeated work. Stopping holds everything done so far: your next message resumes it automatically. (${i} of ${r} extensions.)`,l.appendChild(d);const u=document.createElement("div");u.className="approval-actions";const m=(e,o,s)=>{const i=document.createElement("button");return i.type="button",i.className=`approval-btn ${o}`,i.textContent=e,i.addEventListener("click",(()=>(e=>{for(const e of u.querySelectorAll("button"))e.disabled=!0;l.classList.add("resolved");const o=document.createElement("div");o.className="approval-decision",o.textContent=e?`Continuing — ${a} more rounds`:"Stopped — the work is held",l.appendChild(o),t.respondRoundsAsk(n.id,e)})(s))),i};u.appendChild(m(`Keep going (${a} more rounds)`,"allow",!0)),u.appendChild(m("Stop here","deny",!1)),l.appendChild(u);let p=e.querySelector(".approval-slot");if(!p){p=document.createElement("div"),p.className="approval-slot";const t=o?e.querySelector(o):null;t?e.insertBefore(p,t):e.appendChild(p)}p.appendChild(l)}(n,e.rounds,".body"),void X({force:!0})}if(e&&e.tool){if("run"===e.tool.phase)return void Qt(e.tool);b.push(e.tool);const t=Kt();return t.classList.remove("pending"),Vt(t,e.tool,"tool-activity",".body"),void X()}const n=e&&("string"==typeof e.delta?e.delta:e.content);n&&(v+=n,x())};try{const i=await t.chat({class:s,prompt:e,model:a,maxTokens:p,sessionId:f,autonomous:u,effort:m,workers:y,messages:g,attachments:o,roundsAsk:!0},E);if(i&&i.aborted){const e=new Error(i.message||"This operation was aborted");throw e.name="AbortError",e.code="ABORT_ERR",e}const l=i&&i.choices&&i.choices[0]||{},c=l.message&&l.message.content||v||"(empty response)";isPlaceholderContent(c)||R.push({role:"assistant",content:c});const d=[];i&&i.model?d.push(`model: ${i.model}`):a&&d.push(`model: ${a}`),d.push(function(e){const t=U.find((t=>t.class===e));return t?t.label:e}(s)),u?d.push(`autonomous (${m}, ${y||"auto"}w)`):m&&d.push(`effort: ${m}`);const h=turnAccounting(i&&i.usage,a,{costUsd:i&&"number"==typeof i.costUsd?i.costUsd:void 0}),C=displayTokens(h);if(null!=C)d.push(`tokens: ${C}`);else{const t=estimatedBuckets(e,c,c===k?"":k);t&&t.output>0&&d.push(`~${t.output} tokens`)}const w=feeBillable(function(){const e="undefined"!=typeof state?state:null;return e&&e.entitlement?e.entitlement:null}());null!=h.cost&&w&&d.push(fmtCost(h.cost,h.real)),"byok"===s&&null!=h.cost&&w&&d.push("your provider bill (est.) + AEGIS handling fee");const x=F(f,i&&i.usage,{model:a,costUsd:i&&"number"==typeof i.costUsd?i.costUsd:void 0,calls:i&&i.calls,prompt:e,reply:c,reasoning:c===k?"":k}),S=fmtRoll(x,{omitMoney:!w});S&&d.push(`session: ${S}`),Dt("assistant",c,d.join(" · ")||void 0,f,b);try{await n.append(f,{role:"assistant",content:c,...P(i&&i.usage,a,h,{prompt:e,reply:c,reasoning:c===k?"":k,calls:i&&i.calls})}),await n.save({id:f,title:e.slice(0,60)}),"function"==typeof n.nameSession&&n.nameSession({sessionId:f,prompt:e,class:s,model:a}).then((e=>{e&&yn().catch((()=>{}))})).catch((()=>{}))}catch{}gn(),function(){const e=r.exploreToggle;return Boolean(e&&e.checked)}()&&"(empty response)"!==c&&function(e){const t=document.createElement("div");t.className="chatflow";const n=document.createElement("div");n.className="flow-rail";const o=document.createElement("span");o.className="flow-rail-label",o.textContent="discovery lane";const s=document.createElement("span");s.className="flow-rail-hint",s.textContent="alternatives from the AI — scroll →",n.appendChild(o),n.appendChild(s);const a=document.createElement("div");a.className="flow-track";const i=document.createElement("button");i.type="button",i.className="ghost-btn flow-add",i.textContent="+ another path",i.addEventListener("click",(()=>{Ft(j[G%j.length],a,e)})),a.appendChild(i),t.appendChild(n),t.appendChild(a),r.messages.appendChild(t);for(const t of j.slice(0,2))Ft(t,a,e)}({prompt:e,cls:s,model:a,maxTokens:p,parentSessionId:f})}catch(t){if(isCancellation(t,{userStopped:z===d})){const t=salvageTurn({streamedText:v,reasoningText:k}),o=t.text,s=t.reasoning,i=replayableContent(t.kind,o);R.push({role:"assistant",content:i});const r=turnAccounting(void 0,a,{}),l=F(f,void 0,{model:a,prompt:e,reply:o,reasoning:s}),c=["stopped by you"];"reasoning-only"===t.kind&&c.push("reasoning only");const d=displayTokens(r);if(null!=d)c.push(`tokens: ${d}`);else{const t=estimatedBuckets(e,o,s);t&&t.output>0&&c.push(`~${t.output} tokens`)}const u=fmtRoll(l);u&&c.push(`session: ${u}`),Dt("assistant",o,c.join(" · "),f,b);try{await n.append(f,{role:"assistant",content:i,...P(void 0,a,r,{prompt:e,reply:o,reasoning:s})})}catch{}gn()}else Dt("assistant",`Error: ${t&&t.message?t.message:t}`,"request failed")}finally{Pt(!1),Y===d&&(Y=null,B=null),yn()}}let Sn=[],En=[],$n=0;function qn(){return r.classSelect&&"pro"===r.classSelect.value}function Ln(){const e=r.attachRow,t=r.attachNote;if(!e)return;e.textContent="";const n=Sn.length+En.length;if(e.hidden=0===n,t&&(t.hidden=!0,t.textContent=""),n){for(const t of Sn){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} · ${Mn(t.size)}${t.truncated?" (truncated)":""}`,n.appendChild(s),n.appendChild(An((()=>{Sn=Sn.filter((e=>e!==t)),Ln()}))),e.appendChild(n)}for(const t of En){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(An((()=>{En=En.filter((e=>e!==t)),Ln()}))),e.appendChild(n)}if(t&&qn()){const e=Sn.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 An(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 Mn(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 Nn(t){const n=(t||"").split(/[\\/]/).pop()||t;if(Sn.length>=8)return En.push({path:t,name:n,reason:"at most 8 files per message"}),void Ln();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 En.push({path:t,name:n,reason:o&&o.reason||"not attached"}),void Ln();Sn.some((e=>e.path===o.attachment.path))||(Sn.push(o.attachment),Ln())}const Hn=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function In(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 Bn(e,t){const n=[],o="string"==typeof e?e:"";o.trim()&&n.push({type:"text",text:o});for(const e of t||[]){const t=In(e);"image"===e.kind&&e.dataUrl&&Hn.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 Tn(){try{de(await e.status())}catch{de(null)}"on"===localStorage.getItem(d)&&(r.autonomousToggle.checked=!0),r.autonomousToggle.addEventListener("change",(()=>{localStorage.setItem(d,r.autonomousToggle.checked?"on":"off"),ne()}));const n=localStorage.getItem(u)||localStorage.getItem("aegis.autonomousEffort"),i=Array.from(r.effortSelect.options).some((e=>e.value===n));n&&i?r.effortSelect.value=n:n&&localStorage.setItem(u,r.effortSelect.value),r.effortSelect.addEventListener("change",(()=>{localStorage.setItem(u,r.effortSelect.value),se(r.classSelect.value)}));const y=localStorage.getItem(m);y&&(r.autonomousWorkers.value=y),r.autonomousWorkers.addEventListener("change",(()=>{localStorage.setItem(m,r.autonomousWorkers.value)})),ne();const h=localStorage.getItem(p);r.exploreToggle.checked="on"===h,r.exploreToggle.addEventListener("change",(()=>{localStorage.setItem(p,r.exploreToggle.checked?"on":"off"),r.exploreToggle.checked||W()})),r.classSelect.addEventListener("change",(()=>{localStorage.setItem(l,r.classSelect.value),se(r.classSelect.value),Zt(r.classSelect.value)})),r.modelSelect.addEventListener("change",(()=>{const e=O.get(r.modelSelect.value),t=maxTokensCeiling(e),n=r.modelHint.textContent.replace(/ · max output: [\d,]+$/,"");r.modelHint.textContent=t<FLAT_CEILING?`${n} · max output: ${t.toLocaleString()}`:n,se(r.classSelect.value),"byok"===r.classSelect.value&&e&&e.provider&&!1===e.configured&&function(e){if(!r.settingsList||!e)return;const t=r.settingsList.querySelector(`.setting-row[data-provider="byok:${e}"] input[type="password"]`);if(At(r.settingsList),t&&t.focus(),r.modelHint){const t=r.modelHint.textContent.replace(/ — no .* key saved; add it below\.$/,"");r.modelHint.textContent=`${t} — no ${e} key saved; add it below.`}}(e.provider)})),r.modelFree.addEventListener("input",(()=>{se(r.classSelect.value)})),r.newChat.addEventListener("click",bn),e.onMenuNewChat&&e.onMenuNewChat(bn),e.onMenuSearch&&e.onMenuSearch(yt),e.onMenuFingerprint&&e.onMenuFingerprint((()=>{Ve&&"function"==typeof Ve.open&&Ve.open()})),e.onMenuGoogleDrive&&e.onMenuGoogleDrive((()=>{Ve&&"function"==typeof Ve.open&&Ve.open({focus:"drive"})})),e.onMenuExportMarkdown&&e.onMenuExportMarkdown((()=>Cn("markdown"))),e.onMenuExportJson&&e.onMenuExportJson((()=>Cn("json"))),e.onDeepLink&&e.onDeepLink(wn),e.onQuickLauncherPush&&e.onQuickLauncherPush(Fe),r.sessionsRefresh.addEventListener("click",yn),r.syncNow.addEventListener("click",vn),r.sessionsExport.addEventListener("click",(()=>Cn("markdown"))),r.apiKeySave.addEventListener("click",Ce),r.apiKeyVerify.addEventListener("click",be),r.apiKeyInput.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),Ce())})),r.customSave&&r.customSave.addEventListener("click",rn),r.customRemove&&r.customRemove.addEventListener("click",ln);for(const e of[r.customBaseUrl,r.customKey,r.customModel])e&&e.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),rn())}));r.upgradePlan.addEventListener("click",(()=>ve("upgrade"))),r.topupBtn.addEventListener("click",(()=>ve("topup"))),attachScrollLift({panes:document.querySelectorAll(".messages, .side, .memory-scroll"),target:document.body,requestFrame:e=>window.requestAnimationFrame(e)}),r.quickLauncherSave.addEventListener("click",xe),r.quickLauncherShortcut.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),xe())})),r.confirmMode&&r.confirmMode.addEventListener("change",(()=>$e(r.confirmMode.checked))),r.autoMode&&r.autoMode.addEventListener("click",(()=>{r.confirmMode&&$e(!r.confirmMode.checked)})),r.composer.addEventListener("submit",(e=>{e.preventDefault(),xn()})),r.prompt&&(window.addEventListener("dragenter",(e=>{if(!e.dataTransfer)return;const t=Array.from(e.dataTransfer.types||[]);(t.includes("Files")||t.includes("text/plain")||t.includes("text/uri-list"))&&($n+=1,document.body.classList.add("is-dropping"))})),window.addEventListener("dragleave",(()=>{$n=Math.max(0,$n-1),0===$n&&document.body.classList.remove("is-dropping")})),window.addEventListener("dragover",(e=>{e.dataTransfer&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")})),window.addEventListener("drop",(t=>{$n=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 Nn(n):(En.push({name:t.name||"file",reason:"no path available"}),Ln())}return}const s=(n.getData("text/uri-list")||n.getData("text/plain")||"").split(/\r?\n/).map((e=>{const t=e.trim();if(!t)return"";const n=t.replace(/^file:\/\//,"");if(n===t)return t;try{return decodeURIComponent(n).trim()}catch{return n.trim()}})).filter(Boolean).join("\n");s&&(t.preventDefault(),function(e){const t=r.prompt;if(!t)return;const n="number"==typeof t.selectionStart?t.selectionStart:t.value.length,o="number"==typeof t.selectionEnd?t.selectionEnd:t.value.length,s=t.value.slice(0,n),a=t.value.slice(o),i=s&&!/\s$/.test(s)?" ":"";t.value=`${s}${i}${e}${a}`;const l=(s+i+e).length;try{t.setSelectionRange(l,l)}catch{}t.focus()}(s))}(t).catch((()=>{}))})),document.addEventListener("dragover",(e=>e.preventDefault())),document.addEventListener("drop",(e=>e.preventDefault())),r.classSelect&&r.classSelect.addEventListener("change",Ln),Ln()),r.prompt.addEventListener("keydown",(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),r.composer.requestSubmit())})),r.tabSessions&&r.tabSessions.addEventListener("click",(()=>pn("sessions"))),r.tabMemory&&r.tabMemory.addEventListener("click",(()=>pn("memory"))),r.memorySearchForm.addEventListener("submit",(e=>{e.preventDefault(),lt(r.memoryQuery.value.trim())})),r.memorySaveBtn.addEventListener("click",gt),r.memoryImportBtn.addEventListener("click",ft),r.memoryOpen&&r.memoryOpen.addEventListener("click",yt),r.memoryClose&&r.memoryClose.addEventListener("click",ht),r.memoryBackdrop&&r.memoryBackdrop.addEventListener("click",ht),r.memoryOverlaySave&&r.memoryOverlaySave.addEventListener("click",gt),r.memoryFilters&&r.memoryFilters.addEventListener("submit",(e=>{e.preventDefault(),je.query=r.memoryOverlayQuery.value.trim(),pt(je.query)})),r.memoryFiltersClear&&r.memoryFiltersClear.addEventListener("click",(()=>{r.memoryOverlayQuery.value="",je.query="",je.source="",je.role="",mt()})),r.keysClose&&r.keysClose.addEventListener("click",Rt),r.keysBackdrop&&r.keysBackdrop.addEventListener("click",Rt),r.keysDismiss&&r.keysDismiss.addEventListener("click",Ut),r.keysGotoAegis&&r.keysGotoAegis.addEventListener("click",(()=>{Rt(),At(r.apiKeyInput),r.apiKeyInput&&r.apiKeyInput.focus(),r.apiKeyHint&&(r.apiKeyHint.textContent=`Missing: ${function(){const e=[];return!0!==le&&e.push("the AEGIS key"),!0!==ce&&e.push("your provider (BYOK) key"),e.join(" and ")}()}. This is the AEGIS account key — the same one the CLI reads from ~/.aegiscode/.env, so pasting it here configures both.`)})),r.keysGotoByok&&r.keysGotoByok.addEventListener("click",(()=>{Rt(),Mt()})),s&&(r.queueEnqueue&&r.queueEnqueue.addEventListener("click",Ie),r.queueDrain&&r.queueDrain.addEventListener("click",(()=>Be("one"))),r.queueProceed&&r.queueProceed.addEventListener("click",(()=>Be("all"))),r.queueStop&&r.queueStop.addEventListener("click",Te),"function"==typeof s.onProgress&&s.onProgress(De),r.queueClassSelect&&r.queueClassSelect.addEventListener("change",(()=>{localStorage.setItem(c,r.queueClassSelect.value),tn(r.queueClassSelect.value)})),await He(),await async function(){if(!r.queueClassSelect)return;let e=[];try{e=await t.listClasses()||[]}catch(t){e=[],r.queueModelHint&&(r.queueModelHint.textContent=`listClasses failed: ${t&&t.message?t.message:t}`)}r.queueClassSelect.innerHTML="";for(const t of e){const e=document.createElement("option");e.value=t.class,e.textContent=t.configured?t.label:`${t.label} (not configured)`,r.queueClassSelect.appendChild(e)}const n=localStorage.getItem(c);n&&e.some((e=>e.class===n))&&(r.queueClassSelect.value=n),await tn(r.queueClassSelect.value)}()),a&&(r.queueAuto&&r.queueAuto.addEventListener("change",(()=>Oe(r.queueAuto.checked))),r.queueAutoInterval&&r.queueAutoInterval.addEventListener("change",(()=>{r.queueAuto&&r.queueAuto.checked&&Oe(!0)})),await async function(){if(!a||"function"!=typeof a.status)return null;try{const e=await a.status();return Ue(e),e}catch(e){return r.queueAutoHint&&(r.queueAutoHint.textContent=`automation status unavailable: ${e&&e.message?e.message:e}`),null}}()),J=createTranscriptView({messages:r.messages,requestFrame:e=>requestAnimationFrame(e)}),J.attachScrollVeto();let f=null;window.__aegisSmoke=Object.freeze({isScrolledUp:()=>J.isScrolledUp(),metrics:()=>J.metrics(),escapeDecision:()=>f&&"function"==typeof f.lastDecision?f.lastDecision():null,stopOutcome:()=>Z}),f=bindEscapeInterrupt({doc:document,isOverlayOpen:Ge,onOverlayEscape:()=>{if(We())Rt();else{if(Ve&&"function"==typeof Ve.close)try{return void Ve.close()}catch(e){}ht()}},hasPendingTurn:()=>!!B,stopTurn:ee}),r.accountBanner&&e.onAccountStatus&&(e.onAccountStatus(he),e.accountStatus().then(he).catch((e=>console.warn("account status unavailable",e))),r.accountRetryBtn.addEventListener("click",(()=>fe(r.accountRetryBtn))),r.keysAccountRetry&&r.keysAccountRetry.addEventListener("click",(()=>fe(r.keysAccountRetry)))),r.updateBanner&&e.onUpdateStatus&&(e.onUpdateStatus(pe),e.updateStatus().then(pe).catch((()=>{})),r.updateDownloadBtn.addEventListener("click",(()=>{r.updateDownloadBtn.disabled=!0,Promise.resolve(e.downloadUpdate()).then((e=>{e&&e.status&&pe(e)})).catch((()=>{})).finally((()=>{r.updateDownloadBtn.disabled=!1}))})),r.updateRestartBtn.addEventListener("click",(()=>{e.quitAndInstallUpdate()})),r.updateRetryBtn&&e.checkForUpdates&&r.updateRetryBtn.addEventListener("click",(()=>{r.updateRetryBtn.disabled=!0,Promise.resolve(e.checkForUpdates()).then(pe).catch((()=>{})).finally((()=>{r.updateRetryBtn.disabled=!1}))})),r.updateLaterBtn.addEventListener("click",(()=>{me=ue&&ue.status,r.updateBanner.hidden=!0}))),r.messages.querySelector(".msg, .chatflow")||$t(),await Xt(),await sn(),await async function(){if(o)try{we(await o.status())}catch(e){r.quickLauncherHint.textContent=`status failed: ${e&&e.message?e.message:e}`}}(),await async function(){if(r.confirmMode&&e.getConfirmMode)try{Se(await e.getConfirmMode())}catch(e){r.confirmModeHint.textContent=`status failed: ${e&&e.message?e.message:e}`}}(),await yn(),await fn(),ge(),pn("sessions"),r.memoryQuietFloor&&(r.memoryQuietFloor.textContent=String(Pe)),lt("");try{!function(){if(window.aegisProviderToolbar&&r.ptList)if(Ye=window.aegisProviderToolbar.mount({list:r.ptList,count:r.ptCount,search:r.ptSearch,hint:r.ptHint,onSelect:Xe}),r.ptRefresh&&r.ptRefresh.addEventListener("click",(()=>{Je(!0)})),"function"==typeof IntersectionObserver&&r.ptList.closest("section")){const e=new IntersectionObserver((t=>{t.some((e=>e.isIntersecting))&&(e.disconnect(),Je(!1))}));e.observe(r.ptList.closest("section"))}else Je(!1)}()}catch(e){r.ptHint&&(r.ptHint.textContent=`provider list unavailable: ${e&&e.message||e}`)}if(r.companionDismiss&&r.companionDismiss.addEventListener("click",(()=>{localStorage.setItem(Ze,JSON.stringify({day:window.aegisCompanion?window.aegisCompanion.dayKey(new Date):"",id:r.companionCard.dataset.messageId||""})),r.companionCard.hidden=!0})),tt(),window.aegisFingerprint)try{Ve=window.aegisFingerprint.mount({api:e,getSessionId:()=>T}),Ve.refresh().catch((()=>{}))}catch(e){const t=r.fpCardStatus;t&&(t.textContent=`authorship panel unavailable: ${e&&e.message||e}`)}}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",Tn):Tn()}();
|
|
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)}}
|
|
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),
|
|
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()}();
|