aegisone 1.0.65 → 1.0.67

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.
Files changed (43) hide show
  1. package/README.md +1 -1
  2. package/bin/aegis.js +1 -1
  3. package/package.json +1 -1
  4. package/vendor/cli/bin/aegiscode.js +47 -5
  5. package/vendor/cli/package.json +1 -1
  6. package/vendor/cli/src/app.js +1 -1
  7. package/vendor/cli/src/autonomous.js +574 -10
  8. package/vendor/cli/src/commands.js +1 -1
  9. package/vendor/cli/src/dream-cmd.js +3 -0
  10. package/vendor/cli/src/limits.js +1 -1
  11. package/vendor/cli/src/provenance.lock.json +3 -3
  12. package/vendor/cli/src/screen.js +1 -1
  13. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1
  14. package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
  15. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -1
  16. package/vendor/cli/vendor/desktop/main.js +82 -1
  17. package/vendor/cli/vendor/mcp/tools.js +1 -1
  18. package/vendor/desktop/lib/local/autonomous.js +1 -1
  19. package/vendor/desktop/lib/local/integrity.js +1 -1
  20. package/vendor/desktop/lib/local/queue.js +1 -1
  21. package/vendor/desktop/main.js +82 -1
  22. package/vendor/desktop/package.json +1 -1
  23. package/vendor/desktop/preload.js +1 -1
  24. package/vendor/desktop/renderer/app.js +3 -3
  25. package/vendor/desktop/renderer/pty-panel.js +1 -1
  26. package/vendor/desktop/renderer/pty-window.html +72 -0
  27. package/vendor/desktop/renderer/pty-window.js +3 -0
  28. package/vendor/desktop/renderer/stream-policy.js +1 -1
  29. package/vendor/desktop/renderer/style.css +55 -3
  30. package/vendor/desktop/vendor/faces/cli/bin/aegiscode.js +2 -2
  31. package/vendor/desktop/vendor/faces/cli/package.json +1 -1
  32. package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
  33. package/vendor/desktop/vendor/faces/cli/src/autonomous.js +1 -1
  34. package/vendor/desktop/vendor/faces/cli/src/commands.js +1 -1
  35. package/vendor/desktop/vendor/faces/cli/src/dream-cmd.js +3 -0
  36. package/vendor/desktop/vendor/faces/cli/src/limits.js +1 -1
  37. package/vendor/desktop/vendor/faces/cli/src/provenance.lock.json +3 -3
  38. package/vendor/desktop/vendor/faces/cli/src/screen.js +1 -1
  39. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/autonomous.js +1 -1
  40. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
  41. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/queue.js +1 -1
  42. package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +3 -3
  43. package/vendor/desktop/vendor/faces/cli/vendor/mcp/tools.js +1 -1
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
4
- "use strict";const path=require("node:path"),fs=require("node:fs"),{execFile:execFile}=require("node:child_process"),{pathToFileURL:pathToFileURL}=require("node:url");let sharedClient;try{sharedClient=require("../client/aegis.js")}catch{sharedClient=require("./vendor/aegis.js")}const{createClient:createClient}=sharedClient;let credentials,autoProvision,sharedPresence,sharedTopup,googleSignIn,driveConnectLib,driveUploadLib,conversationExportLib;try{credentials=require("../client/credentials.js")}catch{credentials=require("./vendor/credentials.js")}try{autoProvision=require("../client/auto-provision.js")}catch{autoProvision=require("./vendor/auto-provision.js")}try{sharedPresence=require("../client/presence.js")}catch{sharedPresence=require("./vendor/presence.js")}try{sharedTopup=require("../client/topup.js")}catch{sharedTopup=require("./vendor/topup.js")}try{googleSignIn=require("../client/google-signin.js")}catch{googleSignIn=require("./vendor/google-signin.js")}try{driveConnectLib=require("../client/drive-connect.js")}catch{driveConnectLib=require("./vendor/drive-connect.js")}try{driveUploadLib=require("../client/drive-upload.js")}catch{driveUploadLib=require("./vendor/drive-upload.js")}try{conversationExportLib=require("../client/conversation-export.js")}catch{try{conversationExportLib=require("./vendor/conversation-export.js")}catch{conversationExportLib=null}}const{createGoogleConnect:createGoogleConnect}=require("./lib/google-connect.js");let sharedFingerprint;try{sharedFingerprint=require("../client/device-fingerprint.js")}catch{sharedFingerprint=require("./vendor/device-fingerprint.js")}const{createFingerprintService:createFingerprintService}=require("./lib/fingerprint.js"),{createAutoDrain:createAutoDrain,createAutoMint:createAutoMint}=require("./lib/auto.js");let envFile=null;try{envFile=require("../client/env-file.js")}catch{try{envFile=require("./vendor/env-file.js")}catch{}}let electron=null;try{electron=require("electron")}catch{}const os=require("node:os"),{createLocalEngine:createLocalEngine}=require("./lib/local/engine.js"),{createAccountKey:createAccountKey,startupKeyOverride:startupKeyOverride}=require("./lib/account-key.js"),{createSettingsStore:createSettingsStore,isReservedNamespace:isReservedNamespace}=require("./lib/settings.js"),sessionStore=require("./lib/sync/sessions.js"),memoryQueue=require("./lib/sync/memory-queue.js"),sessionSearch=(()=>{try{return require("../client/session-search.js")}catch{return require("./vendor/session-search.js")}})(),creditsLib=(()=>{try{return require("../client/credits.js")}catch{return require("./vendor/credits.js")}})(),speechHost=require("./lib/speech-host.js"),skillsHost=require("./lib/skills-host.js");function readSpeechSettings(e){try{if(!e||"function"!=typeof e.getSharedPref)return{};const t=e.getSharedPref("speech");return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}catch{return{}}}const memoryStore=require("./lib/sync/memory-store.js"),persistGate=require("./lib/sync/persist-gate.js"),avatarStore=require("./lib/avatar/store.js"),windowState=require("./lib/window-state.js"),deepLink=require("./lib/deep-link.js"),quickLauncherLib=require("./lib/quick-launcher.js");let foreignMemory,foreignSessions;try{foreignMemory=require("../client/foreign-memory.js")}catch{foreignMemory=require("./vendor/foreign-memory.js")}try{foreignSessions=require("../client/foreign-sessions.js")}catch{foreignSessions=require("./vendor/foreign-sessions.js")}const localTools=require("./lib/local/tools.js"),queueModule=require("./lib/local/queue.js"),autonomousModule=require("./lib/local/autonomous.js"),{autoContinuePlan:autoContinuePlan,autoContinueLimit:autoContinueLimit,autoRoundsDefault:autoRoundsDefault}=require("./lib/local/autonomous.js"),entitlementModule=require("./lib/local/entitlement.js"),telemetryModule=require("./lib/local/telemetry.js"),covenantModule=require("./lib/local/covenant.js"),{createTelemetry:createTelemetry,telemetryEnabled:telemetryEnabled}=telemetryModule,IPC_PREFIX="aegis:",MODEL_PREFIX="model:",SYNC_PREFIX="sync:",TOOLS_PREFIX="tools:",QUICK_PREFIX="quick:",QUEUE_PREFIX="queue:",AUTO_PREFIX="auto:",DESKTOP_CLASSES=Object.freeze(["aegis","byok","local"]),CHAT_DELTA_CHANNEL="aegis:chatDelta",PTY_EVENT_CHANNEL="aegis:ptyEvent",MENU_NEW_CHAT_CHANNEL="aegis:menuNewChat",MENU_SEARCH_CHANNEL="aegis:menuSearch",MENU_SEARCH_MEMORY_CHANNEL="aegis:menuSearchMemory",MENU_CREDITS_CHANNEL="aegis:menuCredits",MENU_PALETTE_CHANNEL="aegis:menuPalette",MENU_TOGGLE_SIDEBAR_CHANNEL="aegis:menuToggleSidebar",MENU_FIND_CHANNEL="aegis:menuFind",MENU_GO_BACK_CHANNEL="aegis:menuGoBack",MENU_GO_FORWARD_CHANNEL="aegis:menuGoForward",navState={back:!1,forward:!1},MENU_EXPORT_MARKDOWN_CHANNEL="aegis:menuExportMarkdown",MENU_EXPORT_JSON_CHANNEL="aegis:menuExportJson",MENU_FINGERPRINT_CHANNEL="aegis:menuFingerprint",MENU_GOOGLE_DRIVE_CHANNEL="aegis:menuGoogleDrive",DEEP_LINK_CHANNEL="aegis:deepLink",QUICK_LAUNCHER_PUSH_CHANNEL="aegis:quickLauncherPush",QUEUE_PROGRESS_CHANNEL="queue:progress",QUEUE_CHANGED_CHANNEL="queue:changed",QUEUE_MUTATING_METHODS=new Set(["enqueue","clear","retry","remove","drain","proceed","stop"]),QUEUE_MAX_TASK_CHARS=8e3,QUEUE_MAX_ROUNDS=200,QUEUE_MAX_WORKERS=8,QUEUE_EFFORTS=new Set(["low","medium","high","max"]);function taggedChunk(e,t){return{...e&&"object"==typeof e?e:{delta:e},id:t}}const APP_VERSION=require("./package.json").version;function maskKey(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}function upgradeInfo(e){const t=e&&e.status,r=e&&e.data||{},n="string"==typeof r.error?r.error:"";if(402!==t&&"free_session_limit_reached"!==n)return null;const o=null!=r.tokensUsed?r.tokensUsed:null!=r.sessionsUsed?r.sessionsUsed:null,s=null!=r.tokenLimit?r.tokenLimit:null!=r.freeSessionLimit?r.freeSessionLimit:null;return{url:r.upgradeUrl||"https://aegiscloud.org/go/upgrade?s=desktop&c=status_card",used:o,limit:s,code:n||"free_session_limit_reached"}}function errorText(e){return e&&e.message?e.message:String(e)}function isAbortShapedError(e){return!(!e||"object"!=typeof e||!0!==e.aegisCancelled&&"AbortError"!==e.name&&"ABORT_ERR"!==e.code)}function abortedTurnPayload(e){return{aborted:!0,status:0,code:"ABORT_ERR",message:errorText(e),choices:[{message:{content:""}}]}}function backgroundLaneLogs(e){const t=process.env.AEGIS_DEBUG;return"1"===t||"true"===t||"yes"===t||Boolean(e&&"function"==typeof e.getDevMode&&e.getDevMode())}function describeSyncError(e){const t=e&&(e.status||e.response&&e.response.status)||0,r=errorText(e);return upgradeInfo(e)?{kind:"quota",status:t||402,message:r,hint:"the plan's synced-token ceiling is reached — free space in the account dashboard or upgrade to keep syncing"}:401===t?{kind:"auth",status:t,message:r,hint:"the memory token was refused — re-enter your AEGIS API key to exchange a new one"}:{kind:"error",status:t||null,message:r,hint:null}}function syncErrorReason(e){return e?e.hint?`${e.message} — ${e.hint}`:e.message:"sync failed"}async function billingResult(e){try{const t=await e();return{ok:!0,url:t&&t.url||null,status:0,reason:null,setupRequired:!1,upgrade:null}}catch(e){const t=e&&e.data||{};return{ok:!1,url:null,status:e&&e.status||0,reason:errorText(e),setupRequired:Boolean(t.setup_required),upgrade:upgradeInfo(e)}}}const{bankAmount:bankAmount,parseTopupAmount:parseTopupAmount,startTopup:startTopup,createCreditWatch:createCreditWatch,TOPUP_POLL_MS:TOPUP_POLL_MS,TOPUP_POLL_TRIES:TOPUP_POLL_TRIES}=sharedTopup;let topupWatch=null;function watchTopupCredit(e,t){const r=t||{},n=r.intervalMs||TOPUP_POLL_MS,o=r.log;topupWatch&&clearInterval(topupWatch);const s=createCreditWatch(e,r.maxTries?{maxTries:r.maxTries}:void 0),a=()=>{topupWatch&&clearInterval(topupWatch),topupWatch=null,s.stop()},i=async()=>{const e=await s.tick();"credited"===e.state?(a(),(e=>{if("function"!=typeof r.notify)try{const t=electron&&electron.Notification;t&&t.isSupported()&&new t({title:"aegis one",body:`Bank credited — €${e.toFixed(2)} available`}).show()}catch{}else r.notify(e)})(e.amount)):"expired"===e.state&&(a(),o&&o("top-up: no credit observed within the watch window; stopping"))};return topupWatch=setInterval(i,n),topupWatch&&"function"==typeof topupWatch.unref&&topupWatch.unref(),{stop:a,tick:i,get baseline(){return s.baseline}}}let memoryIndexHandle=null,memoryIndexOff=!1,memoryIndexTries=0;function memoryIndex(e){if(memoryIndexHandle)return memoryIndexHandle;if(memoryIndexOff||!e)return null;try{const t=new memoryStore.MemoryStore({dir:e});return t.open().ok?(memoryIndexTries=0,memoryIndexHandle=t,memoryIndexHandle):((!memoryStore.isAvailable()||++memoryIndexTries>=3)&&(memoryIndexOff=!0),null)}catch{return(!memoryStore.isAvailable()||++memoryIndexTries>=3)&&(memoryIndexOff=!0),null}}function closeMemoryIndex(){if(memoryIndexHandle){try{memoryIndexHandle.close()}catch{}memoryIndexHandle=null}}async function saveMemoryWithQueue(e,t,r,n,o){const s=avatarStore.normalizeMemoryEntry(r);try{const t=await e.memorySave(s);if(n&&s&&"object"==typeof s&&n.awardSave(s,{session:s.session}),o&&s&&"object"==typeof s)try{o.upsert(s)}catch{}return t}catch(e){const o=upgradeInfo(e);if(o)return{ok:!1,queued:0,saved:0,upgrade:o,reason:errorText(e)};if(!t||!r)throw e;return memoryQueue.enqueue(t,s),n&&s&&"object"==typeof s&&n.awardQueued(s,{session:s.session}),{ok:!0,queued:!0,reason:errorText(e)}}}async function normalizeMemoryRead(e){try{const t=await e,r=quotaFromPayload(t);return r?Object.assign({},t,{upgrade:r}):t}catch(e){const t=upgradeInfo(e);if(!t)throw e;return{entries:[],upgrade:t}}}async function normalizeMemoryReadWithFallback(e,t,r,n){try{return await normalizeMemoryRead(e)}catch(e){const o=Number(e&&e.status),s=o>=400&&o<500||!t?null:searchMemoryLocally(t,r,n);if(!s||!s.entries.length)throw e;return s}}function searchMemoryLocally(e,t,r){let n;try{n=e.search(t,{limit:r})}catch{return null}return n&&n.ok&&Array.isArray(n.results)?{entries:n.results.map(e=>({id:e.id,content:e.body,source:"local-index",scope:e.scope,tags:Array.isArray(e.tags)?e.tags:[],createdAt:e.updated})),local:!0,fts:!0===n.fts}:null}async function indexPulledMemory(e,t){const r=await e;if(t&&r&&Array.isArray(r.entries)&&r.entries.length)try{t.upsertMany(r.entries)}catch{}return r}function quotaFromPayload(e){if(!e||"object"!=typeof e)return null;const t=null!=e.tokensUsed?e.tokensUsed:null,r=null!=e.tokenLimit?e.tokenLimit:null;return null==t||null==r||r<=0||t<r?null:{url:"https://aegiscloud.org/go/upgrade?s=desktop&c=memory_quota",used:t,limit:r,code:"sync_quota_reached"}}async function importForeignSessions(e,t){const r=t||{},n=foreignSessions.scan({sources:r.sources,limit:r.limit||500}),o=foreignSessions.describe(n),s=n.sources.map(e=>({id:e.id,label:e.label,verified:e.verified,present:e.present,unreadable:e.unreadable,count:e.count,messages:e.messages,files:e.files,skipped:e.skipped})),a={summary:o,totals:n.totals,sources:s};if(!r.confirm||!n.sessions.length)return{...a,ok:!0,dryRun:!r.confirm,imported:0,skippedExisting:0,sessions:n.sessions.map(e=>({id:e.id,title:e.title,source:e.source,sourceLabel:e.sourceLabel,messages:e.messages.length,updatedAt:e.updatedAt}))};const i=new Set((sessions.listSessions(e)||[]).map(e=>e&&e.id).filter(Boolean));let c=0,l=0;const u=[];for(const t of n.sessions)try{if(i.has(t.id)){l+=1;continue}sessions.upsertSession(e,foreignSessions.toRecord(t,{pending:!0===r.sync})),c+=1}catch(e){u.push(errorText(e))}return{...a,ok:0===u.length,dryRun:!1,imported:c,skippedExisting:l,reason:u[0]||null}}async function importForeignMemory(e,t,r,n,o){const s=r||{},a=foreignMemory.scan({sources:s.sources,limit:s.limit||1e3}),i=foreignMemory.describe(a),c=a.sources.map(e=>({id:e.id,label:e.label,verified:e.verified,present:e.present,count:e.count,skipped:e.skipped,files:e.files})),l={summary:i,totals:a.totals,sources:c};if(!s.confirm||!a.entries.length)return{...l,ok:!0,dryRun:!s.confirm,saved:0,queued:0};let u=0,d=0;const p=[];let m=null;for(const r of foreignMemory.chunk(a.entries,200))try{const t=await e.memorySaveBatch(r);if(u+=t&&t.saved||r.length,n&&r.length){const e=r[0]||{};n.awardImports(r,{source:e.session||e.source||"foreign-import"})}if(o&&r.length)try{o.upsertMany(r)}catch{}}catch(e){if(m=upgradeInfo(e),!m&&t)for(const e of r)memoryQueue.enqueue(t,e),d+=1,n&&n.awardQueued(e,{session:e&&e.session});p.push(errorText(e));break}return{...l,ok:0===p.length,dryRun:!1,saved:u,queued:d,upgrade:m,reason:p[0]||null}}function resolveIconsDir(e,t,r){return e?path.join(t,"icons"):path.join(r,"build")}function iconForPlatform(e,t){return"darwin"===t?path.join(e,"icon.icns"):"win32"===t?path.join(e,"icon.ico"):path.join(e,"icon.png")}function isSafeExternalUrl(e){if("string"!=typeof e||!e)return!1;try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}function providerRouteConfigured(e){try{const t=e&&e.settings&&e.settings.list;return"function"==typeof t&&(t.call(e.settings)||[]).some(e=>{if(!e||!e.provider||isReservedNamespace(e.provider))return!1;const t="string"==typeof e.baseURL?e.baseURL.trim():"";return Boolean(e.configured||t)})}catch{return!1}}function createIpcDispatch(e,t,r,n,o,s,a){let i=null;const c=new Proxy({},{get(e,r){i||(i=createFingerprintService({dir:t,getVaultBackend:a}));const n=i[r];return"function"==typeof n?n.bind(i):n},has:(e,r)=>(i||(i=createFingerprintService({dir:t,getVaultBackend:a})),r in i)}),l=()=>{try{return Boolean("function"==typeof o&&o())}catch{return!1}},u=n||(()=>Promise.reject(new Error("no opener configured")));return{status:()=>({appVersion:APP_VERSION,clientVersion:e.clientVersion,apiBase:e.apiBase,keyConfigured:Boolean(e.apiKey),keyMask:maskKey(e.apiKey),providerConfigured:l()}),setApiKey:t=>{try{const n=t&&t.key;return e.setApiKey(n||""),r&&r(e.apiKey),{ok:!0,keyConfigured:Boolean(e.apiKey),keyMask:maskKey(e.apiKey)}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},verifyApiKey:async()=>{try{return{ok:!0,...await e.verifyApiKey()}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},tokenBankBalance:()=>e.tokenBankBalance(),billingCheckout:()=>billingResult(()=>e.billingCheckout()),tokenBankTopup:async t=>{const r=parseTopupAmount(t&&t.amountEur);if(!r.ok)return{ok:!1,url:null,status:400,reason:r.message,setupRequired:!1,upgrade:null};const n=await startTopup(e,r.amount);return!0===n.ok&&n.url&&watchTopupCredit(e),{ok:!0===n.ok,url:n.url,status:n.status,reason:n.ok?null:n.hint?`${n.message} — ${n.hint}`:n.message,setupRequired:n.setupRequired,upgrade:null}},listModels:()=>e.listModels(),chatCompletion:t=>e.chatCompletion({prompt:t&&t.prompt,system:t&&t.system,model:t&&t.model,mode:t&&t.mode,maxTokens:t&&t.maxTokens,stream:t&&t.stream,onStream:t&&t.onStream}),fingerprintStatus:()=>c.status(),fingerprintKeygen:e=>c.keygen(e||{}),fingerprintMint:e=>c.mint(e||{}),fingerprintVerify:e=>c.verify(e||{}),fingerprintBackup:e=>c.backup(e||{}),
4
+ "use strict";const path=require("node:path"),fs=require("node:fs"),{execFile:execFile}=require("node:child_process"),{pathToFileURL:pathToFileURL}=require("node:url");let sharedClient;try{sharedClient=require("../client/aegis.js")}catch{sharedClient=require("./vendor/aegis.js")}const{createClient:createClient}=sharedClient;let credentials,autoProvision,sharedPresence,sharedTopup,googleSignIn,driveConnectLib,driveUploadLib,conversationExportLib;try{credentials=require("../client/credentials.js")}catch{credentials=require("./vendor/credentials.js")}try{autoProvision=require("../client/auto-provision.js")}catch{autoProvision=require("./vendor/auto-provision.js")}try{sharedPresence=require("../client/presence.js")}catch{sharedPresence=require("./vendor/presence.js")}try{sharedTopup=require("../client/topup.js")}catch{sharedTopup=require("./vendor/topup.js")}try{googleSignIn=require("../client/google-signin.js")}catch{googleSignIn=require("./vendor/google-signin.js")}try{driveConnectLib=require("../client/drive-connect.js")}catch{driveConnectLib=require("./vendor/drive-connect.js")}try{driveUploadLib=require("../client/drive-upload.js")}catch{driveUploadLib=require("./vendor/drive-upload.js")}try{conversationExportLib=require("../client/conversation-export.js")}catch{try{conversationExportLib=require("./vendor/conversation-export.js")}catch{conversationExportLib=null}}const{createGoogleConnect:createGoogleConnect}=require("./lib/google-connect.js");let sharedFingerprint;try{sharedFingerprint=require("../client/device-fingerprint.js")}catch{sharedFingerprint=require("./vendor/device-fingerprint.js")}const{createFingerprintService:createFingerprintService}=require("./lib/fingerprint.js"),{createAutoDrain:createAutoDrain,createAutoMint:createAutoMint}=require("./lib/auto.js");let envFile=null;try{envFile=require("../client/env-file.js")}catch{try{envFile=require("./vendor/env-file.js")}catch{}}let electron=null;try{electron=require("electron")}catch{}const os=require("node:os"),{createLocalEngine:createLocalEngine}=require("./lib/local/engine.js"),{createAccountKey:createAccountKey,startupKeyOverride:startupKeyOverride}=require("./lib/account-key.js"),{createSettingsStore:createSettingsStore,isReservedNamespace:isReservedNamespace}=require("./lib/settings.js"),sessionStore=require("./lib/sync/sessions.js"),memoryQueue=require("./lib/sync/memory-queue.js"),sessionSearch=(()=>{try{return require("../client/session-search.js")}catch{return require("./vendor/session-search.js")}})(),creditsLib=(()=>{try{return require("../client/credits.js")}catch{return require("./vendor/credits.js")}})(),speechHost=require("./lib/speech-host.js"),skillsHost=require("./lib/skills-host.js");function readSpeechSettings(e){try{if(!e||"function"!=typeof e.getSharedPref)return{};const t=e.getSharedPref("speech");return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}catch{return{}}}const memoryStore=require("./lib/sync/memory-store.js"),persistGate=require("./lib/sync/persist-gate.js"),avatarStore=require("./lib/avatar/store.js"),windowState=require("./lib/window-state.js"),deepLink=require("./lib/deep-link.js"),quickLauncherLib=require("./lib/quick-launcher.js");let foreignMemory,foreignSessions;try{foreignMemory=require("../client/foreign-memory.js")}catch{foreignMemory=require("./vendor/foreign-memory.js")}try{foreignSessions=require("../client/foreign-sessions.js")}catch{foreignSessions=require("./vendor/foreign-sessions.js")}const localTools=require("./lib/local/tools.js"),queueModule=require("./lib/local/queue.js"),autonomousModule=require("./lib/local/autonomous.js"),{autoContinuePlan:autoContinuePlan,autoContinueLimit:autoContinueLimit,autoRoundsDefault:autoRoundsDefault}=require("./lib/local/autonomous.js"),entitlementModule=require("./lib/local/entitlement.js"),telemetryModule=require("./lib/local/telemetry.js"),covenantModule=require("./lib/local/covenant.js"),{createTelemetry:createTelemetry,telemetryEnabled:telemetryEnabled}=telemetryModule,IPC_PREFIX="aegis:",MODEL_PREFIX="model:",SYNC_PREFIX="sync:",TOOLS_PREFIX="tools:",QUICK_PREFIX="quick:",QUEUE_PREFIX="queue:",AUTO_PREFIX="auto:",DESKTOP_CLASSES=Object.freeze(["aegis","byok","local"]),CHAT_DELTA_CHANNEL="aegis:chatDelta",PTY_EVENT_CHANNEL="aegis:ptyEvent",MENU_NEW_CHAT_CHANNEL="aegis:menuNewChat",MENU_SEARCH_CHANNEL="aegis:menuSearch",MENU_SEARCH_MEMORY_CHANNEL="aegis:menuSearchMemory",MENU_CREDITS_CHANNEL="aegis:menuCredits",MENU_PALETTE_CHANNEL="aegis:menuPalette",MENU_TOGGLE_SIDEBAR_CHANNEL="aegis:menuToggleSidebar",MENU_FIND_CHANNEL="aegis:menuFind",MENU_GO_BACK_CHANNEL="aegis:menuGoBack",MENU_GO_FORWARD_CHANNEL="aegis:menuGoForward",navState={back:!1,forward:!1},MENU_EXPORT_MARKDOWN_CHANNEL="aegis:menuExportMarkdown",MENU_EXPORT_JSON_CHANNEL="aegis:menuExportJson",MENU_FINGERPRINT_CHANNEL="aegis:menuFingerprint",MENU_GOOGLE_DRIVE_CHANNEL="aegis:menuGoogleDrive",DEEP_LINK_CHANNEL="aegis:deepLink",QUICK_LAUNCHER_PUSH_CHANNEL="aegis:quickLauncherPush",QUEUE_PROGRESS_CHANNEL="queue:progress",QUEUE_CHANGED_CHANNEL="queue:changed",QUEUE_MUTATING_METHODS=new Set(["enqueue","clear","retry","remove","drain","proceed","stop"]),QUEUE_MAX_TASK_CHARS=8e3,QUEUE_MAX_ROUNDS=200,QUEUE_MAX_WORKERS=8,QUEUE_EFFORTS=new Set(["low","medium","high","max"]);function taggedChunk(e,t){return{...e&&"object"==typeof e?e:{delta:e},id:t}}const APP_VERSION=require("./package.json").version;function maskKey(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}function upgradeInfo(e){const t=e&&e.status,n=e&&e.data||{},r="string"==typeof n.error?n.error:"";if(402!==t&&"free_session_limit_reached"!==r)return null;const o=null!=n.tokensUsed?n.tokensUsed:null!=n.sessionsUsed?n.sessionsUsed:null,s=null!=n.tokenLimit?n.tokenLimit:null!=n.freeSessionLimit?n.freeSessionLimit:null;return{url:n.upgradeUrl||"https://aegiscloud.org/go/upgrade?s=desktop&c=status_card",used:o,limit:s,code:r||"free_session_limit_reached"}}function errorText(e){return e&&e.message?e.message:String(e)}function isAbortShapedError(e){return!(!e||"object"!=typeof e||!0!==e.aegisCancelled&&"AbortError"!==e.name&&"ABORT_ERR"!==e.code)}function abortedTurnPayload(e){return{aborted:!0,status:0,code:"ABORT_ERR",message:errorText(e),choices:[{message:{content:""}}]}}function backgroundLaneLogs(e){const t=process.env.AEGIS_DEBUG;return"1"===t||"true"===t||"yes"===t||Boolean(e&&"function"==typeof e.getDevMode&&e.getDevMode())}function describeSyncError(e){const t=e&&(e.status||e.response&&e.response.status)||0,n=errorText(e);return upgradeInfo(e)?{kind:"quota",status:t||402,message:n,hint:"the plan's synced-token ceiling is reached — free space in the account dashboard or upgrade to keep syncing"}:401===t?{kind:"auth",status:t,message:n,hint:"the memory token was refused — re-enter your AEGIS API key to exchange a new one"}:{kind:"error",status:t||null,message:n,hint:null}}function syncErrorReason(e){return e?e.hint?`${e.message} — ${e.hint}`:e.message:"sync failed"}async function billingResult(e){try{const t=await e();return{ok:!0,url:t&&t.url||null,status:0,reason:null,setupRequired:!1,upgrade:null}}catch(e){const t=e&&e.data||{};return{ok:!1,url:null,status:e&&e.status||0,reason:errorText(e),setupRequired:Boolean(t.setup_required),upgrade:upgradeInfo(e)}}}const{bankAmount:bankAmount,parseTopupAmount:parseTopupAmount,startTopup:startTopup,createCreditWatch:createCreditWatch,TOPUP_POLL_MS:TOPUP_POLL_MS,TOPUP_POLL_TRIES:TOPUP_POLL_TRIES}=sharedTopup;let topupWatch=null;function watchTopupCredit(e,t){const n=t||{},r=n.intervalMs||TOPUP_POLL_MS,o=n.log;topupWatch&&clearInterval(topupWatch);const s=createCreditWatch(e,n.maxTries?{maxTries:n.maxTries}:void 0),a=()=>{topupWatch&&clearInterval(topupWatch),topupWatch=null,s.stop()},i=async()=>{const e=await s.tick();"credited"===e.state?(a(),(e=>{if("function"!=typeof n.notify)try{const t=electron&&electron.Notification;t&&t.isSupported()&&new t({title:"aegis one",body:`Bank credited — €${e.toFixed(2)} available`}).show()}catch{}else n.notify(e)})(e.amount)):"expired"===e.state&&(a(),o&&o("top-up: no credit observed within the watch window; stopping"))};return topupWatch=setInterval(i,r),topupWatch&&"function"==typeof topupWatch.unref&&topupWatch.unref(),{stop:a,tick:i,get baseline(){return s.baseline}}}let memoryIndexHandle=null,memoryIndexOff=!1,memoryIndexTries=0;function memoryIndex(e){if(memoryIndexHandle)return memoryIndexHandle;if(memoryIndexOff||!e)return null;try{const t=new memoryStore.MemoryStore({dir:e});return t.open().ok?(memoryIndexTries=0,memoryIndexHandle=t,memoryIndexHandle):((!memoryStore.isAvailable()||++memoryIndexTries>=3)&&(memoryIndexOff=!0),null)}catch{return(!memoryStore.isAvailable()||++memoryIndexTries>=3)&&(memoryIndexOff=!0),null}}function closeMemoryIndex(){if(memoryIndexHandle){try{memoryIndexHandle.close()}catch{}memoryIndexHandle=null}}async function saveMemoryWithQueue(e,t,n,r,o){const s=avatarStore.normalizeMemoryEntry(n);try{const t=await e.memorySave(s);if(r&&s&&"object"==typeof s&&r.awardSave(s,{session:s.session}),o&&s&&"object"==typeof s)try{o.upsert(s)}catch{}return t}catch(e){const o=upgradeInfo(e);if(o)return{ok:!1,queued:0,saved:0,upgrade:o,reason:errorText(e)};if(!t||!n)throw e;return memoryQueue.enqueue(t,s),r&&s&&"object"==typeof s&&r.awardQueued(s,{session:s.session}),{ok:!0,queued:!0,reason:errorText(e)}}}async function normalizeMemoryRead(e){try{const t=await e,n=quotaFromPayload(t);return n?Object.assign({},t,{upgrade:n}):t}catch(e){const t=upgradeInfo(e);if(!t)throw e;return{entries:[],upgrade:t}}}async function normalizeMemoryReadWithFallback(e,t,n,r){try{return await normalizeMemoryRead(e)}catch(e){const o=Number(e&&e.status),s=o>=400&&o<500||!t?null:searchMemoryLocally(t,n,r);if(!s||!s.entries.length)throw e;return s}}function searchMemoryLocally(e,t,n){let r;try{r=e.search(t,{limit:n})}catch{return null}return r&&r.ok&&Array.isArray(r.results)?{entries:r.results.map(e=>({id:e.id,content:e.body,source:"local-index",scope:e.scope,tags:Array.isArray(e.tags)?e.tags:[],createdAt:e.updated})),local:!0,fts:!0===r.fts}:null}async function indexPulledMemory(e,t){const n=await e;if(t&&n&&Array.isArray(n.entries)&&n.entries.length)try{t.upsertMany(n.entries)}catch{}return n}function quotaFromPayload(e){if(!e||"object"!=typeof e)return null;const t=null!=e.tokensUsed?e.tokensUsed:null,n=null!=e.tokenLimit?e.tokenLimit:null;return null==t||null==n||n<=0||t<n?null:{url:"https://aegiscloud.org/go/upgrade?s=desktop&c=memory_quota",used:t,limit:n,code:"sync_quota_reached"}}async function importForeignSessions(e,t){const n=t||{},r=foreignSessions.scan({sources:n.sources,limit:n.limit||500}),o=foreignSessions.describe(r),s=r.sources.map(e=>({id:e.id,label:e.label,verified:e.verified,present:e.present,unreadable:e.unreadable,count:e.count,messages:e.messages,files:e.files,skipped:e.skipped})),a={summary:o,totals:r.totals,sources:s};if(!n.confirm||!r.sessions.length)return{...a,ok:!0,dryRun:!n.confirm,imported:0,skippedExisting:0,sessions:r.sessions.map(e=>({id:e.id,title:e.title,source:e.source,sourceLabel:e.sourceLabel,messages:e.messages.length,updatedAt:e.updatedAt}))};const i=new Set((sessions.listSessions(e)||[]).map(e=>e&&e.id).filter(Boolean));let c=0,l=0;const u=[];for(const t of r.sessions)try{if(i.has(t.id)){l+=1;continue}sessions.upsertSession(e,foreignSessions.toRecord(t,{pending:!0===n.sync})),c+=1}catch(e){u.push(errorText(e))}return{...a,ok:0===u.length,dryRun:!1,imported:c,skippedExisting:l,reason:u[0]||null}}async function importForeignMemory(e,t,n,r,o){const s=n||{},a=foreignMemory.scan({sources:s.sources,limit:s.limit||1e3}),i=foreignMemory.describe(a),c=a.sources.map(e=>({id:e.id,label:e.label,verified:e.verified,present:e.present,count:e.count,skipped:e.skipped,files:e.files})),l={summary:i,totals:a.totals,sources:c};if(!s.confirm||!a.entries.length)return{...l,ok:!0,dryRun:!s.confirm,saved:0,queued:0};let u=0,d=0;const p=[];let m=null;for(const n of foreignMemory.chunk(a.entries,200))try{const t=await e.memorySaveBatch(n);if(u+=t&&t.saved||n.length,r&&n.length){const e=n[0]||{};r.awardImports(n,{source:e.session||e.source||"foreign-import"})}if(o&&n.length)try{o.upsertMany(n)}catch{}}catch(e){if(m=upgradeInfo(e),!m&&t)for(const e of n)memoryQueue.enqueue(t,e),d+=1,r&&r.awardQueued(e,{session:e&&e.session});p.push(errorText(e));break}return{...l,ok:0===p.length,dryRun:!1,saved:u,queued:d,upgrade:m,reason:p[0]||null}}function resolveIconsDir(e,t,n){return e?path.join(t,"icons"):path.join(n,"build")}function iconForPlatform(e,t){return"darwin"===t?path.join(e,"icon.icns"):"win32"===t?path.join(e,"icon.ico"):path.join(e,"icon.png")}function isSafeExternalUrl(e){if("string"!=typeof e||!e)return!1;try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}function providerRouteConfigured(e){try{const t=e&&e.settings&&e.settings.list;return"function"==typeof t&&(t.call(e.settings)||[]).some(e=>{if(!e||!e.provider||isReservedNamespace(e.provider))return!1;const t="string"==typeof e.baseURL?e.baseURL.trim():"";return Boolean(e.configured||t)})}catch{return!1}}function createIpcDispatch(e,t,n,r,o,s,a){let i=null;const c=new Proxy({},{get(e,n){i||(i=createFingerprintService({dir:t,getVaultBackend:a}));const r=i[n];return"function"==typeof r?r.bind(i):r},has:(e,n)=>(i||(i=createFingerprintService({dir:t,getVaultBackend:a})),n in i)}),l=()=>{try{return Boolean("function"==typeof o&&o())}catch{return!1}},u=r||(()=>Promise.reject(new Error("no opener configured")));return{status:()=>({appVersion:APP_VERSION,clientVersion:e.clientVersion,apiBase:e.apiBase,keyConfigured:Boolean(e.apiKey),keyMask:maskKey(e.apiKey),providerConfigured:l()}),setApiKey:t=>{try{const r=t&&t.key;return e.setApiKey(r||""),n&&n(e.apiKey),{ok:!0,keyConfigured:Boolean(e.apiKey),keyMask:maskKey(e.apiKey)}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},verifyApiKey:async()=>{try{return{ok:!0,...await e.verifyApiKey()}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},tokenBankBalance:()=>e.tokenBankBalance(),billingCheckout:()=>billingResult(()=>e.billingCheckout()),tokenBankTopup:async t=>{const n=parseTopupAmount(t&&t.amountEur);if(!n.ok)return{ok:!1,url:null,status:400,reason:n.message,setupRequired:!1,upgrade:null};const r=await startTopup(e,n.amount);return!0===r.ok&&r.url&&watchTopupCredit(e),{ok:!0===r.ok,url:r.url,status:r.status,reason:r.ok?null:r.hint?`${r.message} — ${r.hint}`:r.message,setupRequired:r.setupRequired,upgrade:null}},listModels:()=>e.listModels(),chatCompletion:t=>e.chatCompletion({prompt:t&&t.prompt,system:t&&t.system,model:t&&t.model,mode:t&&t.mode,maxTokens:t&&t.maxTokens,stream:t&&t.stream,onStream:t&&t.onStream}),fingerprintStatus:()=>c.status(),fingerprintKeygen:e=>c.keygen(e||{}),fingerprintMint:e=>c.mint(e||{}),fingerprintVerify:e=>c.verify(e||{}),fingerprintBackup:e=>c.backup(e||{}),
5
5
  // gdrive:AEGIS-AGPL/records and writes the `.anchor.json` link beside the
6
- fingerprintPublish:e=>c.publish(e||{}),fingerprintAnchor:e=>c.anchor(e||{}),fingerprintVault:()=>c.vaultList(),fingerprintVaultAudit:()=>c.vaultAudit(),byokStatus:()=>e.byokStatus(),byokSet:t=>e.byokSet(t&&t.provider,t&&t.apiKey),memorySearch:r=>{const n=s&&"function"==typeof s.capabilities?s.capabilities():null,o=r&&r.limit,a=Number.isFinite(o)?o:n&&Number.isFinite(n.recallEntries)?n.recallEntries:void 0;return normalizeMemoryReadWithFallback(e.memorySearch(r&&r.query,a),memoryIndex(t),r&&r.query,a)},memorySave:r=>saveMemoryWithQueue(e,t,r&&r.entry,s,memoryIndex(t)),memoryList:r=>normalizeMemoryReadWithFallback(e.memoryList(r&&r.limit),memoryIndex(t),"",r&&r.limit),verifyToken:t=>e.verifyToken(t&&t.token),memoryActivate:t=>e.memoryActivate(t&&t.token),memoryPull:r=>indexPulledMemory(e.memoryPull(r&&r.since),memoryIndex(t)),memorySaveBatch:t=>e.memorySaveBatch(t&&t.entries),memoryImport:r=>importForeignMemory(e,t,r,s,memoryIndex(t)),sessionsImportScan:()=>importForeignSessions(t,{confirm:!1}),sessionsImport:e=>importForeignSessions(t,e),importConversation:t=>e.importConversation(t||{}),personaRead:()=>{if(!s)return{ok:!1,reason:"no avatar store in this build"};try{const e=s.readPersona();return{ok:!0,persona:e.persona,warnings:e.warnings||[],capabilities:"function"==typeof s.capabilities?s.capabilities():null}}catch(e){return{ok:!1,reason:errorText(e)}}},personaPatch:e=>{if(!s)return{ok:!1,reason:"no avatar store in this build"};const t=e&&e.patch;if(!t||"object"!=typeof t)return{ok:!1,reason:"no patch"};try{const e=s.writePersona(t);return{ok:!0,saved:!0,persona:e.persona,warnings:e.warnings||[]}}catch(e){return{ok:!1,reason:errorText(e)}}},openExternal:e=>{const t=e&&e.url;return isSafeExternalUrl(t)?Promise.resolve(u(t)).then(()=>({ok:!0}),e=>({ok:!1,reason:errorText(e)})):Promise.resolve({ok:!1,reason:"unsupported URL scheme"})}}}function withReplyNotify(e,t,r){return r?e.then(e=>(r(t,e),e)):e}function registerIpc(e,t,r,n,o,s,a,i,c){const l=createIpcDispatch(t,r,n,o,a,c,i);for(const[t,r]of Object.entries(l))"chatCompletion"!==t?e.handle(`aegis:${t}`,(e,t)=>r(t)):e.handle(`aegis:${t}`,(e,t)=>{const n={...t||{}};if(!n.stream)return withReplyNotify(r(n),e,s);const o=e&&e.sender;return withReplyNotify(r({...n,stream:!0,onStream:e=>{o&&"function"==typeof o.send&&!o.isDestroyed()&&o.send("aegis:chatDelta",taggedChunk(e,n.sessionId))}}),e,s)});return l}function createAccentDispatch(e){if(!e)throw new Error("createAccentDispatch requires a settings store");return{getAccent:()=>({name:e.getAccent()}),setAccent:t=>{const r=t&&t.name;return"string"!=typeof r?{name:e.getAccent()}:{name:e.setAccent(r)}}}}function createFontScaleDispatch(e){if(!e)throw new Error("createFontScaleDispatch requires a settings store");return{getFontScale:()=>({scale:e.getFontScale()}),setFontScale:t=>{const r=t&&t.scale;return"number"!=typeof r?{scale:e.getFontScale()}:{scale:e.setFontScale(r)}}}}function createConfirmModeDispatch(e){if(!e)throw new Error("createConfirmModeDispatch requires a settings store");return{getConfirmMode:()=>({enabled:e.getConfirmMode()}),setConfirmMode:t=>{const r=t&&t.enabled;return"boolean"!=typeof r?{enabled:e.getConfirmMode()}:{enabled:e.setConfirmMode(r)}}}}function createDevModeDispatch(e){if(!e)throw new Error("createDevModeDispatch requires a settings store");return{getDevMode:()=>({enabled:e.getDevMode()}),setDevMode:t=>{const r=t&&t.enabled;return"boolean"!=typeof r?{enabled:e.getDevMode()}:{enabled:e.setDevMode(r)}},getAccountUsername:()=>({username:e.getAccountUsername()}),setAccountUsername:t=>{const r=t&&"string"==typeof t.username?t.username:null;return{username:e.setAccountUsername(r)}}}}function createModelAutoSyncDispatch(e,t){if(!e)throw new Error("createModelAutoSyncDispatch requires a settings store");return{getModelAutoSync:()=>{const e=t&&"function"==typeof t.modelAutoSyncStatus?t.modelAutoSyncStatus():{enabled:!1};return{enabled:Boolean(e&&e.enabled),status:e}},setModelAutoSync:r=>{const n=r&&r.enabled;if("boolean"!=typeof n){const e=t&&"function"==typeof t.modelAutoSyncStatus?t.modelAutoSyncStatus():{enabled:!1};return{enabled:Boolean(e&&e.enabled),status:e}}return e.setSharedPref("modelAutoSync",n),{enabled:n,status:t&&"function"==typeof t.modelAutoSyncStatus?t.modelAutoSyncStatus():{enabled:n}}}}}function createPermissionModeDispatch(e){if(!e)throw new Error("createPermissionModeDispatch requires a settings store");return{getPermissionMode:()=>({mode:e.getPermissionMode()}),setPermissionMode:t=>{const r=t&&t.mode;return"plan"!==r&&null!=r?{mode:e.getPermissionMode()}:{mode:e.setPermissionMode("plan"===r?"plan":null)}}}}function withAutoRoundsSwitch(e,t){const r=e.setConfirmMode;return{...e,setConfirmMode:e=>{const n=r(e);return e&&"boolean"==typeof e.enabled&&t&&"function"==typeof t.setAutoRounds&&t.setAutoRounds(!1===e.enabled),n}}}function createPermRulesDispatch(e){if(!e)throw new Error("createPermRulesDispatch requires a rule store");const t=(e,t)=>{try{return e()}catch(e){return{...t,ok:!1,reason:e&&e.message||String(e)}}};return{permRulesList:()=>t(()=>e.listRules(),{}),permRulesAdd:r=>{const n=r&&r.list,o=r&&r.rule;return"string"!=typeof n||"string"!=typeof o?t(()=>e.listRules(),{reason:"a rule needs a list and a pattern"}):t(()=>e.addRule(n,o),{})},permRulesRemove:r=>{const n=r&&r.list,o=r&&r.rule;return"string"!=typeof n||"string"!=typeof o?t(()=>e.listRules(),{reason:"a rule needs a list and a pattern"}):t(()=>e.removeRule(n,o),{})}}}function createCliFaceDispatch(e){const t=e||{},r=t.face||require("./lib/local/cli-face.js"),n=t.platform||require("./vendor/platform.js"),o=t.spawn||require("node:child_process").spawn,s=e=>{try{return Boolean(n.resolveExecutable(e,{platform:t.hostPlatform||process.platform,env:t.env||process.env}))}catch{return!1}},a=t.entryExists||(e=>{try{return require("node:fs").existsSync(e)}catch{return!1}});return{openCliFace:e=>{const n=t.appInfo||{};let i;try{i=r.plan({packaged:n.packaged,resourcesPath:n.resourcesPath,appDir:n.appDir,execPath:n.execPath,nodePath:n.nodePath,platform:t.hostPlatform||process.platform,exists:s,entryExists:a,args:e&&Array.isArray(e.args)?e.args:[]})}catch(e){return{ok:!1,reason:`could not plan the terminal face: ${e&&e.message||e}`,command:r.CLI_BIN}}if(!i||!i.ok)return{ok:!1,reason:i&&i.reason||"could not open a terminal",command:i&&i.command||r.CLI_BIN};try{const e=o(i.exec,i.args,{detached:!0,stdio:"ignore",env:Object.assign({},t.env||process.env,i.env||{})});e&&"function"==typeof e.unref&&e.unref()}catch(e){return{ok:!1,reason:`could not start ${i.exec}: ${e&&e.message||e}`,command:i.command}}return{ok:!0,emulator:i.exec,command:i.command}}}}function createPtyIpc(e,t){const r=t||{},n=r.ptyHostModule||require("./lib/local/pty-host.js"),o=void 0!==r.nodePty?r.nodePty:n.probeNodePty(),s=n.createPtyHost({nativePty:Boolean(o),appInfo:r.appInfo,spawnPty:o?(e,t)=>o.spawn(e[0],e.slice(1),{name:"xterm-color",cols:t.cols||80,rows:t.rows||24,cwd:t.cwd||process.cwd(),env:Object.assign({},process.env,t.env||{})}):void 0});return e.handle("aegis:ptyHello",(e,t)=>s.hello(t&&t.id||0)),e.handle("aegis:ptyExec",(e,t)=>{const r=t||{},n=e&&e.sender;return s.exec(r.id,r.params,e=>{n&&!n.isDestroyed()&&n.send("aegis:ptyEvent",e)})}),e.handle("aegis:ptyWrite",(e,t)=>{const r=t||{};return s.write(r.id,r.data)}),e.handle("aegis:ptyResize",(e,t)=>{const r=t||{};return s.resize(r.id,r.cols,r.rows)}),e.handle("aegis:ptyCancel",(e,t)=>s.cancel((t||{}).id)),s}function createSandboxPolicyDispatch(e,t,r){if(!e)throw new Error("createSandboxPolicyDispatch requires a settings store");const n=t||{},o=(Array.isArray(n.MODES)?n.MODES:["off","read-only","workspace-write","managed"]).filter(e=>"managed"!==e),s=r&&r.appDir,a=()=>{const t=e.getSandboxPolicy(),r=t&&o.includes(t.mode)?t.mode:"workspace-write",a=t&&"open"===t.network?"open":"restricted";let i=null,c=null,l=null;try{const e=(e=>{const t=n.detectCached||n.detect;if("function"!=typeof t||"function"!=typeof n.describe)return null;try{const r=t({appDir:s}),o=n.describe(r,e);return{mechanism:r&&(r.mechanism||(r.path?"bwrap":null))||null,enforced:Boolean(r&&r.available)&&"off"!==e.mode,sentence:"string"==typeof o?o:null}}catch{return{mechanism:null,enforced:null,sentence:null}}})("function"==typeof n.normalize?n.normalize(t,void 0):{mode:r,network:a});e&&({sentence:i,enforced:c,mechanism:l}=e)}catch{}return{ok:!0,mode:r,network:a,modes:o,stored:!!t,sentence:i,enforced:c,mechanism:l}};return{getSandboxPolicy:()=>a(),setSandboxPolicy:t=>{const r=t&&t.mode,i=t&&t.network;if("string"!=typeof r||!o.includes(r))return a();if(void 0!==i&&"open"!==i&&"restricted"!==i)return a();const c=e.getSandboxPolicy(),l=c&&c.fileSystem&&Array.isArray(c.fileSystem.entries)?{entries:c.fileSystem.entries}:{entries:[]},u=void 0===i?c&&"open"===c.network?"open":"restricted":i;try{e.setSandboxPolicy({mode:r,fileSystem:l,network:u})}catch{return a()}if("function"==typeof n.invalidateProbe)try{n.invalidateProbe(s)}catch{}return a()}}}function registerConfirmModeIpc(e,t){for(const[r,n]of Object.entries(t))e.handle(`aegis:${r}`,(e,t)=>n(t));return t}function createVaultBackendDispatch(e){if(!e)throw new Error("createVaultBackendDispatch requires a settings store");return{getVaultBackend:()=>e.vaultBackendConfig(),setVaultBackend:t=>e.setVaultBackendConfig(t&&t.backend)}}function createTelemetryDispatch(e){const t=e||null;return{telemetryEvent:e=>{try{if(!t||"function"!=typeof t.record)return{ok:!1,reason:"telemetry off"};const r=e&&"object"==typeof e?e:{};return t.record(r.event,{campaign:r.campaign,surface:r.surface})?{ok:!0}:{ok:!1,reason:"not an allowlisted funnel event"}}catch(e){return{ok:!1,reason:errorText(e)}}},telemetryReport:()=>{try{return t&&"function"==typeof t.report?t.report():{enabled:!1,transport:"off"}}catch(e){return{enabled:!1,error:errorText(e)}}}}}function createCovenantDispatch(e){return{covenantStatus:()=>({ok:!0,covenant:e.snapshot(),gapReport:e.gapReport()}),covenantGapReport:()=>({ok:!0,gapReport:e.gapReport()})}}function registerCovenantIpc(e,t){for(const[r,n]of Object.entries(t))e.handle(`aegis:${r}`,(e,t)=>n(t));return t}function registerTelemetryIpc(e,t){for(const[r,n]of Object.entries(t))e.handle(`aegis:${r}`,(e,t)=>n(t));return t}function safeExportBasename(e){return(e&&(e.title||e.id)||"session").replace(/[^\w.-]+/g,"_").slice(0,80)||"session"}function createExportDispatch(e,t,r,n){return{exportSession:async o=>{const s=o&&o.sessionId,a=o&&"json"===o.format?"json":"markdown",i=s?e.getSession(t,s):null;if(!i)return{ok:!1,reason:"session not found"};const c="json"===a?e.toJson(i):e.toMarkdown(i),l="json"===a?"json":"md",u="json"===a?[{name:"JSON",extensions:["json"]}]:[{name:"Markdown",extensions:["md"]}],d=await r({defaultPath:`${safeExportBasename(i)}.${l}`,filters:u});if(!d||d.canceled||!d.filePath)return{ok:!1,canceled:!0};try{await n(d.filePath,c)}catch(e){return{ok:!1,reason:errorText(e)}}return{ok:!0,filePath:d.filePath}}}}function registerExportIpc(e,t,r,n,o){const s=createExportDispatch(t,r,n,o);for(const[t,r]of Object.entries(s))e.handle(`aegis:${t}`,(e,t)=>r(t));return s}function createQuickLauncherDispatch(e,t={}){const r=Boolean(t.isPackaged),n=t.applyConfig||(()=>({active:!1,reason:null})),o=t.pushToMain||(()=>({ok:!1,reason:"no main window"}));let s={active:!1,reason:null};return{status:function(){return{...e.quickLauncherConfig(),packaged:r,...s}},setConfig:function(t){const o=e.setQuickLauncherConfig({enabled:t&&t.enabled,shortcut:t&&t.shortcut});return s=n(o)||{active:!1,reason:null},{...o,packaged:r,...s}},pushToMain:(e,t)=>o(e,t)}}function registerQuickLauncherIpc(e,t){for(const[r,n]of Object.entries(t))"pushToMain"!==r?e.handle(`quick:${r}`,(e,t)=>n(t)):e.handle(`quick:${r}`,(e,t)=>n(t,e));return t}function resolveUserDataDir(e){if(e&&"function"==typeof e.getPath)try{return e.getPath("userData")}catch{}try{const e=require("../one/src/iface/paths.js").plan({platform:process.platform,env:process.env});if(e&&e.ok)return e.state}catch{}return path.join(os.homedir(),".aegiscode")}function createEngine(e,{app:t,safeStorage:r,dir:n,sessionsDir:o}={}){const s=n||resolveUserDataDir(t),a=createSettingsStore({dir:s,safeStorage:r}),i=avatarStore.createAvatarStore({dir:s,log:()=>{}});try{i.verifyAtBoot()}catch(e){console.error("aegis: avatar carve-out violation",e&&e.message)}a.migrateLegacyAegisKey();const c=()=>{try{return i.capabilities()}catch{return null}};return{engine:createLocalEngine({aegis:e,settings:a,recallProvider:({system:e})=>require("./lib/avatar/turn.js").composeSystemPrompt(e,{capabilities:c(),persona:i.readPersona().persona,deep:!1}).system,sandbox:{policy:()=>"function"==typeof a.getSandboxPolicy?a.getSandboxPolicy():null,strict:!1,appDir:__dirname},permissionRules:{rulesVerdict:require("./lib/local/perm-rules.js").rulesVerdict,subjectFor:require("./lib/local/perm-rules.js").subjectFor,alwaysAllow:require("./lib/local/perm-write.js").alwaysAllow}}),sessionsDir:o||sessionStore.resolveStoreDir(s),settingsDir:s,settings:a,avatar:i}}const PREVIEW_READ_MAX_BYTES=524288;function readTextFileForPreview(e){try{const t=e&&"string"==typeof e.file?e.file:"",r=e&&"string"==typeof e.cwd?e.cwd:"";if(!t||!r||!path.isAbsolute(r))return null;const n=fs.realpathSync(r),o=fs.realpathSync(path.resolve(n,t)),s=path.relative(n,o);if(""===s||s.startsWith("..")||path.isAbsolute(s))return null;const a=fs.statSync(o);if(!a.isFile())return null;if(a.size<=524288)return{text:fs.readFileSync(o,"utf8"),truncated:!1};const i=fs.openSync(o,"r");try{const e=Buffer.alloc(524288),t=fs.readSync(i,e,0,524288,0);let r=e.toString("utf8",0,t);const n=r.lastIndexOf("\n");return n>0&&(r=r.slice(0,n+1)),{text:r,truncated:!0}}finally{fs.closeSync(i)}}catch{return null}}const attachmentsModule=require("./lib/local/attachments.js");function nativeImageResizer(e,t){try{const{nativeImage:r}=require("electron");if(!r)return null;const n=r.createFromBuffer(e);if(!n||n.isEmpty())return null;const o=n.getSize(),s=Math.max(o.width,o.height),a=s>1568?n.resize({width:Math.round(1568*o.width/s)}):n,i="image/png"===t?a.toPNG():a.toJPEG(82);return i&&i.length?{buffer:i,mime:"image/png"===t?"image/png":"image/jpeg"}:null}catch{return null}}function ingestAttachment(e,{resize:t=nativeImageResizer}={}){const r=e&&"string"==typeof e.path?e.path.trim():"";if(!r)return{ok:!1,reason:"no path"};if(!path.isAbsolute(r))return{ok:!1,reason:"not an absolute path"};let n,o,s;try{n=fs.realpathSync(r),o=fs.statSync(n)}catch{return{ok:!1,reason:"not found"}}if(!o.isFile())return{ok:!1,reason:"not a regular file"};if(0===o.size)return{ok:!1,reason:"empty file"};if(o.size>attachmentsModule.MAX_FILE_BYTES)return{ok:!1,reason:`too large (${attachmentsModule.humanBytes(o.size)})`};try{s=fs.readFileSync(n)}catch{return{ok:!1,reason:"unreadable"}}const a=attachmentsModule.sniff(s),i={path:n,name:path.basename(n),size:o.size,mime:a.mime,kind:a.kind};if("image"===a.kind){let{mime:e}=a,r=s,n=!1;if(r.length>attachmentsModule.MAX_IMAGE_BYTES&&"function"==typeof t){const o=t(s,e);o&&o.buffer&&o.buffer.length<r.length&&(r=o.buffer,e=o.mime,n=!0)}const o=attachmentsModule.toDataUrl(r,e);return o?{ok:!0,attachment:{...i,kind:"image",mime:e,size:r.length,dataUrl:o,scaled:n,vision:attachmentsModule.isVisionMime(e)}}:{ok:!1,reason:"could not encode image"}}if("text"===a.kind){if(o.size>attachmentsModule.MAX_TEXT_BYTES){let e=s.subarray(0,attachmentsModule.MAX_TEXT_BYTES).toString("utf8");const t=e.lastIndexOf("\n");return t>0&&(e=e.slice(0,t+1)),{ok:!0,attachment:{...i,kind:"text",text:e,truncated:!0}}}return{ok:!0,attachment:{...i,kind:"text",text:s.toString("utf8"),truncated:!1}}}return"pdf"===a.kind?{ok:!0,attachment:{...i,kind:"pdf"}}:{ok:!0,attachment:{...i,kind:"binary"}}}function createModelDispatch(e,{env:t=process.env,settings:r}={}){const n=new Map;let o,s=autoRoundsDefault(t),a=!1;const i=()=>{const t=r||e&&e.settings||null,n=e=>"boolean"==typeof e?e:void 0;let i;try{if(t&&"function"==typeof t.confirmModeState){const e=t.confirmModeState();i=n(e&&e.enabled)}void 0===i&&t&&"function"==typeof t.getConfirmMode&&(i=n(t.getConfirmMode()))}catch{}return a||void 0===i||(void 0===o?o=i:i!==o&&(a=!0,s=!0)),!(!s||!t||void 0===i)&&!1===i},c={listClasses:async()=>(await e.listClasses()).filter(e=>DESKTOP_CLASSES.includes(e.class)),listModels:t=>e.listModels(t&&t.class),chat:r=>{const o=r&&r.onStream;if("function"!=typeof o)return e.chat(r,o);const s=r&&r.sessionId||"";return e.chat(r,r=>{if(r&&r.rounds&&r.rounds.id&&i()){const a=autoContinuePlan({on:!0,used:n.get(s)||0,limit:autoContinueLimit(t)});if(n.set(s,a.used),a.auto){const t="function"==typeof e.respondRoundsAsk?e.respondRoundsAsk(r.rounds.id,!0):{ok:!1};if(t&&t.ok){const e=Number(r.rounds.spent)||0;return void o({note:`auto mode: the ${e}-round limit was reached — continuing automatically (${a.used}/${a.cap}, then it asks).`})}}}o(r)})},"settings.get":()=>e.settings.list().filter(e=>!(e&&isReservedNamespace(e.provider))),"settings.set":t=>e.settings.set(t&&t.provider,{baseURL:t&&t.baseURL,key:t&&t.key}),"settings.remove":t=>e.settings.remove(t&&t.provider),"userModels.get":()=>e.userModels(),"userModels.add":t=>e.addUserModel(t&&t.provider,t&&t.model),"userModels.remove":t=>e.removeUserModel(t&&t.provider,t&&t.model),"userModels.discover":t=>e.discoverModels(t&&t.provider),"userModels.addAll":t=>e.addUserModels(t&&t.provider,t&&t.ids),"userModels.canDiscover":t=>Boolean(e.canDiscoverModels(t&&t.provider)),"userModels.discoverable":()=>e.discoverableProviders(),"userModels.syncPlan":t=>e.modelSyncPlan(t&&t.only),"userModels.syncApply":t=>e.modelSyncApply(t&&t.plan,t&&t.only),"userModels.syncStatus":()=>e.modelAutoSyncStatus(),"userModels.syncNow":t=>e.modelAutoSyncRun(t&&t.only),"memoryPersist.get":()=>e.settings.memoryPersistState(),"memoryPersist.set":t=>e.settings.setMemoryPersist(Boolean(t&&t.enabled)),cancel:t=>e.cancel(t&&t.sessionId),respondApproval:t=>e.respondApproval(t&&t.approvalId,t&&t.decision),respondRoundsAsk:t=>"function"==typeof e.respondRoundsAsk?e.respondRoundsAsk(t&&t.roundsAskId,t&&t.decision):{ok:!1},clearApprovals:t=>e.clearSessionApprovals(t&&t.sessionId),listUndoable:t=>"function"==typeof e.listUndoable?e.listUndoable(t&&t.sessionId):[],undoMutation:t=>"function"==typeof e.undoMutation?e.undoMutation(t&&t.sessionId,t&&t.id):{ok:!1,error:"undo is not available on this engine"}};return Object.defineProperties(c,{autoRoundsOn:{value:i,enumerable:!1},setAutoRounds:{value:e=>{s=Boolean(e),a=!0},enumerable:!1}}),c}function createSyncDispatch(e,t,r,n,o){let s=null;function a(){return Boolean(r&&r.apiKey)}async function i(){const n=e.listPending(t);if(!a())return{ok:!1,queued:n.length,reason:"no AEGIS key configured"};const o=await async function(){const e=memoryQueue.listQueued(t);if(!e.length)return{flushed:0,remaining:0,upgrade:null};const n=[];let o=0,s=null;for(let a=0;a<e.length;a+=1)try{await r.memorySave(e[a]),o+=1;const n=memoryIndex(t);if(n)try{n.upsert(e[a])}catch{}}catch(t){const r=upgradeInfo(t);if(r){s=r,n.push(...e.slice(a));break}n.push(e[a])}return memoryQueue.save(t,n),{flushed:o,remaining:n.length,upgrade:s}}();if(!n.length)return{ok:!0,queued:0,pushed:0,memoryFlushed:o.flushed,upgrade:o.upgrade};let i=0,c=null,l=null;for(const o of n)try{const n=await r.conversationSyncPush({session_id:o.id,title:o.title,messages:o.messages}),s=n&&(n.session_id||n.id);e.markSynced(t,o.id,{remoteId:s}),i+=1}catch(e){if(c=e,l=describeSyncError(e),"quota"===l.kind||"auth"===l.kind)break}const u=e.listPending(t).length;i&&(s=Date.now());const d=(c?upgradeInfo(c):null)||o.upgrade;return 0===i&&c?{ok:!1,queued:u,reason:syncErrorReason(l),failed:l?[l]:[],kind:l?l.kind:"error",status:l?l.status:0,hint:l?l.hint:null,memoryFlushed:o.flushed,upgrade:d}:{ok:!0,queued:u,pushed:i,failed:l?[l]:[],memoryFlushed:o.flushed,upgrade:d}}const c=persistGate.createAutoPush({push:i,dir:n||t}),l=["id","title","updatedAt","pending","named","seq","cwd","dir","origin","remoteId","lastSyncedAt"];return{auto:()=>c.auto(),memoryPersistState:()=>c.gate(),listSessions:()=>{return{sessions:(r=e.listSessions(t),(Array.isArray(r)?r:[]).filter(e=>e&&e.id).map(e=>{const t={};for(const r of l)void 0!==e[r]&&(t[r]=e[r]);const r=Array.isArray(e.messages)?e.messages:[];t.messages=r.length;const n=r.find(e=>e&&"user"===e.role&&e.content);return t.firstPrompt=n?String(n.content):"",t}))};var r},searchSessions:r=>{const n=r&&"string"==typeof r.query?r.query:"",o=Number.isInteger(r&&r.limit)?r.limit:50,s=Math.max(1,o),a=e.listSessions(t)||[],i=sessionSearch.rankSessions(n,a).slice(0,s);let c=[],l=0,u="ok";try{const e=memoryIndex(t);if(e){const t=e.search(n,{limit:s});t&&t.ok?(c=(t.results||[]).map(e=>({id:e.id,content:e.body||"",scope:e.scope||"",tags:Array.isArray(e.tags)?e.tags:[],updated:e.updated||null})),l=e.count()):u="error"}else u=memoryStore.isAvailable()&&t?"error":"unavailable"}catch{c=[],l=0,u="error"}return{query:n,total:a.length,memoryStatus:u,memoryTotal:l,memory:c,sessions:i.map(e=>({id:e&&e.id,title:e&&e.title||e&&e.id||"untitled",updatedAt:e&&e.updatedAt||null,messages:e&&Array.isArray(e.messages)?e.messages.map(e=>({role:e&&e.role,content:"string"==typeof(e&&e.content)?e.content.slice(0,400):""})):[],reason:sessionSearch.matchReason(n,e)}))}},open:r=>e.getSession(t,r&&r.sessionId),save:r=>e.upsertSession(t,r||{}),append:r=>e.appendMessage(t,r&&r.sessionId,r&&r.message),delete:r=>e.deleteSession(t,r&&r.sessionId),rename:r=>e.renameSession(t,r&&r.sessionId,r&&r.title),nameSession:async r=>{const n=r&&r.sessionId,s=r&&r.prompt;if(!n||!String(null==s?"":s).trim())return null;let a;for(const e of["../client/naming.js","./vendor/naming.js","./vendor/client/naming.js"])try{a=require(e);break}catch{}if(!a)return null;const i=async(e,t={})=>{if(!o||"function"!=typeof o.chat)return null;try{const s=await o.chat({class:r&&r.class||"aegis",model:r&&r.model,prompt:e,system:t.system,maxTokens:64,sessionId:`${n}:naming`,tools:!1}),a=s&&s.choices&&s.choices[0]||{};return a.message&&a.message.content||null}catch{return null}};try{return await a.nameSession(e.namingStore,t,n,s,{callModel:i})}catch{return null}},push:i,pull:async function(){if(!a())return{ok:!1,merged:0,reason:"no AEGIS key configured"};try{const n=await r.conversationSyncPull(),o=e.mergeRemoteSessions(t,n&&n.sessions||[]);return s=Date.now(),{ok:!0,merged:o,failed:[],upgrade:null}}catch(e){const t=describeSyncError(e);return{ok:!1,merged:0,reason:syncErrorReason(t),failed:[t],kind:t.kind,status:t.status,hint:t.hint,upgrade:upgradeInfo(e)}}},status:()=>({count:e.listSessions(t).length,pending:e.listPending(t).length,cloud:a(),lastSyncAt:s})}}const HEARTBEAT_RETRY_BASE_MS=5e3,HEARTBEAT_RETRY_MAX_MS=3e4;function createHeartbeatRetry(e,t={}){const r="function"==typeof t.now?t.now:()=>Date.now(),n=Number(t.baseMs)>0?Number(t.baseMs):5e3,o=Number(t.maxMs)>0?Number(t.maxMs):3e4;let s=0,a=0,i=null,c=!1;function l(e){s+=1;const t=Math.min(o,n*2**Math.max(0,s-1));return i=e||"push failed",a=r()+t,{attempted:!0,ok:!1,error:i,failures:s,retryInMs:t}}return{run:async function(){const t=r();if(s>0&&t<a)return{attempted:!1,ok:!1,error:i,failures:s,retryInMs:a-t};if(c)return{attempted:!1,ok:!1,error:i,failures:s,retryInMs:0};c=!0;try{const t=await e();return t&&!1===t.ok?l(t.reason||t.kind||"push failed"):(s=0,a=0,i=null,{attempted:!0,ok:!0,error:null,failures:0,retryInMs:0,result:t})}catch(e){return l(errorText(e))}finally{c=!1}},state:function(){const e=r();return{failures:s,lastError:i,retryInMs:s>0&&a>e?a-e:0}},recordFailure:e=>l(errorText(e))}}function registerModelIpc(e,t,r,n,o,s,a,i){const c=createModelDispatch(t),l=createSyncDispatch(sessionStore,r,n,a,c),u=createHeartbeatRetry(()=>l.push(),s);function d(){const e=u.run();e&&"function"==typeof e.catch&&e.catch(e=>u.recordFailure(e))}for(const[t,r]of Object.entries(c))"chat"!==t?"listModels"!==t?e.handle(`model:${t}`,(e,t)=>r(t)):e.handle(`model:${t}`,(e,t)=>(d(),r(t))):e.handle(`model:${t}`,(e,t)=>{const n={...t||{}},s=!0===n.bestEffort;delete n.bestEffort;const a="low"===n.effort||"medium"===n.effort||"max"===n.effort?n.effort:"high";n.effort=a;const c=e&&e.sender,l=n.class||"model",u=r({...n,onStream:e=>{c&&"function"==typeof c.send&&!c.isDestroyed()&&c.send("aegis:chatDelta",taggedChunk(e,n.sessionId))}});return s?u.then(t=>(o&&o(e,t),t),e=>{const t=e&&"number"==typeof e.status?e.status:0,r=e&&e.code||"";return backgroundLaneLogs(i)&&console.warn(`[model] background ${l} turn produced no answer: ${errorText(e)}${t?` (status ${t})`:""}${r?` [${r}]`:""}`),{bestEffortFailed:!0,status:t,code:r||void 0,message:errorText(e),choices:[{message:{content:""}}]}}):withReplyNotify(u,e,o).catch(e=>{if(isAbortShapedError(e))return backgroundLaneLogs(i)&&console.warn(`[model] ${l} turn stopped before it finished: ${errorText(e)} [ABORT_ERR]`),abortedTurnPayload(e);const t=e&&"number"==typeof e.status?e.status:0,r=e&&e.code||"";return backgroundLaneLogs(i)&&console.error(`[model] ${l} turn failed: ${errorText(e)}${t?` (status ${t})`:""}${r?` [${r}]`:""}`,e&&e.stack?e.stack:""),{providerFailed:!0,status:t,code:r||void 0,message:errorText(e),choices:[{message:{content:""}}]}})});e.on("model:readTextFile",(e,t)=>{e.returnValue=readTextFileForPreview(t)}),e.handle("aegis:attachments:ingest",async(e,t)=>ingestAttachment(t));for(const[t,r]of Object.entries(l))"status"!==t?e.handle(`sync:${t}`,(e,t)=>r(t)):e.handle(`sync:${t}`,(e,t)=>{d();const n=r(t);return n&&"object"==typeof n?{...n,retry:u.state()}:n});return{modelDispatch:c,syncDispatch:l,heartbeat:u}}function createQueueEngine(e,t){return createLocalEngine({aegis:e,settings:t,getConfirmMode:()=>!1})}function queueEngineWithDeniedApprovals(e){return e&&"function"==typeof e.chat?{...e,chat:(t,r)=>e.chat(t,t=>{(t=>{const r=t&&t.approval;if(r&&r.id&&"function"==typeof e.respondApproval)try{e.respondApproval(r.id,"deny")}catch{}})(t),(t=>{const r=t&&t.rounds;if(r&&r.id&&"function"==typeof e.respondRoundsAsk)try{e.respondRoundsAsk(r.id,!1)}catch{}})(t),"function"==typeof r&&r(t)})}:e}function isExistingDir(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function clampInt(e,t,r){const n=Number(e);return!Number.isInteger(n)||n<t||n>r?null:n}function createQueueDispatch({engine:e,env:t=process.env,queue:r=queueModule,autonomous:n=autonomousModule,entitlement:o=entitlementModule.createEntitlement({}),log:s=()=>{}}={}){if(!e||"function"!=typeof e.chat)throw new Error("createQueueDispatch: a local engine with chat() is required");let a=null,i=!1,c=!1;const l=n.createQueueWorker({engine:queueEngineWithDeniedApprovals(e),env:t,log:e=>{e&&"start"===e.type&&(a=e.taskId),e&&"finish"===e.type&&(a=null),s(e)},canFanOut:()=>o.current().entitled});function u(){const e=r.loadQueue(t);return{ok:!0,items:e,pending:r.pendingCount(e),running:e.find(e=>e&&"running"===e.status)||null,draining:c,stopping:i,defaultCwd:process.cwd(),defaultModel:n.resolveModel({env:t}),queueFile:r.queuePath(t),runs:r.readRuns(t,{limit:20}),entitlement:o.current()}}const d=e=>(e||[]).map(e=>({id:e.id,ok:Boolean(e.ok),error:e.error||null}));return{enqueue:async e=>{await o.refresh();const s=o.gateFanout({workers:clampInt(e&&e.workers,1,8),fanout:Boolean(e&&!0===e.fanout)});if(!s.ok)return{...s,...u()};const{opts:a,error:i}=function(e){const t=e||{},r=String(null==t.task?"":t.task).trim();if(!r)return{error:"a queued task needs text"};if(r.length>8e3)return{error:`task text is too long (${r.length} > 8000 chars)`};const o=String(null==t.cwd?"":t.cwd).trim()||process.cwd();if(!path.isAbsolute(o))return{error:"the working directory must be an absolute path"};if(!isExistingDir(o))return{error:`not a directory: ${o}`};const s=n.normalizeClass(t.class),a=String(null==t.model?"":t.model).trim().slice(0,120)||null,i=n.modelRefusal(a,s);if(i)return{error:i};const c=String(null==t.effort?"":t.effort).trim().toLowerCase();return{opts:{task:r,cwd:o,class:s,model:a,effort:QUEUE_EFFORTS.has(c)?c:null,workers:clampInt(t.workers,1,8),maxRounds:clampInt(t.maxRounds,1,200),singlePass:!(!0===t.fanout||!0===t.autonomous),commit:Boolean(t.commit),source:"desktop"}}}(e);return i?{ok:!1,reason:i,...u()}:{ok:!0,item:r.addTask(t,a),...u()}},list:()=>u(),entitlement:async e=>(await o.refresh({force:Boolean(e&&!0===e.force)}),{ok:!0,...u()}),clear:e=>({...r.clearQueue(t,{all:Boolean(e&&e.all)}),ok:!0,...u()}),retry:e=>{const n=e&&e.id,o=r.retryTask(t,n);return o?{ok:!0,item:o,...u()}:{ok:!1,reason:`no task #${n}`,...u()}},remove:e=>{const n=e&&e.id,o=r.loadQueue(t),s=r.findTask(o,n);return s?"running"===s.status?{ok:!1,reason:`task #${s.id} is running — stop the drain first`,...u()}:(r.saveQueue(t,o.filter(e=>Number(e&&e.id)!==Number(s.id))),{ok:!0,removed:s.id,...u()}):{ok:!1,reason:`no task #${n}`,...u()}},drain:()=>async function(){if(c)return{ok:!1,reason:"a drain is already running in this window",...u()};let e;c=!0,i=!1;try{const t=await l.proceed({max:1});e=t.locked?{ok:!1,locked:!0,holder:t.holder,ran:[]}:{ok:!0,ran:d(t.ran)}}catch(t){e={ok:!1,reason:errorText(t),ran:[]}}return c=!1,a=null,{...e,...u()}}(),proceed:()=>async function(){if(c)return{ok:!1,reason:"a drain is already running in this window",...u()};c=!0,i=!1;const e=[];let t;try{for(;;){const r=await l.proceed({max:1});if(r.locked){t={ok:!1,locked:!0,holder:r.holder,ran:d(e)};break}if(!r.ran.length){t={ok:!0,stopped:i,ran:d(e)};break}if(e.push(...r.ran),i){t={ok:!0,stopped:!0,ran:d(e)};break}}}catch(r){t={ok:!1,reason:errorText(r),ran:d(e)}}return c=!1,a=null,{...t,...u()}}(),stop:e=>{i=!0;const t=e&&null!=e.id?e.id:a,r=null==t?null:l.cancel(t);return{ok:!0,wasDraining:c,cancelled:r,...u()}}}}function createAutoDispatch({autoDrain:e,autoMint:t}={}){if(!e||"function"!=typeof e.state)throw new Error("createAutoDispatch: the auto-drain automation is required");if(!t||"function"!=typeof t.state)throw new Error("createAutoDispatch: the auto-mint automation is required");return{autoStatus:()=>({ok:!0,drain:e.state(),mint:t.state()}),autoSetDrain:t=>{const r=t||{},n={};null!=r.enabled&&(n.enabled=Boolean(r.enabled)),null!=r.intervalMs&&(n.intervalMs=Number(r.intervalMs));try{return{ok:!0,drain:e.set(n)}}catch(e){return{ok:!1,error:errorText(e)}}},autoSetMint:e=>{const r=e||{},n={};null!=r.enabled&&(n.enabled=Boolean(r.enabled)),null!=r.publish&&(n.publish=Boolean(r.publish));try{return{ok:!0,mint:t.set(n)}}catch(e){return{ok:!1,error:errorText(e)}}},autoSealNow:async e=>{const r=e||{};null!=r.publish&&t.set({publish:Boolean(r.publish)});try{const e=await t.flush();return t.reset(),{ok:!0,...e}}catch(e){return t.reset(),{ok:!1,error:errorText(e)}}}}}function liveAppWindows(){try{const e=require("electron"),t=e&&e.BrowserWindow;return t&&"function"==typeof t.getAllWindows?t.getAllWindows().filter(e=>e&&"function"==typeof e.send&&!("function"==typeof e.isDestroyed&&e.isDestroyed())):[]}catch{return[]}}function registerQueueIpc(e,{engine:t,env:r,queue:n,autonomous:o,entitlement:s,aegis:a,windows:i=liveAppWindows}={}){let c=null;const l=s||entitlementModule.createEntitlement({probe:a&&"function"==typeof a.verifyApiKey?async()=>{const e=await a.verifyApiKey(),t=e&&"object"==typeof e?{...e}:{};if("function"==typeof a.tokenBankBalance)try{const e=await a.tokenBankBalance();e&&"object"==typeof e&&(null!=e.balance_micros?t.balance_micros=e.balance_micros:null!=e.balance_eur&&(t.balance_eur=e.balance_eur))}catch{}return t}:void 0}),u=()=>{let e=[];try{e=i()||[]}catch{e=[]}for(const t of e)try{t.send("queue:changed",{at:Date.now()})}catch{}},d=createQueueDispatch({engine:t,env:r,queue:n,autonomous:o,entitlement:l,log:e=>{e&&"finish"===e.type&&u(),c&&"function"==typeof c.send&&("function"==typeof c.isDestroyed&&c.isDestroyed()||c.send("queue:progress",e))}});for(const[t,r]of Object.entries(d))e.handle(`queue:${t}`,(e,n)=>{c=e&&e.sender||null;const o=r(n);return QUEUE_MUTATING_METHODS.has(t)?o&&"function"==typeof o.then?o.then(e=>(u(),e),e=>{throw u(),e}):(u(),o):o});return d}function registerAutoIpc(e,t){for(const[r,n]of Object.entries(t))e.handle(`auto:${r}`,(e,t)=>n(t));return t}const UPDATE_STATUS_CHANNEL="aegis:updateStatus",ACCOUNT_STATUS_CHANNEL="aegis:accountStatusChanged",UPDATE_CHECK_INTERVAL_MS=144e5,UPDATE_RETRY_BACKOFF_MS=[6e4,3e5,9e5,36e5];function describeRegistryFailure(e,t,r){switch(e){case"not-found":return`${r} is not published on the npm registry (404)`;case"forbidden":return`the npm registry refused the request (${t||"auth"})`;case"malformed":return"the npm registry sent a response this app could not read";case"too-large":return"the npm registry response was too large to read";case"timeout":return"the npm registry did not respond in time";case"network":return"the npm registry could not be reached";default:return"the update check did not complete"}}function resolveUpdateOwner({dir:e=__dirname,readJson:t=e=>JSON.parse(fs.readFileSync(e,"utf8"))}={}){const r=`${path.sep}vendor${path.sep}desktop`,n=String(e).lastIndexOf(r);if(n>0){const r=String(e).slice(0,n);try{const e=t(path.join(r,"package.json")).version;if(e)return{pkg:"aegisone",current:String(e),productDir:r}}catch{}}try{const r=t(path.join(e,"package.json")).version;if(r)return{pkg:"aegis-desktop",current:String(r),productDir:null}}catch{}return{pkg:"aegis-desktop",current:"unknown",productDir:null}}function installFailureText(e,t="the installer failed"){const r=String(null==e?"":e).split("\n").map(e=>e.replace(/^\s*npm\s+(error|ERR!)\s*/i,"").trim()).filter(Boolean).filter(e=>!/^A complete log of this run can be found/i.test(e)).filter(e=>!/^In most cases you or one of your dependencies/i.test(e)).filter(e=>!/^a package version that doesn't exist\.?$/i.test(e));if(!r.length)return t;const n=r.findIndex(e=>/^code\s+[A-Z]/i.test(e)),o=n>=0&&r[n+1]?r[n+1]:r[0],s=n>=0?r[n].replace(/^code\s+/i,""):"";return s?`${o} (${s})`:o}function createNpmUpdateManager({onStatus:e,packaged:t=!1,now:r=()=>Date.now(),fetchImpl:n,setTimeoutImpl:o=setTimeout,clearTimeoutImpl:s=clearTimeout,runUpgrade:a,relaunch:i,owner:c}={}){const l=c||resolveUpdateOwner(),u=l.pkg;let d=l.current,p={status:"idle",version:null,error:null,phase:null,channel:"npm",reason:null,transient:!1,attempts:0,retryInMs:0,command:null,plan:null,method:null,canDownload:!1,decomposed:!1};const m=t=>(p={...p,...t},e&&e(p),p);let f=null;try{f=require("../client/update.js")}catch{try{f=require("./vendor/update.js")}catch{f=null}}let g=0,h=0,y=null,k=null,b=null,v=null;function S(){y&&s(y),y=null}const w=(e,t)=>"function"==typeof f.isTransientReason?f.isTransientReason(e,t):"unknown"===e;let E=null;async function A({announce:e=!1}={}){if(!f)return m({status:"disabled",error:"update checker unavailable"});if(k)return k;k=(async()=>{const s=p.status,a=p.version;let i;m({status:"checking",error:null,reason:null,transient:!1,phase:null});try{i=await async function(){if(n)return n({pkg:u});if(f&&"function"==typeof f.checkPublished){const e=await f.checkPublished({current:d,pkg:u,now:r(),intervalMs:0});return e?{ok:e.ok,latest:e.latest,reason:e.reason,status:e.status}:{ok:!1,latest:null,reason:"unknown",status:null}}return{ok:!1,latest:null,reason:"unavailable",status:null}}()}catch(e){i={ok:!1,latest:null,reason:"unknown",status:null,error:errorText(e)}}if(i.ok){if(g=0,h=0,S(),await async function(){if(null!==E)return E;if(!f||"function"!=typeof f.serverUpdateVerdict)return null;try{const e=await f.serverUpdateVerdict({current:d});return e&&e.ok&&(E=Boolean(e.decomposed)),E}catch{return null}}())return m({status:"decomposed",version:i.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0,decomposed:!0});if(!f.isNewer(i.latest,d))return m({status:"up-to-date",version:i.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0});const e=function(){if(v)return v;const e=f&&f.detectInstallMethod;if("function"!=typeof e)return v="npm",v;try{v=e({env:process.env,argv:process.argv,pkg:u,entry:__dirname,fileExists:e=>fs.existsSync(path.resolve(__dirname,"..",e))})}catch{v="npm"}return v}(),r="function"==typeof f.updatePlan?f.updatePlan({current:d,latest:i.latest,behind:!0,channel:"npm",pkg:u,method:e}):null;return m({status:"available",version:i.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0,plan:r,method:e,command:t?`${i.latest} is published — reinstall aegis one from the installer to pick it up`:r&&r.instruction||`npm i -g ${u}@latest`,commandIsSentence:t||Boolean(r&&!r.apply),canDownload:Boolean(r&&r.apply)&&!t})}g+=1;const c=i.error||describeRegistryFailure(i.reason,i.status,u);return w(i.reason,i.status)?(function(){S();const e=UPDATE_RETRY_BACKOFF_MS[Math.min(Math.max(g-1,0),UPDATE_RETRY_BACKOFF_MS.length-1)];h=r()+e,y=o(()=>{y=null,A().catch(()=>{})},e),y&&y.unref&&y.unref(),m({retryInMs:e})}(),m(e?{status:"error",phase:"check",error:c,reason:i.reason,transient:!0,attempts:g}:{status:"available"===s?"available":"unavailable",version:a,error:c,reason:i.reason,transient:!0,attempts:g})):(S(),h=0,m({status:"error",phase:"check",error:c,reason:i.reason,transient:!1,attempts:g,retryInMs:0}))})();try{return await k}finally{k=null}}return{status:()=>p,check:A,download:async()=>{const e=!t&&p.plan&&p.plan.apply;if(!e)return m({status:"available"===p.status?"available":p.status,command:p.plan&&p.plan.instruction||p.command,canDownload:!1});m({status:"downloading",error:null,progress:0,phase:null});const r=await function(e){const t=a||((e,t)=>new Promise(r=>{execFile(e,t,{timeout:18e4,windowsHide:!0},(e,t,n)=>{if(e)return r({ok:!1,output:String(n||t||e.message||e)});r({ok:!0,output:String(t||"")})})})),r=!a&&f&&"function"==typeof f.installSpawn?f.installSpawn(e,{env:process.env}):null,n=r?r.command:e.command,o=r?r.args:e.args;return Promise.resolve(t(n,o)).then(e=>({ok:Boolean(e&&e.ok),output:String(e&&e.output||"")}),e=>({ok:!1,output:errorText(e)}))}(e);return r.ok?m({status:"downloaded",version:p.version,error:null,progress:100,command:`npm i -g ${u}@latest`,canDownload:!1}):m({status:"error",transient:!1,phase:"install",error:installFailureText(r.output),command:`${e.command} ${e.args.join(" ")}`})},quitAndInstall:()=>{"downloaded"===p.status&&(i||(()=>{try{const{app:e}=require("electron");e.relaunch(),e.exit(0)}catch{}}))()},start:()=>{A().catch(()=>{}),b=setInterval(()=>A().catch(()=>{}),144e5),b.unref&&b.unref()},stop:()=>{S(),b&&clearInterval(b),b=null},retryState:()=>({attempts:g,retryAt:h,inFlight:!!k,hasTimer:!!y})}}function createUpdateManager({isPackaged:e,onStatus:t}){let r={status:"idle",version:null,error:null,canDownload:!1};return createNpmUpdateManager({onStatus:function(e){r={...r,...e},t&&t(r)},packaged:Boolean(e)})}function createUpdateDispatch(e){return{checkForUpdates:()=>e.check({announce:!0}),downloadUpdate:()=>e.download(),quitAndInstallUpdate:()=>(e.quitAndInstall(),{ok:!0}),updateStatus:()=>Promise.resolve(e.status())}}function registerUpdateIpc(e,t){const r=createUpdateDispatch(t);for(const[t,n]of Object.entries(r))e.handle(`aegis:${t}`,(e,t)=>n(t));return r}let resolveTargetWindow=null;function sendToAppWindow(e,t){const r="function"==typeof resolveTargetWindow?resolveTargetWindow():null,n=r&&!r.isDestroyed()?r:e.getFocusedWindow()||e.getAllWindows()[0];n&&!n.isDestroyed()&&n.webContents.send(t)}function sendDeepLinkToWindow(e,t){if(!e||e.isDestroyed()||!t)return;const r=()=>{e.isDestroyed()||e.webContents.send("aegis:deepLink",t)};e.webContents.isLoadingMainFrame()?e.webContents.once("did-finish-load",r):r()}function buildAppMenu({app:e,Menu:t,BrowserWindow:r,updateManager:n,loggedIn:o}){const s="darwin"===process.platform;e.setAboutPanelOptions({applicationName:e.getName(),applicationVersion:e.getVersion(),version:e.getVersion(),
6
+ fingerprintPublish:e=>c.publish(e||{}),fingerprintAnchor:e=>c.anchor(e||{}),fingerprintVault:()=>c.vaultList(),fingerprintVaultAudit:()=>c.vaultAudit(),byokStatus:()=>e.byokStatus(),byokSet:t=>e.byokSet(t&&t.provider,t&&t.apiKey),memorySearch:n=>{const r=s&&"function"==typeof s.capabilities?s.capabilities():null,o=n&&n.limit,a=Number.isFinite(o)?o:r&&Number.isFinite(r.recallEntries)?r.recallEntries:void 0;return normalizeMemoryReadWithFallback(e.memorySearch(n&&n.query,a),memoryIndex(t),n&&n.query,a)},memorySave:n=>saveMemoryWithQueue(e,t,n&&n.entry,s,memoryIndex(t)),memoryList:n=>normalizeMemoryReadWithFallback(e.memoryList(n&&n.limit),memoryIndex(t),"",n&&n.limit),verifyToken:t=>e.verifyToken(t&&t.token),memoryActivate:t=>e.memoryActivate(t&&t.token),memoryPull:n=>indexPulledMemory(e.memoryPull(n&&n.since),memoryIndex(t)),memorySaveBatch:t=>e.memorySaveBatch(t&&t.entries),memoryImport:n=>importForeignMemory(e,t,n,s,memoryIndex(t)),sessionsImportScan:()=>importForeignSessions(t,{confirm:!1}),sessionsImport:e=>importForeignSessions(t,e),importConversation:t=>e.importConversation(t||{}),personaRead:()=>{if(!s)return{ok:!1,reason:"no avatar store in this build"};try{const e=s.readPersona();return{ok:!0,persona:e.persona,warnings:e.warnings||[],capabilities:"function"==typeof s.capabilities?s.capabilities():null}}catch(e){return{ok:!1,reason:errorText(e)}}},personaPatch:e=>{if(!s)return{ok:!1,reason:"no avatar store in this build"};const t=e&&e.patch;if(!t||"object"!=typeof t)return{ok:!1,reason:"no patch"};try{const e=s.writePersona(t);return{ok:!0,saved:!0,persona:e.persona,warnings:e.warnings||[]}}catch(e){return{ok:!1,reason:errorText(e)}}},openExternal:e=>{const t=e&&e.url;return isSafeExternalUrl(t)?Promise.resolve(u(t)).then(()=>({ok:!0}),e=>({ok:!1,reason:errorText(e)})):Promise.resolve({ok:!1,reason:"unsupported URL scheme"})}}}function withReplyNotify(e,t,n){return n?e.then(e=>(n(t,e),e)):e}function registerIpc(e,t,n,r,o,s,a,i,c){const l=createIpcDispatch(t,n,r,o,a,c,i);for(const[t,n]of Object.entries(l))"chatCompletion"!==t?e.handle(`aegis:${t}`,(e,t)=>n(t)):e.handle(`aegis:${t}`,(e,t)=>{const r={...t||{}};if(!r.stream)return withReplyNotify(n(r),e,s);const o=e&&e.sender;return withReplyNotify(n({...r,stream:!0,onStream:e=>{o&&"function"==typeof o.send&&!o.isDestroyed()&&o.send("aegis:chatDelta",taggedChunk(e,r.sessionId))}}),e,s)});return l}function createAccentDispatch(e){if(!e)throw new Error("createAccentDispatch requires a settings store");return{getAccent:()=>({name:e.getAccent()}),setAccent:t=>{const n=t&&t.name;return"string"!=typeof n?{name:e.getAccent()}:{name:e.setAccent(n)}}}}function createFontScaleDispatch(e){if(!e)throw new Error("createFontScaleDispatch requires a settings store");return{getFontScale:()=>({scale:e.getFontScale()}),setFontScale:t=>{const n=t&&t.scale;return"number"!=typeof n?{scale:e.getFontScale()}:{scale:e.setFontScale(n)}}}}function createConfirmModeDispatch(e){if(!e)throw new Error("createConfirmModeDispatch requires a settings store");return{getConfirmMode:()=>({enabled:e.getConfirmMode()}),setConfirmMode:t=>{const n=t&&t.enabled;return"boolean"!=typeof n?{enabled:e.getConfirmMode()}:{enabled:e.setConfirmMode(n)}}}}function createDevModeDispatch(e){if(!e)throw new Error("createDevModeDispatch requires a settings store");return{getDevMode:()=>({enabled:e.getDevMode()}),setDevMode:t=>{const n=t&&t.enabled;return"boolean"!=typeof n?{enabled:e.getDevMode()}:{enabled:e.setDevMode(n)}},getAccountUsername:()=>({username:e.getAccountUsername()}),setAccountUsername:t=>{const n=t&&"string"==typeof t.username?t.username:null;return{username:e.setAccountUsername(n)}}}}function createModelAutoSyncDispatch(e,t){if(!e)throw new Error("createModelAutoSyncDispatch requires a settings store");return{getModelAutoSync:()=>{const e=t&&"function"==typeof t.modelAutoSyncStatus?t.modelAutoSyncStatus():{enabled:!1};return{enabled:Boolean(e&&e.enabled),status:e}},setModelAutoSync:n=>{const r=n&&n.enabled;if("boolean"!=typeof r){const e=t&&"function"==typeof t.modelAutoSyncStatus?t.modelAutoSyncStatus():{enabled:!1};return{enabled:Boolean(e&&e.enabled),status:e}}return e.setSharedPref("modelAutoSync",r),{enabled:r,status:t&&"function"==typeof t.modelAutoSyncStatus?t.modelAutoSyncStatus():{enabled:r}}}}}function createPermissionModeDispatch(e){if(!e)throw new Error("createPermissionModeDispatch requires a settings store");return{getPermissionMode:()=>({mode:e.getPermissionMode()}),setPermissionMode:t=>{const n=t&&t.mode;return"plan"!==n&&null!=n?{mode:e.getPermissionMode()}:{mode:e.setPermissionMode("plan"===n?"plan":null)}}}}function withAutoRoundsSwitch(e,t){const n=e.setConfirmMode;return{...e,setConfirmMode:e=>{const r=n(e);return e&&"boolean"==typeof e.enabled&&t&&"function"==typeof t.setAutoRounds&&t.setAutoRounds(!1===e.enabled),r}}}function createPermRulesDispatch(e){if(!e)throw new Error("createPermRulesDispatch requires a rule store");const t=(e,t)=>{try{return e()}catch(e){return{...t,ok:!1,reason:e&&e.message||String(e)}}};return{permRulesList:()=>t(()=>e.listRules(),{}),permRulesAdd:n=>{const r=n&&n.list,o=n&&n.rule;return"string"!=typeof r||"string"!=typeof o?t(()=>e.listRules(),{reason:"a rule needs a list and a pattern"}):t(()=>e.addRule(r,o),{})},permRulesRemove:n=>{const r=n&&n.list,o=n&&n.rule;return"string"!=typeof r||"string"!=typeof o?t(()=>e.listRules(),{reason:"a rule needs a list and a pattern"}):t(()=>e.removeRule(r,o),{})}}}function createCliFaceDispatch(e){const t=e||{},n=t.face||require("./lib/local/cli-face.js"),r=t.platform||require("./vendor/platform.js"),o=t.spawn||require("node:child_process").spawn,s=e=>{try{return Boolean(r.resolveExecutable(e,{platform:t.hostPlatform||process.platform,env:t.env||process.env}))}catch{return!1}},a=t.entryExists||(e=>{try{return require("node:fs").existsSync(e)}catch{return!1}});return{openCliFace:e=>{const r=t.appInfo||{};let i;try{i=n.plan({packaged:r.packaged,resourcesPath:r.resourcesPath,appDir:r.appDir,execPath:r.execPath,nodePath:r.nodePath,platform:t.hostPlatform||process.platform,exists:s,entryExists:a,args:e&&Array.isArray(e.args)?e.args:[]})}catch(e){return{ok:!1,reason:`could not plan the terminal face: ${e&&e.message||e}`,command:n.CLI_BIN}}if(!i||!i.ok)return{ok:!1,reason:i&&i.reason||"could not open a terminal",command:i&&i.command||n.CLI_BIN};try{const e=o(i.exec,i.args,{detached:!0,stdio:"ignore",env:Object.assign({},t.env||process.env,i.env||{})});e&&"function"==typeof e.unref&&e.unref()}catch(e){return{ok:!1,reason:`could not start ${i.exec}: ${e&&e.message||e}`,command:i.command}}return{ok:!0,emulator:i.exec,command:i.command}}}}function createPtyIpc(e,t){const n=t||{},r=n.ptyHostModule||require("./lib/local/pty-host.js"),o=void 0!==n.nodePty?n.nodePty:r.probeNodePty(),s=r.createPtyHost({nativePty:Boolean(o),appInfo:n.appInfo,spawnPty:o?(e,t)=>o.spawn(e[0],e.slice(1),{name:"xterm-color",cols:t.cols||80,rows:t.rows||24,cwd:t.cwd||process.cwd(),env:Object.assign({},process.env,t.env||{})}):void 0});return e.handle("aegis:ptyHello",(e,t)=>s.hello(t&&t.id||0)),e.handle("aegis:ptyExec",(e,t)=>{const n=t||{},r=e&&e.sender;return s.exec(n.id,n.params,e=>{r&&!r.isDestroyed()&&r.send("aegis:ptyEvent",e)})}),e.handle("aegis:ptyWrite",(e,t)=>{const n=t||{};return s.write(n.id,n.data)}),e.handle("aegis:ptyResize",(e,t)=>{const n=t||{};return s.resize(n.id,n.cols,n.rows)}),e.handle("aegis:ptyCancel",(e,t)=>s.cancel((t||{}).id)),s}function createSandboxPolicyDispatch(e,t,n){if(!e)throw new Error("createSandboxPolicyDispatch requires a settings store");const r=t||{},o=(Array.isArray(r.MODES)?r.MODES:["off","read-only","workspace-write","managed"]).filter(e=>"managed"!==e),s=n&&n.appDir,a=()=>{const t=e.getSandboxPolicy(),n=t&&o.includes(t.mode)?t.mode:"workspace-write",a=t&&"open"===t.network?"open":"restricted";let i=null,c=null,l=null;try{const e=(e=>{const t=r.detectCached||r.detect;if("function"!=typeof t||"function"!=typeof r.describe)return null;try{const n=t({appDir:s}),o=r.describe(n,e);return{mechanism:n&&(n.mechanism||(n.path?"bwrap":null))||null,enforced:Boolean(n&&n.available)&&"off"!==e.mode,sentence:"string"==typeof o?o:null}}catch{return{mechanism:null,enforced:null,sentence:null}}})("function"==typeof r.normalize?r.normalize(t,void 0):{mode:n,network:a});e&&({sentence:i,enforced:c,mechanism:l}=e)}catch{}return{ok:!0,mode:n,network:a,modes:o,stored:!!t,sentence:i,enforced:c,mechanism:l}};return{getSandboxPolicy:()=>a(),setSandboxPolicy:t=>{const n=t&&t.mode,i=t&&t.network;if("string"!=typeof n||!o.includes(n))return a();if(void 0!==i&&"open"!==i&&"restricted"!==i)return a();const c=e.getSandboxPolicy(),l=c&&c.fileSystem&&Array.isArray(c.fileSystem.entries)?{entries:c.fileSystem.entries}:{entries:[]},u=void 0===i?c&&"open"===c.network?"open":"restricted":i;try{e.setSandboxPolicy({mode:n,fileSystem:l,network:u})}catch{return a()}if("function"==typeof r.invalidateProbe)try{r.invalidateProbe(s)}catch{}return a()}}}function registerConfirmModeIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`aegis:${n}`,(e,t)=>r(t));return t}function createVaultBackendDispatch(e){if(!e)throw new Error("createVaultBackendDispatch requires a settings store");return{getVaultBackend:()=>e.vaultBackendConfig(),setVaultBackend:t=>e.setVaultBackendConfig(t&&t.backend)}}function createTelemetryDispatch(e){const t=e||null;return{telemetryEvent:e=>{try{if(!t||"function"!=typeof t.record)return{ok:!1,reason:"telemetry off"};const n=e&&"object"==typeof e?e:{};return t.record(n.event,{campaign:n.campaign,surface:n.surface})?{ok:!0}:{ok:!1,reason:"not an allowlisted funnel event"}}catch(e){return{ok:!1,reason:errorText(e)}}},telemetryReport:()=>{try{return t&&"function"==typeof t.report?t.report():{enabled:!1,transport:"off"}}catch(e){return{enabled:!1,error:errorText(e)}}}}}function createCovenantDispatch(e){return{covenantStatus:()=>({ok:!0,covenant:e.snapshot(),gapReport:e.gapReport()}),covenantGapReport:()=>({ok:!0,gapReport:e.gapReport()})}}function registerCovenantIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`aegis:${n}`,(e,t)=>r(t));return t}function registerTelemetryIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`aegis:${n}`,(e,t)=>r(t));return t}function safeExportBasename(e){return(e&&(e.title||e.id)||"session").replace(/[^\w.-]+/g,"_").slice(0,80)||"session"}function createExportDispatch(e,t,n,r){return{exportSession:async o=>{const s=o&&o.sessionId,a=o&&"json"===o.format?"json":"markdown",i=s?e.getSession(t,s):null;if(!i)return{ok:!1,reason:"session not found"};const c="json"===a?e.toJson(i):e.toMarkdown(i),l="json"===a?"json":"md",u="json"===a?[{name:"JSON",extensions:["json"]}]:[{name:"Markdown",extensions:["md"]}],d=await n({defaultPath:`${safeExportBasename(i)}.${l}`,filters:u});if(!d||d.canceled||!d.filePath)return{ok:!1,canceled:!0};try{await r(d.filePath,c)}catch(e){return{ok:!1,reason:errorText(e)}}return{ok:!0,filePath:d.filePath}}}}function registerExportIpc(e,t,n,r,o){const s=createExportDispatch(t,n,r,o);for(const[t,n]of Object.entries(s))e.handle(`aegis:${t}`,(e,t)=>n(t));return s}function createQuickLauncherDispatch(e,t={}){const n=Boolean(t.isPackaged),r=t.applyConfig||(()=>({active:!1,reason:null})),o=t.pushToMain||(()=>({ok:!1,reason:"no main window"}));let s={active:!1,reason:null};return{status:function(){return{...e.quickLauncherConfig(),packaged:n,...s}},setConfig:function(t){const o=e.setQuickLauncherConfig({enabled:t&&t.enabled,shortcut:t&&t.shortcut});return s=r(o)||{active:!1,reason:null},{...o,packaged:n,...s}},pushToMain:(e,t)=>o(e,t)}}function registerQuickLauncherIpc(e,t){for(const[n,r]of Object.entries(t))"pushToMain"!==n?e.handle(`quick:${n}`,(e,t)=>r(t)):e.handle(`quick:${n}`,(e,t)=>r(t,e));return t}function resolveUserDataDir(e){if(e&&"function"==typeof e.getPath)try{return e.getPath("userData")}catch{}try{const e=require("../one/src/iface/paths.js").plan({platform:process.platform,env:process.env});if(e&&e.ok)return e.state}catch{}return path.join(os.homedir(),".aegiscode")}function createEngine(e,{app:t,safeStorage:n,dir:r,sessionsDir:o}={}){const s=r||resolveUserDataDir(t),a=createSettingsStore({dir:s,safeStorage:n}),i=avatarStore.createAvatarStore({dir:s,log:()=>{}});try{i.verifyAtBoot()}catch(e){console.error("aegis: avatar carve-out violation",e&&e.message)}a.migrateLegacyAegisKey();const c=()=>{try{return i.capabilities()}catch{return null}};return{engine:createLocalEngine({aegis:e,settings:a,recallProvider:({system:e})=>require("./lib/avatar/turn.js").composeSystemPrompt(e,{capabilities:c(),persona:i.readPersona().persona,deep:!1}).system,sandbox:{policy:()=>"function"==typeof a.getSandboxPolicy?a.getSandboxPolicy():null,strict:!1,appDir:__dirname},permissionRules:{rulesVerdict:require("./lib/local/perm-rules.js").rulesVerdict,subjectFor:require("./lib/local/perm-rules.js").subjectFor,alwaysAllow:require("./lib/local/perm-write.js").alwaysAllow}}),sessionsDir:o||sessionStore.resolveStoreDir(s),settingsDir:s,settings:a,avatar:i}}const PREVIEW_READ_MAX_BYTES=524288;function readTextFileForPreview(e){try{const t=e&&"string"==typeof e.file?e.file:"",n=e&&"string"==typeof e.cwd?e.cwd:"";if(!t||!n||!path.isAbsolute(n))return null;const r=fs.realpathSync(n),o=fs.realpathSync(path.resolve(r,t)),s=path.relative(r,o);if(""===s||s.startsWith("..")||path.isAbsolute(s))return null;const a=fs.statSync(o);if(!a.isFile())return null;if(a.size<=524288)return{text:fs.readFileSync(o,"utf8"),truncated:!1};const i=fs.openSync(o,"r");try{const e=Buffer.alloc(524288),t=fs.readSync(i,e,0,524288,0);let n=e.toString("utf8",0,t);const r=n.lastIndexOf("\n");return r>0&&(n=n.slice(0,r+1)),{text:n,truncated:!0}}finally{fs.closeSync(i)}}catch{return null}}const attachmentsModule=require("./lib/local/attachments.js");function nativeImageResizer(e,t){try{const{nativeImage:n}=require("electron");if(!n)return null;const r=n.createFromBuffer(e);if(!r||r.isEmpty())return null;const o=r.getSize(),s=Math.max(o.width,o.height),a=s>1568?r.resize({width:Math.round(1568*o.width/s)}):r,i="image/png"===t?a.toPNG():a.toJPEG(82);return i&&i.length?{buffer:i,mime:"image/png"===t?"image/png":"image/jpeg"}:null}catch{return null}}function ingestAttachment(e,{resize:t=nativeImageResizer}={}){const n=e&&"string"==typeof e.path?e.path.trim():"";if(!n)return{ok:!1,reason:"no path"};if(!path.isAbsolute(n))return{ok:!1,reason:"not an absolute path"};let r,o,s;try{r=fs.realpathSync(n),o=fs.statSync(r)}catch{return{ok:!1,reason:"not found"}}if(!o.isFile())return{ok:!1,reason:"not a regular file"};if(0===o.size)return{ok:!1,reason:"empty file"};if(o.size>attachmentsModule.MAX_FILE_BYTES)return{ok:!1,reason:`too large (${attachmentsModule.humanBytes(o.size)})`};try{s=fs.readFileSync(r)}catch{return{ok:!1,reason:"unreadable"}}const a=attachmentsModule.sniff(s),i={path:r,name:path.basename(r),size:o.size,mime:a.mime,kind:a.kind};if("image"===a.kind){let{mime:e}=a,n=s,r=!1;if(n.length>attachmentsModule.MAX_IMAGE_BYTES&&"function"==typeof t){const o=t(s,e);o&&o.buffer&&o.buffer.length<n.length&&(n=o.buffer,e=o.mime,r=!0)}const o=attachmentsModule.toDataUrl(n,e);return o?{ok:!0,attachment:{...i,kind:"image",mime:e,size:n.length,dataUrl:o,scaled:r,vision:attachmentsModule.isVisionMime(e)}}:{ok:!1,reason:"could not encode image"}}if("text"===a.kind){if(o.size>attachmentsModule.MAX_TEXT_BYTES){let e=s.subarray(0,attachmentsModule.MAX_TEXT_BYTES).toString("utf8");const t=e.lastIndexOf("\n");return t>0&&(e=e.slice(0,t+1)),{ok:!0,attachment:{...i,kind:"text",text:e,truncated:!0}}}return{ok:!0,attachment:{...i,kind:"text",text:s.toString("utf8"),truncated:!1}}}return"pdf"===a.kind?{ok:!0,attachment:{...i,kind:"pdf"}}:{ok:!0,attachment:{...i,kind:"binary"}}}function createModelDispatch(e,{env:t=process.env,settings:n}={}){const r=new Map;let o,s=autoRoundsDefault(t),a=!1;const i=()=>{const t=n||e&&e.settings||null,r=e=>"boolean"==typeof e?e:void 0;let i;try{if(t&&"function"==typeof t.confirmModeState){const e=t.confirmModeState();i=r(e&&e.enabled)}void 0===i&&t&&"function"==typeof t.getConfirmMode&&(i=r(t.getConfirmMode()))}catch{}return a||void 0===i||(void 0===o?o=i:i!==o&&(a=!0,s=!0)),!(!s||!t||void 0===i)&&!1===i},c={listClasses:async()=>(await e.listClasses()).filter(e=>DESKTOP_CLASSES.includes(e.class)),listModels:t=>e.listModels(t&&t.class),chat:n=>{const o=n&&n.onStream;if("function"!=typeof o)return e.chat(n,o);const s=n&&n.sessionId||"";return e.chat(n,n=>{if(n&&n.rounds&&n.rounds.id&&i()){const a=autoContinuePlan({on:!0,used:r.get(s)||0,limit:autoContinueLimit(t)});if(r.set(s,a.used),a.auto){const t="function"==typeof e.respondRoundsAsk?e.respondRoundsAsk(n.rounds.id,!0):{ok:!1};if(t&&t.ok){const e=Number(n.rounds.spent)||0;return void o({note:`auto mode: the ${e}-round limit was reached — continuing automatically (${a.used}/${a.cap}, then it asks).`})}}}o(n)})},"settings.get":()=>e.settings.list().filter(e=>!(e&&isReservedNamespace(e.provider))),"settings.set":t=>e.settings.set(t&&t.provider,{baseURL:t&&t.baseURL,key:t&&t.key}),"settings.remove":t=>e.settings.remove(t&&t.provider),"userModels.get":()=>e.userModels(),"userModels.add":t=>e.addUserModel(t&&t.provider,t&&t.model),"userModels.remove":t=>e.removeUserModel(t&&t.provider,t&&t.model),"userModels.discover":t=>e.discoverModels(t&&t.provider),"userModels.addAll":t=>e.addUserModels(t&&t.provider,t&&t.ids),"userModels.canDiscover":t=>Boolean(e.canDiscoverModels(t&&t.provider)),"userModels.discoverable":()=>e.discoverableProviders(),"userModels.syncPlan":t=>e.modelSyncPlan(t&&t.only),"userModels.syncApply":t=>e.modelSyncApply(t&&t.plan,t&&t.only),"userModels.syncStatus":()=>e.modelAutoSyncStatus(),"userModels.syncNow":t=>e.modelAutoSyncRun(t&&t.only),"memoryPersist.get":()=>e.settings.memoryPersistState(),"memoryPersist.set":t=>e.settings.setMemoryPersist(Boolean(t&&t.enabled)),cancel:t=>e.cancel(t&&t.sessionId),respondApproval:t=>e.respondApproval(t&&t.approvalId,t&&t.decision),respondRoundsAsk:t=>"function"==typeof e.respondRoundsAsk?e.respondRoundsAsk(t&&t.roundsAskId,t&&t.decision):{ok:!1},clearApprovals:t=>e.clearSessionApprovals(t&&t.sessionId),listUndoable:t=>"function"==typeof e.listUndoable?e.listUndoable(t&&t.sessionId):[],undoMutation:t=>"function"==typeof e.undoMutation?e.undoMutation(t&&t.sessionId,t&&t.id):{ok:!1,error:"undo is not available on this engine"}};return Object.defineProperties(c,{autoRoundsOn:{value:i,enumerable:!1},setAutoRounds:{value:e=>{s=Boolean(e),a=!0},enumerable:!1}}),c}function createSyncDispatch(e,t,n,r,o){let s=null;function a(){return Boolean(n&&n.apiKey)}async function i(){const r=e.listPending(t);if(!a())return{ok:!1,queued:r.length,reason:"no AEGIS key configured"};const o=await async function(){const e=memoryQueue.listQueued(t);if(!e.length)return{flushed:0,remaining:0,upgrade:null};const r=[];let o=0,s=null;for(let a=0;a<e.length;a+=1)try{await n.memorySave(e[a]),o+=1;const r=memoryIndex(t);if(r)try{r.upsert(e[a])}catch{}}catch(t){const n=upgradeInfo(t);if(n){s=n,r.push(...e.slice(a));break}r.push(e[a])}return memoryQueue.save(t,r),{flushed:o,remaining:r.length,upgrade:s}}();if(!r.length)return{ok:!0,queued:0,pushed:0,memoryFlushed:o.flushed,upgrade:o.upgrade};let i=0,c=null,l=null;for(const o of r)try{const r=await n.conversationSyncPush({session_id:o.id,title:o.title,messages:o.messages}),s=r&&(r.session_id||r.id);e.markSynced(t,o.id,{remoteId:s}),i+=1}catch(e){if(c=e,l=describeSyncError(e),"quota"===l.kind||"auth"===l.kind)break}const u=e.listPending(t).length;i&&(s=Date.now());const d=(c?upgradeInfo(c):null)||o.upgrade;return 0===i&&c?{ok:!1,queued:u,reason:syncErrorReason(l),failed:l?[l]:[],kind:l?l.kind:"error",status:l?l.status:0,hint:l?l.hint:null,memoryFlushed:o.flushed,upgrade:d}:{ok:!0,queued:u,pushed:i,failed:l?[l]:[],memoryFlushed:o.flushed,upgrade:d}}const c=persistGate.createAutoPush({push:i,dir:r||t}),l=["id","title","updatedAt","pending","named","seq","cwd","dir","origin","remoteId","lastSyncedAt"];return{auto:()=>c.auto(),memoryPersistState:()=>c.gate(),listSessions:()=>{return{sessions:(n=e.listSessions(t),(Array.isArray(n)?n:[]).filter(e=>e&&e.id).map(e=>{const t={};for(const n of l)void 0!==e[n]&&(t[n]=e[n]);const n=Array.isArray(e.messages)?e.messages:[];t.messages=n.length;const r=n.find(e=>e&&"user"===e.role&&e.content);return t.firstPrompt=r?String(r.content):"",t}))};var n},searchSessions:n=>{const r=n&&"string"==typeof n.query?n.query:"",o=Number.isInteger(n&&n.limit)?n.limit:50,s=Math.max(1,o),a=e.listSessions(t)||[],i=sessionSearch.rankSessions(r,a).slice(0,s);let c=[],l=0,u="ok";try{const e=memoryIndex(t);if(e){const t=e.search(r,{limit:s});t&&t.ok?(c=(t.results||[]).map(e=>({id:e.id,content:e.body||"",scope:e.scope||"",tags:Array.isArray(e.tags)?e.tags:[],updated:e.updated||null})),l=e.count()):u="error"}else u=memoryStore.isAvailable()&&t?"error":"unavailable"}catch{c=[],l=0,u="error"}return{query:r,total:a.length,memoryStatus:u,memoryTotal:l,memory:c,sessions:i.map(e=>({id:e&&e.id,title:e&&e.title||e&&e.id||"untitled",updatedAt:e&&e.updatedAt||null,messages:e&&Array.isArray(e.messages)?e.messages.map(e=>({role:e&&e.role,content:"string"==typeof(e&&e.content)?e.content.slice(0,400):""})):[],reason:sessionSearch.matchReason(r,e)}))}},open:n=>e.getSession(t,n&&n.sessionId),save:n=>e.upsertSession(t,n||{}),append:n=>e.appendMessage(t,n&&n.sessionId,n&&n.message),delete:n=>e.deleteSession(t,n&&n.sessionId),rename:n=>e.renameSession(t,n&&n.sessionId,n&&n.title),nameSession:async n=>{const r=n&&n.sessionId,s=n&&n.prompt;if(!r||!String(null==s?"":s).trim())return null;let a;for(const e of["../client/naming.js","./vendor/naming.js","./vendor/client/naming.js"])try{a=require(e);break}catch{}if(!a)return null;const i=async(e,t={})=>{if(!o||"function"!=typeof o.chat)return null;try{const s=await o.chat({class:n&&n.class||"aegis",model:n&&n.model,prompt:e,system:t.system,maxTokens:64,sessionId:`${r}:naming`,tools:!1}),a=s&&s.choices&&s.choices[0]||{};return a.message&&a.message.content||null}catch{return null}};try{return await a.nameSession(e.namingStore,t,r,s,{callModel:i})}catch{return null}},push:i,pull:async function(){if(!a())return{ok:!1,merged:0,reason:"no AEGIS key configured"};try{const r=await n.conversationSyncPull(),o=e.mergeRemoteSessions(t,r&&r.sessions||[]);return s=Date.now(),{ok:!0,merged:o,failed:[],upgrade:null}}catch(e){const t=describeSyncError(e);return{ok:!1,merged:0,reason:syncErrorReason(t),failed:[t],kind:t.kind,status:t.status,hint:t.hint,upgrade:upgradeInfo(e)}}},status:()=>({count:e.listSessions(t).length,pending:e.listPending(t).length,cloud:a(),lastSyncAt:s})}}const HEARTBEAT_RETRY_BASE_MS=5e3,HEARTBEAT_RETRY_MAX_MS=3e4;function createHeartbeatRetry(e,t={}){const n="function"==typeof t.now?t.now:()=>Date.now(),r=Number(t.baseMs)>0?Number(t.baseMs):5e3,o=Number(t.maxMs)>0?Number(t.maxMs):3e4;let s=0,a=0,i=null,c=!1;function l(e){s+=1;const t=Math.min(o,r*2**Math.max(0,s-1));return i=e||"push failed",a=n()+t,{attempted:!0,ok:!1,error:i,failures:s,retryInMs:t}}return{run:async function(){const t=n();if(s>0&&t<a)return{attempted:!1,ok:!1,error:i,failures:s,retryInMs:a-t};if(c)return{attempted:!1,ok:!1,error:i,failures:s,retryInMs:0};c=!0;try{const t=await e();return t&&!1===t.ok?l(t.reason||t.kind||"push failed"):(s=0,a=0,i=null,{attempted:!0,ok:!0,error:null,failures:0,retryInMs:0,result:t})}catch(e){return l(errorText(e))}finally{c=!1}},state:function(){const e=n();return{failures:s,lastError:i,retryInMs:s>0&&a>e?a-e:0}},recordFailure:e=>l(errorText(e))}}function registerModelIpc(e,t,n,r,o,s,a,i){const c=createModelDispatch(t),l=createSyncDispatch(sessionStore,n,r,a,c),u=createHeartbeatRetry(()=>l.push(),s);function d(){const e=u.run();e&&"function"==typeof e.catch&&e.catch(e=>u.recordFailure(e))}for(const[t,n]of Object.entries(c))"chat"!==t?"listModels"!==t?e.handle(`model:${t}`,(e,t)=>n(t)):e.handle(`model:${t}`,(e,t)=>(d(),n(t))):e.handle(`model:${t}`,(e,t)=>{const r={...t||{}},s=!0===r.bestEffort;delete r.bestEffort;const a="low"===r.effort||"medium"===r.effort||"max"===r.effort?r.effort:"high";r.effort=a;const c=e&&e.sender,l=r.class||"model",u=n({...r,onStream:e=>{c&&"function"==typeof c.send&&!c.isDestroyed()&&c.send("aegis:chatDelta",taggedChunk(e,r.sessionId))}});return s?u.then(t=>(o&&o(e,t),t),e=>{const t=e&&"number"==typeof e.status?e.status:0,n=e&&e.code||"";return backgroundLaneLogs(i)&&console.warn(`[model] background ${l} turn produced no answer: ${errorText(e)}${t?` (status ${t})`:""}${n?` [${n}]`:""}`),{bestEffortFailed:!0,status:t,code:n||void 0,message:errorText(e),choices:[{message:{content:""}}]}}):withReplyNotify(u,e,o).catch(e=>{if(isAbortShapedError(e))return backgroundLaneLogs(i)&&console.warn(`[model] ${l} turn stopped before it finished: ${errorText(e)} [ABORT_ERR]`),abortedTurnPayload(e);const t=e&&"number"==typeof e.status?e.status:0,n=e&&e.code||"";return backgroundLaneLogs(i)&&console.error(`[model] ${l} turn failed: ${errorText(e)}${t?` (status ${t})`:""}${n?` [${n}]`:""}`,e&&e.stack?e.stack:""),{providerFailed:!0,status:t,code:n||void 0,message:errorText(e),choices:[{message:{content:""}}]}})});e.on("model:readTextFile",(e,t)=>{e.returnValue=readTextFileForPreview(t)}),e.handle("aegis:attachments:ingest",async(e,t)=>ingestAttachment(t));for(const[t,n]of Object.entries(l))"status"!==t?e.handle(`sync:${t}`,(e,t)=>n(t)):e.handle(`sync:${t}`,(e,t)=>{d();const r=n(t);return r&&"object"==typeof r?{...r,retry:u.state()}:r});return{modelDispatch:c,syncDispatch:l,heartbeat:u}}function createQueueEngine(e,t){return createLocalEngine({aegis:e,settings:t,getConfirmMode:()=>!1})}function queueEngineWithDeniedApprovals(e){return e&&"function"==typeof e.chat?{...e,chat:(t,n)=>e.chat(t,t=>{(t=>{const n=t&&t.approval;if(n&&n.id&&"function"==typeof e.respondApproval)try{e.respondApproval(n.id,"deny")}catch{}})(t),(t=>{const n=t&&t.rounds;if(n&&n.id&&"function"==typeof e.respondRoundsAsk)try{e.respondRoundsAsk(n.id,!1)}catch{}})(t),"function"==typeof n&&n(t)})}:e}function isExistingDir(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function clampInt(e,t,n){const r=Number(e);return!Number.isInteger(r)||r<t||r>n?null:r}function createQueueDispatch({engine:e,env:t=process.env,queue:n=queueModule,autonomous:r=autonomousModule,entitlement:o=entitlementModule.createEntitlement({}),log:s=()=>{}}={}){if(!e||"function"!=typeof e.chat)throw new Error("createQueueDispatch: a local engine with chat() is required");let a=null,i=!1,c=!1;const l=r.createQueueWorker({engine:queueEngineWithDeniedApprovals(e),env:t,log:e=>{e&&"start"===e.type&&(a=e.taskId),e&&"finish"===e.type&&(a=null),s(e)},canFanOut:()=>o.current().entitled});function u(){const e=n.loadQueue(t);return{ok:!0,items:e,pending:n.pendingCount(e),running:e.find(e=>e&&"running"===e.status)||null,draining:c,stopping:i,defaultCwd:process.cwd(),defaultModel:r.resolveModel({env:t}),queueFile:n.queuePath(t),runs:n.readRuns(t,{limit:20}),entitlement:o.current()}}const d=e=>(e||[]).map(e=>({id:e.id,ok:Boolean(e.ok),error:e.error||null}));return{enqueue:async e=>{await o.refresh();const s=o.gateFanout({workers:clampInt(e&&e.workers,1,8),fanout:Boolean(e&&!0===e.fanout)});if(!s.ok)return{...s,...u()};const{opts:a,error:i}=function(e){const t=e||{},n=String(null==t.task?"":t.task).trim();if(!n)return{error:"a queued task needs text"};if(n.length>8e3)return{error:`task text is too long (${n.length} > 8000 chars)`};const o=String(null==t.cwd?"":t.cwd).trim()||process.cwd();if(!path.isAbsolute(o))return{error:"the working directory must be an absolute path"};if(!isExistingDir(o))return{error:`not a directory: ${o}`};const s=r.normalizeClass(t.class),a=String(null==t.model?"":t.model).trim().slice(0,120)||null,i=r.modelRefusal(a,s);if(i)return{error:i};const c=String(null==t.effort?"":t.effort).trim().toLowerCase();return{opts:{task:n,cwd:o,class:s,model:a,effort:QUEUE_EFFORTS.has(c)?c:null,workers:clampInt(t.workers,1,8),maxRounds:clampInt(t.maxRounds,1,200),singlePass:!(!0===t.fanout||!0===t.autonomous),commit:Boolean(t.commit),source:"desktop"}}}(e);return i?{ok:!1,reason:i,...u()}:{ok:!0,item:n.addTask(t,a),...u()}},list:()=>u(),entitlement:async e=>(await o.refresh({force:Boolean(e&&!0===e.force)}),{ok:!0,...u()}),clear:e=>({...n.clearQueue(t,{all:Boolean(e&&e.all)}),ok:!0,...u()}),retry:e=>{const r=e&&e.id,o=n.retryTask(t,r);return o?{ok:!0,item:o,...u()}:{ok:!1,reason:`no task #${r}`,...u()}},remove:e=>{const r=e&&e.id,o=n.loadQueue(t),s=n.findTask(o,r);return s?"running"===s.status?{ok:!1,reason:`task #${s.id} is running — stop the drain first`,...u()}:(n.saveQueue(t,o.filter(e=>Number(e&&e.id)!==Number(s.id))),{ok:!0,removed:s.id,...u()}):{ok:!1,reason:`no task #${r}`,...u()}},drain:()=>async function(){if(c)return{ok:!1,reason:"a drain is already running in this window",...u()};let e;c=!0,i=!1;try{const t=await l.proceed({max:1});e=t.locked?{ok:!1,locked:!0,holder:t.holder,ran:[]}:{ok:!0,ran:d(t.ran)}}catch(t){e={ok:!1,reason:errorText(t),ran:[]}}return c=!1,a=null,{...e,...u()}}(),proceed:()=>async function(){if(c)return{ok:!1,reason:"a drain is already running in this window",...u()};c=!0,i=!1;const e=[];let t;try{for(;;){const n=await l.proceed({max:1});if(n.locked){t={ok:!1,locked:!0,holder:n.holder,ran:d(e)};break}if(!n.ran.length){t={ok:!0,stopped:i,ran:d(e)};break}if(e.push(...n.ran),i){t={ok:!0,stopped:!0,ran:d(e)};break}}}catch(n){t={ok:!1,reason:errorText(n),ran:d(e)}}return c=!1,a=null,{...t,...u()}}(),stop:e=>{i=!0;const t=e&&null!=e.id?e.id:a,n=null==t?null:l.cancel(t);return{ok:!0,wasDraining:c,cancelled:n,...u()}}}}function createAutoDispatch({autoDrain:e,autoMint:t}={}){if(!e||"function"!=typeof e.state)throw new Error("createAutoDispatch: the auto-drain automation is required");if(!t||"function"!=typeof t.state)throw new Error("createAutoDispatch: the auto-mint automation is required");return{autoStatus:()=>({ok:!0,drain:e.state(),mint:t.state()}),autoSetDrain:t=>{const n=t||{},r={};null!=n.enabled&&(r.enabled=Boolean(n.enabled)),null!=n.intervalMs&&(r.intervalMs=Number(n.intervalMs));try{return{ok:!0,drain:e.set(r)}}catch(e){return{ok:!1,error:errorText(e)}}},autoSetMint:e=>{const n=e||{},r={};null!=n.enabled&&(r.enabled=Boolean(n.enabled)),null!=n.publish&&(r.publish=Boolean(n.publish));try{return{ok:!0,mint:t.set(r)}}catch(e){return{ok:!1,error:errorText(e)}}},autoSealNow:async e=>{const n=e||{};null!=n.publish&&t.set({publish:Boolean(n.publish)});try{const e=await t.flush();return t.reset(),{ok:!0,...e}}catch(e){return t.reset(),{ok:!1,error:errorText(e)}}}}}function liveAppWindows(){try{const e=require("electron"),t=e&&e.BrowserWindow;return t&&"function"==typeof t.getAllWindows?t.getAllWindows().filter(e=>e&&"function"==typeof e.send&&!("function"==typeof e.isDestroyed&&e.isDestroyed())):[]}catch{return[]}}function registerQueueIpc(e,{engine:t,env:n,queue:r,autonomous:o,entitlement:s,aegis:a,windows:i=liveAppWindows}={}){let c=null;const l=s||entitlementModule.createEntitlement({probe:a&&"function"==typeof a.verifyApiKey?async()=>{const e=await a.verifyApiKey(),t=e&&"object"==typeof e?{...e}:{};if("function"==typeof a.tokenBankBalance)try{const e=await a.tokenBankBalance();e&&"object"==typeof e&&(null!=e.balance_micros?t.balance_micros=e.balance_micros:null!=e.balance_eur&&(t.balance_eur=e.balance_eur))}catch{}return t}:void 0}),u=()=>{let e=[];try{e=i()||[]}catch{e=[]}for(const t of e)try{t.send("queue:changed",{at:Date.now()})}catch{}},d=createQueueDispatch({engine:t,env:n,queue:r,autonomous:o,entitlement:l,log:e=>{e&&"finish"===e.type&&u(),c&&"function"==typeof c.send&&("function"==typeof c.isDestroyed&&c.isDestroyed()||c.send("queue:progress",e))}});for(const[t,n]of Object.entries(d))e.handle(`queue:${t}`,(e,r)=>{c=e&&e.sender||null;const o=n(r);return QUEUE_MUTATING_METHODS.has(t)?o&&"function"==typeof o.then?o.then(e=>(u(),e),e=>{throw u(),e}):(u(),o):o});return d}function registerAutoIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`auto:${n}`,(e,t)=>r(t));return t}const UPDATE_STATUS_CHANNEL="aegis:updateStatus",ACCOUNT_STATUS_CHANNEL="aegis:accountStatusChanged",UPDATE_CHECK_INTERVAL_MS=144e5,UPDATE_RETRY_BACKOFF_MS=[6e4,3e5,9e5,36e5];function describeRegistryFailure(e,t,n){switch(e){case"not-found":return`${n} is not published on the npm registry (404)`;case"forbidden":return`the npm registry refused the request (${t||"auth"})`;case"malformed":return"the npm registry sent a response this app could not read";case"too-large":return"the npm registry response was too large to read";case"timeout":return"the npm registry did not respond in time";case"network":return"the npm registry could not be reached";default:return"the update check did not complete"}}function resolveUpdateOwner({dir:e=__dirname,readJson:t=e=>JSON.parse(fs.readFileSync(e,"utf8"))}={}){const n=`${path.sep}vendor${path.sep}desktop`,r=String(e).lastIndexOf(n);if(r>0){const n=String(e).slice(0,r);try{const e=t(path.join(n,"package.json")).version;if(e)return{pkg:"aegisone",current:String(e),productDir:n}}catch{}}try{const n=t(path.join(e,"package.json")).version;if(n)return{pkg:"aegis-desktop",current:String(n),productDir:null}}catch{}return{pkg:"aegis-desktop",current:"unknown",productDir:null}}function installFailureText(e,t="the installer failed"){const n=String(null==e?"":e).split("\n").map(e=>e.replace(/^\s*npm\s+(error|ERR!)\s*/i,"").trim()).filter(Boolean).filter(e=>!/^A complete log of this run can be found/i.test(e)).filter(e=>!/^In most cases you or one of your dependencies/i.test(e)).filter(e=>!/^a package version that doesn't exist\.?$/i.test(e));if(!n.length)return t;const r=n.findIndex(e=>/^code\s+[A-Z]/i.test(e)),o=r>=0&&n[r+1]?n[r+1]:n[0],s=r>=0?n[r].replace(/^code\s+/i,""):"";return s?`${o} (${s})`:o}function createNpmUpdateManager({onStatus:e,packaged:t=!1,now:n=()=>Date.now(),fetchImpl:r,setTimeoutImpl:o=setTimeout,clearTimeoutImpl:s=clearTimeout,runUpgrade:a,relaunch:i,owner:c}={}){const l=c||resolveUpdateOwner(),u=l.pkg;let d=l.current,p={status:"idle",version:null,error:null,phase:null,channel:"npm",reason:null,transient:!1,attempts:0,retryInMs:0,command:null,plan:null,method:null,canDownload:!1,decomposed:!1};const m=t=>(p={...p,...t},e&&e(p),p);let f=null;try{f=require("../client/update.js")}catch{try{f=require("./vendor/update.js")}catch{f=null}}let g=0,h=0,y=null,k=null,b=null,v=null;function S(){y&&s(y),y=null}const w=(e,t)=>"function"==typeof f.isTransientReason?f.isTransientReason(e,t):"unknown"===e;let E=null;async function A({announce:e=!1}={}){if(!f)return m({status:"disabled",error:"update checker unavailable"});if(k)return k;k=(async()=>{const s=p.status,a=p.version;let i;m({status:"checking",error:null,reason:null,transient:!1,phase:null});try{i=await async function(){if(r)return r({pkg:u});if(f&&"function"==typeof f.checkPublished){const e=await f.checkPublished({current:d,pkg:u,now:n(),intervalMs:0});return e?{ok:e.ok,latest:e.latest,reason:e.reason,status:e.status}:{ok:!1,latest:null,reason:"unknown",status:null}}return{ok:!1,latest:null,reason:"unavailable",status:null}}()}catch(e){i={ok:!1,latest:null,reason:"unknown",status:null,error:errorText(e)}}if(i.ok){if(g=0,h=0,S(),await async function(){if(null!==E)return E;if(!f||"function"!=typeof f.serverUpdateVerdict)return null;try{const e=await f.serverUpdateVerdict({current:d});return e&&e.ok&&(E=Boolean(e.decomposed)),E}catch{return null}}())return m({status:"decomposed",version:i.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0,decomposed:!0});if(!f.isNewer(i.latest,d))return m({status:"up-to-date",version:i.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0});const e=function(){if(v)return v;const e=f&&f.detectInstallMethod;if("function"!=typeof e)return v="npm",v;try{v=e({env:process.env,argv:process.argv,pkg:u,entry:__dirname,fileExists:e=>fs.existsSync(path.resolve(__dirname,"..",e))})}catch{v="npm"}return v}(),n="function"==typeof f.updatePlan?f.updatePlan({current:d,latest:i.latest,behind:!0,channel:"npm",pkg:u,method:e}):null;return m({status:"available",version:i.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0,plan:n,method:e,command:t?`${i.latest} is published — reinstall aegis one from the installer to pick it up`:n&&n.instruction||`npm i -g ${u}@latest`,commandIsSentence:t||Boolean(n&&!n.apply),canDownload:Boolean(n&&n.apply)&&!t})}g+=1;const c=i.error||describeRegistryFailure(i.reason,i.status,u);return w(i.reason,i.status)?(function(){S();const e=UPDATE_RETRY_BACKOFF_MS[Math.min(Math.max(g-1,0),UPDATE_RETRY_BACKOFF_MS.length-1)];h=n()+e,y=o(()=>{y=null,A().catch(()=>{})},e),y&&y.unref&&y.unref(),m({retryInMs:e})}(),m(e?{status:"error",phase:"check",error:c,reason:i.reason,transient:!0,attempts:g}:{status:"available"===s?"available":"unavailable",version:a,error:c,reason:i.reason,transient:!0,attempts:g})):(S(),h=0,m({status:"error",phase:"check",error:c,reason:i.reason,transient:!1,attempts:g,retryInMs:0}))})();try{return await k}finally{k=null}}return{status:()=>p,check:A,download:async()=>{const e=!t&&p.plan&&p.plan.apply;if(!e)return m({status:"available"===p.status?"available":p.status,command:p.plan&&p.plan.instruction||p.command,canDownload:!1});m({status:"downloading",error:null,progress:0,phase:null});const n=await function(e){const t=a||((e,t)=>new Promise(n=>{execFile(e,t,{timeout:18e4,windowsHide:!0},(e,t,r)=>{if(e)return n({ok:!1,output:String(r||t||e.message||e)});n({ok:!0,output:String(t||"")})})})),n=!a&&f&&"function"==typeof f.installSpawn?f.installSpawn(e,{env:process.env}):null,r=n?n.command:e.command,o=n?n.args:e.args;return Promise.resolve(t(r,o)).then(e=>({ok:Boolean(e&&e.ok),output:String(e&&e.output||"")}),e=>({ok:!1,output:errorText(e)}))}(e);return n.ok?m({status:"downloaded",version:p.version,error:null,progress:100,command:`npm i -g ${u}@latest`,canDownload:!1}):m({status:"error",transient:!1,phase:"install",error:installFailureText(n.output),command:`${e.command} ${e.args.join(" ")}`})},quitAndInstall:()=>{"downloaded"===p.status&&(i||(()=>{try{const{app:e}=require("electron");e.relaunch(),e.exit(0)}catch{}}))()},start:()=>{A().catch(()=>{}),b=setInterval(()=>A().catch(()=>{}),144e5),b.unref&&b.unref()},stop:()=>{S(),b&&clearInterval(b),b=null},retryState:()=>({attempts:g,retryAt:h,inFlight:!!k,hasTimer:!!y})}}function createUpdateManager({isPackaged:e,onStatus:t}){let n={status:"idle",version:null,error:null,canDownload:!1};return createNpmUpdateManager({onStatus:function(e){n={...n,...e},t&&t(n)},packaged:Boolean(e)})}function createUpdateDispatch(e){return{checkForUpdates:()=>e.check({announce:!0}),downloadUpdate:()=>e.download(),quitAndInstallUpdate:()=>(e.quitAndInstall(),{ok:!0}),updateStatus:()=>Promise.resolve(e.status())}}function registerUpdateIpc(e,t){const n=createUpdateDispatch(t);for(const[t,r]of Object.entries(n))e.handle(`aegis:${t}`,(e,t)=>r(t));return n}let resolveTargetWindow=null;function sendToAppWindow(e,t){const n="function"==typeof resolveTargetWindow?resolveTargetWindow():null,r=n&&!n.isDestroyed()?n:e.getFocusedWindow()||e.getAllWindows()[0];r&&!r.isDestroyed()&&r.webContents.send(t)}function sendDeepLinkToWindow(e,t){if(!e||e.isDestroyed()||!t)return;const n=()=>{e.isDestroyed()||e.webContents.send("aegis:deepLink",t)};e.webContents.isLoadingMainFrame()?e.webContents.once("did-finish-load",n):n()}function buildAppMenu({app:e,Menu:t,BrowserWindow:n,updateManager:r,loggedIn:o}){const s="darwin"===process.platform;e.setAboutPanelOptions({applicationName:e.getName(),applicationVersion:e.getVersion(),version:e.getVersion(),
7
7
  // The licence and the copyright, where the OS shows them. macOS draws
8
- copyright:creditsLib.COPYRIGHT,credits:`${creditsLib.LICENCE_NAME}\n${creditsLib.COPYRIGHT}\nSource: ${creditsLib.SOURCE_URL}\nHelp > Credits & licence lists the vendored third-party code and fonts.`});const a={label:"Check for Updates…",click:()=>n.check({announce:!0})},i={label:"New Chat",accelerator:"CmdOrCtrl+N",click:()=>sendToAppWindow(r,"aegis:menuNewChat")},c={label:"Search",accelerator:"CmdOrCtrl+K",click:()=>sendToAppWindow(r,"aegis:menuSearch")},l={label:"Command palette…",accelerator:"CmdOrCtrl+P",click:()=>sendToAppWindow(r,"aegis:menuPalette")},u={label:"Toggle sidebar",accelerator:"CmdOrCtrl+B",click:()=>sendToAppWindow(r,"aegis:menuToggleSidebar")},d={label:"Find in conversation",accelerator:"CmdOrCtrl+F",click:()=>sendToAppWindow(r,"aegis:menuFind")},p={label:"Go Back",accelerator:s?"Cmd+[":"Alt+Left",enabled:navState.back,click:()=>sendToAppWindow(r,"aegis:menuGoBack")},m={label:"Go Forward",accelerator:s?"Cmd+]":"Alt+Right",enabled:navState.forward,click:()=>sendToAppWindow(r,"aegis:menuGoForward")},f={label:"Search memory",accelerator:"CmdOrCtrl+Shift+K",visible:!1,click:()=>sendToAppWindow(r,"aegis:menuSearchMemory")},g={label:"Credits & Licence…",click:()=>sendToAppWindow(r,"aegis:menuCredits")},h={label:"Source Code",click:()=>{try{require("electron").shell.openExternal(creditsLib.SOURCE_URL)}catch{}}},y={label:"Save as…",accelerator:"CmdOrCtrl+S",click:()=>sendToAppWindow(r,"aegis:menuExportMarkdown")},k={label:"Export Session…",click:()=>sendToAppWindow(r,"aegis:menuExportJson")},b={label:"Authorship Panel…",click:()=>sendToAppWindow(r,"aegis:menuFingerprint")},v={label:"Google Drive Backup…",enabled:Boolean(o),click:()=>sendToAppWindow(r,"aegis:menuGoogleDrive")},S=[...s?[{label:e.getName(),submenu:[{role:"about"},a,{type:"separator"},g,h,{type:"separator"},{role:"services"},{type:"separator"},{role:"hide"},{role:"hideOthers"},{role:"unhide"},{type:"separator"},{role:"quit"}]}]:[],{label:"File",submenu:[i,{type:"separator"},y,k,{type:"separator"},...s?[]:[a,{type:"separator"}],s?{role:"close"}:{role:"quit"}]},{label:"Edit",submenu:[{role:"undo"},{role:"redo"},{type:"separator"},{role:"cut"},{role:"copy"},{role:"paste"},{role:"selectAll"},{type:"separator"},d]},{label:"View",submenu:[l,c,f,{type:"separator"},u,{type:"separator"},p,m,{type:"separator"},b,v,{type:"separator"},{role:"reload",accelerator:"CmdOrCtrl+R"},{role:"forceReload"},{type:"separator"},{role:"toggleDevTools",accelerator:"CmdOrCtrl+Shift+I"}]},{label:"Help",submenu:[g,h,{type:"separator"},...s?[]:[{role:"about"}]]}];return t.buildFromTemplate(S)}function bootstrap(){let e=null;const t=electron&&electron.app,r=electron&&electron.BrowserWindow,n=(r,n)=>{const o=n&&(n.stack||n.message)||n&&String(n)||String(n),s=`[${(new Date).toISOString()}] ${r}: ${o}\n`;try{process.stderr.write(`aegis-desktop: ${s}`)}catch{}try{e=e||path.join(t.getPath("userData"),"crash.log"),fs.appendFileSync(e,s,{mode:384})}catch{}return o};process.on("uncaughtException",e=>{n("uncaughtException",e),process.exitCode=1,t?t.exit(1):process.exit(1)}),process.on("unhandledRejection",e=>{n("unhandledRejection",e)}),t&&"function"==typeof t.on&&t.on("render-process-gone",(e,t,o)=>{if(n("render-process-gone",new Error(JSON.stringify(o))),o&&"clean-exit"!==o.reason)try{const e=r.getFocusedWindow&&r.getFocusedWindow()||(r.getAllWindows?r.getAllWindows()[0]:null);e&&!e.isDestroyed()&&e.reload()}catch{}});let o=!1;try{o=require("./lib/local/integrity.js").armed()}catch{o=!0,process.env.AEGIS_REDUCED_MODE="1",process.stderr.write("aegis-desktop: reduced mode (d1) — this build is not the one that was published.\n")}if(o){try{const{app:e}=electron;e&&"function"==typeof e.quit&&e.quit()}catch{}return}const{app:s,BrowserWindow:a,ipcMain:i,safeStorage:c,shell:l,Menu:u,Notification:d,screen:p,dialog:m,globalShortcut:f}=electron;try{let e;try{e=require("./vendor/selfhost.js")}catch{e=require("../one/src/selfhost.js")}const t=e.plan({packaged:s.isPackaged,execPath:process.execPath,resourcesPath:process.resourcesPath,argv:process.argv.slice(1),invokedAs:path.basename(process.argv[1]||process.execPath)});if(t){const r=e.spawnOptions(t,process.env),n=require("node:child_process").spawnSync(r.exec,r.args,{stdio:"inherit",env:r.env}),o="number"==typeof n.status?n.status:1;return void s.exit(o)}}catch(e){s.isPackaged&&!/MODULE_NOT_FOUND/.test(String(e&&e.message))&&process.stderr.write(`aegis: terminal face hand-off failed: ${e&&e.message||e}\n`)}if(s.disableHardwareAcceleration(),s.commandLine.appendSwitch("disable-gpu"),s.commandLine.appendSwitch("disable-software-rasterizer"),s.commandLine.appendSwitch("disable-gpu-compositing"),s.commandLine.appendSwitch("disable-gpu-program-cache"),s.commandLine.appendSwitch("disable-features","UsePortalAccentColor,VaapiVideoDecoder,VaapiVideoEncoder"),process.argv.some(e=>/^--(log-level|enable-logging)/.test(e))||process.env.ELECTRON_ENABLE_LOGGING||s.commandLine.appendSwitch("log-level","3"),!s.requestSingleInstanceLock())return void s.quit();s.setName("aegis one");try{const e=s.getPath("userData"),t=path.dirname(e),r=["sessions.json","avatar","xp.json","queue.jsonl","memory.db","settings.json"],n=e=>{try{return fs.statSync(e).isDirectory()}catch{return!1}},o=e=>{try{return fs.statSync(e).size}catch{return-1}},a=e=>{try{return fs.readFileSync(path.join(e,"settings.json"),"utf8").includes('"__aegis"')}catch{return!1}},i=e=>{if(!n(e))return!1;let t;try{t=fs.readdirSync(e)}catch{return!1}return!!["sessions.json","avatar","xp.json","queue.jsonl"].some(e=>t.includes(e))||a(e)},c=t=>(()=>{try{return fs.realpathSync(t)===fs.realpathSync(e)}catch{return!1}})(),l=e=>n(e)&&0===fs.readdirSync(e).length,u=["AEGIS Desktop","AEGIS One","Electron","aegiscode-gui"].map(e=>path.join(t,e)).filter(e=>i(e)&&!c(e)).sort((e,t)=>o(path.join(t,"sessions.json"))-o(path.join(e,"sessions.json")))[0];if(u&&!i(e))try{if(!fs.existsSync(e)||l(e))fs.existsSync(e)&&fs.rmdirSync(e),fs.renameSync(u,e);else{const t=[];for(const n of r){const r=path.join(u,n),s=path.join(e,n);if(fs.existsSync(r)){if(fs.existsSync(s)){if(!("settings.json"===n&&a(u)&&!a(e)||"memory.db"===n&&o(r)>o(s)))continue;fs.rmSync(s,{recursive:!0,force:!0})}fs.renameSync(r,s),t.push(n)}}t.length&&console.warn(`aegis: adopted user state from ${u}: ${t.join(", ")}`)}}catch(t){console.warn(`aegis: could not move ${u} -> ${e} (${t&&t.message}); reading the old location instead`),s.setPath("userData",u)}try{const e=path.join(os.homedir(),".aegiscode","native-chat-history");if((e=>{try{return fs.statSync(e).isDirectory()}catch{return!1}})(e)){const t=fs.readdirSync(e).filter(e=>e.endsWith(".json")).sort(),r=new Set((sessionStore.listSessions(sessionStore.resolveStoreDir(null))||[]).map(e=>e&&e.id).filter(Boolean));let n=0;for(const o of t){let t=null;try{t=JSON.parse(fs.readFileSync(path.join(e,o),"utf8"))}catch{}if(!t||"object"!=typeof t||Array.isArray(t))continue;const s="string"==typeof t.createdAt&&t.createdAt||"string"==typeof t.created_at&&t.created_at||String(t.timestamp||"");if(!s)continue;let a=`native-${s.replace(/[^0-9T:.Z+-]/g,"")}`.slice(0,80);if(r.has(a)&&(a=`${a}-${o.replace(/\.json$/,"").slice(-24)}`),r.has(a))continue;const i=(Array.isArray(t.messages)?t.messages:t.history&&Array.isArray(t.history.messages)?t.history.messages:t.history&&Array.isArray(t.history)?t.history:t.entries&&Array.isArray(t.entries)?t.entries:[]).map(e=>{const t=void 0!==(e&&(e.content||e.text))?e.content||e.text:e&&"string"==typeof e.prompt?e.prompt:e&&"string"==typeof e.reply?e.reply:null;return null==t||""===t?null:{role:!e||"user"!==e.role&&"assistant"!==e.role?e&&"string"==typeof e.prompt?"user":e&&"string"==typeof e.reply?"assistant":"unknown":e.role,content:String(t)}}).filter(Boolean);if(!i.length)continue;const c=String(t.title||t.session&&t.session.title||"").trim();sessionStore.upsertSession(sessionStore.resolveStoreDir(null),{id:a,title:c||String((i.find(e=>"user"===e.role)||{}).content||"").slice(0,60),messages:i,cwd:"string"==typeof t.cwd?t.cwd:"",updatedAt:Date.parse(t.updatedAt||t.updated_at||t.createdAt||t.created_at||0)||Date.now(),origin:"native-chat",pending:!1}),r.add(a),n+=1}n&&console.warn(`aegis: imported ${n} conversation(s) from ${e}`)}}catch(e){console.warn(`aegis: native-chat import skipped: ${e&&e.message}`)}}catch(e){console.warn(`aegis: userData adoption skipped: ${e&&e.message}`)}if(envFile&&"function"==typeof envFile.loadEnvFile)try{const e=envFile.loadEnvFile();e.loose&&console.warn(`aegis: ${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it.`)}catch(e){console.warn(`aegis: could not read ${envFile.envFileFor()}: ${e&&e.message}`)}s.setAsDefaultProtocolClient(deepLink.PROTOCOL);let g=deepLink.parseDeepLinkArgv(process.argv);s.on("open-url",(e,t)=>{e.preventDefault();const r=deepLink.parseDeepLinkUrl(t);if(!r)return;const n="function"==typeof resolveTargetWindow?resolveTargetWindow():null;n&&!n.isDestroyed()?sendDeepLinkToWindow(n,r):g=r});const h=createClient(credentials.clientOptions()),y=resolveUserDataDir(s),{engine:k,sessionsDir:b,settingsDir:v,settings:S,avatar:w}=createEngine(h,{app:s,safeStorage:c,dir:y}),E=createAccountKey({aegis:h,credentials:credentials,persistKey:e=>S.setAegisKey(e),provision:(e,t)=>autoProvision.autoProvisionApiKey(e,t,{app:"desktop"}),describeFailure:autoProvision.provisionFailureText,onChange:e=>$(e)});let A=null;const M=createGoogleConnect({aegis:h,credentials:credentials,persistKey:e=>S.setAegisKey(e),openUrl:e=>!!isSafeExternalUrl(e)&&(l.openExternal(e),!0),googleSignIn:googleSignIn,driveConnect:driveConnectLib,driveUpload:driveUploadLib,conversationExport:conversationExportLib?{...conversationExportLib,toTranscript:e=>sessionStore.toMarkdown(e)}:null,getSession:e=>sessionStore.getSession(b,e),getAuthor:()=>{try{A||(A=createFingerprintService({dir:y,getVaultBackend:()=>S.vaultBackendConfig().backend}));const e=A.status();return e&&e.ok?e:null}catch{return null}},onAccountChange:()=>$(E.status()),machineFingerprint:()=>sharedFingerprint.machineFingerprint()}),_=Boolean(h.apiKey),D=autoProvision.autoProvisionApiKey(h,credentials,{app:"desktop"}).then(e=>{if(E.recordStartup(e),!e.key&&!h.apiKey){const t=e.error&&(e.error.status||e.error.message||String(e.error))||"no key returned";console.warn(`auto-provision: no account key from register-device (${t})`)}return e});try{const{wrapProviderKeyMirror:e}=require("./lib/provider-key-mirror.js"),t=e=>console.warn(`aegis: ${e}`);e(S,envFile,{onWarn:t}),k&&k.settings&&k.settings!==S&&e(k.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not wire the shared env-file key mirror: ${e&&e.message}`)}let C=null;const P=(e,t)=>{if(function(e){const t=e&&e.sender,r=t&&a.fromWebContents(t);if(!r||r.isDestroyed())return;if(r.isFocused()&&r.isVisible())return;if(!d||!d.isSupported())return;const n=new d({title:"aegis one",body:"Reply ready"});n.on("click",()=>{r.isDestroyed()||(r.isMinimized()&&r.restore(),r.isVisible()||r.show(),r.focus())}),n.show()}(e),C&&"function"==typeof C.note){const e=t&&(t.model||t.modelId)||void 0;C.note({sessionId:t&&t.sessionId||null,model:e})}};registerIpc(i,h,y,e=>{const t=S.setAegisKey(e);return e?credentials.saveApiKey(e):credentials.clearApiKey(),t},e=>l.openExternal(e),P,()=>providerRouteConfigured(k),()=>S.vaultBackendConfig().backend,w);const I=registerModelIpc(i,k,b,h,P,void 0,v,S);registerConfirmModeIpc(i,withAutoRoundsSwitch(createConfirmModeDispatch(S),I.modelDispatch)),registerConfirmModeIpc(i,createPermissionModeDispatch(S)),registerConfirmModeIpc(i,createFontScaleDispatch(S)),registerConfirmModeIpc(i,createAccentDispatch(S)),registerConfirmModeIpc(i,createDevModeDispatch(S)),registerConfirmModeIpc(i,createModelAutoSyncDispatch(S,k)),registerConfirmModeIpc(i,createVaultBackendDispatch(S)),registerConfirmModeIpc(i,createPermRulesDispatch(require("./lib/local/perm-store.js"))),registerConfirmModeIpc(i,createSandboxPolicyDispatch(S,require("./lib/local/sandbox.js"),{appDir:__dirname})),registerConfirmModeIpc(i,createCliFaceDispatch({appInfo:{packaged:s.isPackaged,resourcesPath:process.resourcesPath,appDir:__dirname,execPath:process.execPath,nodePath:process.execPath}})),createPtyIpc(i,{appInfo:{packaged:s.isPackaged,resourcesPath:process.resourcesPath,appDir:__dirname,execPath:process.execPath,nodePath:process.execPath}}),registerTelemetryIpc(i,createTelemetryDispatch(createTelemetry({dir:v,enabled:telemetryEnabled(process.env,S),appVersion:(()=>{try{return"function"==typeof s.getVersion?s.getVersion():""}catch{return""}})()}))),registerCovenantIpc(i,createCovenantDispatch(covenantModule));const T=registerQueueIpc(i,{engine:createQueueEngine(h,S),aegis:h}),x=createAutoDrain({proceed:()=>T.proceed(),settings:S,queue:queueModule,env:process.env,log:e=>{e&&"skip"!==e.type&&(("auto-drain-armed"===e.type||"auto-drain-disarmed"===e.type)&&!process.env.ELECTRON_ENABLE_LOGGING||console.log("[auto-drain]",e.type,e.reason||e.error||""))}});let R=null;C=createAutoMint({mint:e=>(R||(R=createFingerprintService({dir:y,getVaultBackend:()=>S.vaultBackendConfig().backend})),R.mint(e||{})),settings:S}),registerAutoIpc(i,createAutoDispatch({autoDrain:x,autoMint:C})),x.start(),C.start();let L=null,N=null;function q(){return N&&!N.isDestroyed()||(N=new a({width:560,height:320,show:!1,frame:!1,alwaysOnTop:!0,skipTaskbar:!0,resizable:!1,movable:!0,fullscreenable:!1,minimizable:!1,maximizable:!1,backgroundColor:"#0d1117",icon:iconForPlatform(resolveIconsDir(s.isPackaged,process.resourcesPath,__dirname),process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0}}),N.setMenuBarVisibility(!1),N.loadFile(path.join(__dirname,"renderer","quick.html")),N.webContents.on("before-input-event",(e,t)=>{"keyDown"!==t.type||"Escape"!==t.key||N.isDestroyed()||N.hide()}),N.on("blur",()=>{!N.isDestroyed()&&N.isVisible()&&N.hide()}),N.on("closed",()=>{N=null})),N}function U(){const e=q();e.isVisible()?e.hide():function(){const e=q(),t=p.getCursorScreenPoint(),r=p.getAllDisplays(),n=e.getBounds(),o=quickLauncherLib.computeQuickLauncherBounds({cursor:t,displays:r,size:{width:n.width,height:n.height}});e.setBounds(o),e.show(),e.focus()}()}resolveTargetWindow=()=>{if(L&&!L.isDestroyed())return L;const e=a.getFocusedWindow();return e&&!e.isDestroyed()&&e!==N?e:a.getAllWindows().find(e=>e!==N)||null};const F=createQuickLauncherDispatch(S,{isPackaged:s.isPackaged,applyConfig:function(e){if(f.unregisterAll(),!quickLauncherLib.shouldEnableGlobalShortcut({isPackaged:s.isPackaged,enabled:e.enabled}))return{active:!1,reason:null};try{if(!f.register(e.shortcut,U)){const t=`"${e.shortcut}" could not be registered — it may already be in use by another application.`;return console.warn(`[quick-launcher] ${t}`),{active:!1,reason:t}}return{active:!0,reason:null}}catch(t){const r=errorText(t);return console.warn(`[quick-launcher] failed to register shortcut "${e.shortcut}": ${r}`),{active:!1,reason:r}}},pushToMain:function(e,t){const r=t&&t.sender&&a.fromWebContents(t.sender);r&&!r.isDestroyed()&&r.hide();const n=L&&!L.isDestroyed()?L:a.getAllWindows().find(e=>e!==r)||null;return n?(n.webContents.send("aegis:quickLauncherPush",e||{}),n.isMinimized()&&n.restore(),n.isVisible()||n.show(),n.focus(),{ok:!0}):{ok:!1,reason:"no main window is open"}}});registerQuickLauncherIpc(i,F);let j=null;s.on("will-quit",()=>{j&&"function"==typeof j.stop&&j.stop(),closeMemoryIndex(),f.unregisterAll(),W&&"function"==typeof W.stop&&W.stop(),K&&clearInterval(K),K=null});let O=!1;s.on("before-quit",e=>{!O&&k&&"function"==typeof k.unloadLocalModels&&(e.preventDefault(),Promise.resolve().then(()=>k.unloadLocalModels()).catch(()=>{}).finally(()=>{O=!0,s.quit()}))});const B=new Set;function $(e){for(const t of B)t.isDestroyed()||t.webContents.send(ACCOUNT_STATUS_CHANNEL,e);H()}function H(){u.setApplicationMenu(buildAppMenu({app:s,Menu:u,BrowserWindow:a,updateManager:W,loggedIn:Boolean(h.apiKey)}))}const W=createUpdateManager({isPackaged:s.isPackaged,onStatus:function(e){for(const t of B)t.isDestroyed()||t.webContents.send("aegis:updateStatus",e)}});let K=null;registerUpdateIpc(i,W),i.handle("aegis:accountStatus",()=>E.status()),i.handle("aegis:setNavState",(e,t)=>{const r=t&&"object"==typeof t?t:{},n=Boolean(r.back),o=Boolean(r.forward);return n===navState.back&&o===navState.forward||(navState.back=n,navState.forward=o,H()),{ok:!0}}),i.handle("aegis:registerAccount",()=>E.registerAccount()),i.handle("aegis:driveSignIn",()=>M.signInWithGoogle()),i.handle("aegis:driveConnect",()=>M.connectDrive()),i.handle("aegis:driveStatus",()=>M.status()),i.handle("aegis:driveSyncMemory",()=>M.syncMemoryNow()),i.handle("aegis:driveBackupConversation",(e,t)=>M.backupConversation({sessionId:t&&t.sessionId})),i.handle("aegis:speechStatus",()=>{try{return speechHost.status({settings:readSpeechSettings(S)})}catch(e){return{enabled:!1,engine:"none",reason:e&&e.message||"dictation status failed"}}}),i.handle("aegis:speechSet",(e,t)=>{try{const e=t&&"object"==typeof t?t:{},r={...readSpeechSettings(S)};if("boolean"==typeof e.enabled&&(r.enabled=e.enabled),"string"==typeof e.engine&&(r.engine="local"===e.engine?"local":"none"),"string"==typeof e.model&&(r.model=e.model.trim()),"string"==typeof e.language&&(r.language=e.language.trim()||"auto"),null!=e.maxSeconds&&Number.isFinite(Number(e.maxSeconds))&&(r.maxSeconds=Math.min(600,Math.max(5,Math.round(Number(e.maxSeconds))))),!0===r.enabled){const e=speechHost.status({settings:{...r,enabled:!0}});if(!e.enabled)return{ok:!1,...e,settings:e.settings}}return S.setSharedPref("speech",r),{ok:!0,...speechHost.status({settings:r})}}catch(e){return{ok:!1,error:e&&e.message||"could not save dictation settings"}}}),i.handle("aegis:speechTranscribe",(e,t)=>{const r=t&&"object"==typeof t?t:{};return speechHost.transcribe(r.audio,{settings:readSpeechSettings(S),ext:r.ext}).catch(e=>({ok:!1,reason:e&&e.message||"transcription failed"}))}),i.handle("aegis:skillsList",()=>skillsHost.list()),i.handle("aegis:skillsRead",(e,t)=>skillsHost.read(t||{})),i.handle("aegis:skillsCreate",(e,t)=>skillsHost.create(t||{})),i.handle("aegis:skillsRemove",(e,t)=>skillsHost.remove(t||{})),i.handle("aegis:skillsImport",(e,t)=>skillsHost.importFromUrl(t||{})),registerExportIpc(i,sessionStore,b,e=>m.showSaveDialog(a.getFocusedWindow(),e),(e,t)=>fs.promises.writeFile(e,t,"utf8")),i.handle("aegis:credits",()=>{try{return creditsLib.creditsFromDisk({readText:e=>{const t=[path.join(__dirname,"..",e),path.join(__dirname,e),path.join(process.resourcesPath||"","app",e)];for(const e of t)try{return{path:e,text:fs.readFileSync(e,"utf8")}}catch{}return null}})}catch(e){return{program:{licence:creditsLib.LICENCE_ID,name:creditsLib.LICENCE_NAME,url:creditsLib.LICENCE_URL,source:creditsLib.SOURCE_URL,copyright:creditsLib.COPYRIGHT,notice:creditsLib.COPYRIGHT},documents:[],code:[],fonts:[],missing:["licensing","vendor","fonts"],error:String(e&&e.message||e)}}}),H();const Q=pathToFileURL(path.join(__dirname,"renderer","index.html")).href;function G(){const e=windowState.load(y),t=windowState.clampToDisplay(e,p.getAllDisplays(),{width:1080,height:720}),r=resolveIconsDir(s.isPackaged,process.resourcesPath,__dirname),n=new a({...t,minWidth:720,minHeight:480,show:!0,backgroundColor:"#0d1117",title:"aegis one",titleBarStyle:"hidden",titleBarOverlay:{color:"#111114",symbolColor:"#94a2b6",height:35},icon:iconForPlatform(r,process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0,spellcheck:!0}});e&&e.isMaximized&&n.maximize(),n.webContents.setWindowOpenHandler(({url:e})=>(isSafeExternalUrl(e)&&l.openExternal(e),{action:"deny"})),n.webContents.on("will-navigate",(e,t)=>{t!==Q&&(e.preventDefault(),isSafeExternalUrl(t)&&l.openExternal(t))});let o=null;function i(){if(n.isDestroyed())return;const e=n.isMaximized(),t=e?n.getNormalBounds():n.getBounds();windowState.save(y,{...t,isMaximized:e})}function c(){o&&clearTimeout(o),o=setTimeout(i,500)}return n.on("resize",c),n.on("move",c),n.on("close",()=>{o&&clearTimeout(o),i()}),n.loadFile(path.join(__dirname,"renderer","index.html")),B.add(n),L=n,n.on("closed",()=>{B.delete(n),L===n&&(L=null)}),n}s.whenReady().then(async()=>{const e=e=>{if("string"!=typeof e||!e)return!1;try{const t=new URL(e);return"file:"===t.protocol||/^(localhost|127\.0\.0\.1)$/.test(t.hostname)}catch{return!1}},t=t=>{if(!t||"function"!=typeof t.getURL)return!1;const r=t.getURL();return!!e(r)&&!/quick\.html(?:[?#]|$)/.test(r)};try{const r=electron.session;r.defaultSession.setPermissionRequestHandler((e,r,n,o)=>{if("media"!==r)return n(!1);if(!t(e))return n(!1);const s=o&&o.mediaTypes||[];return Array.isArray(s)&&s.length&&!s.includes("audio")||Array.isArray(s)&&s.includes("video")?n(!1):n(!0)}),r.defaultSession.setPermissionCheckHandler((r,n,o)=>"media"===n&&!!t(r)&&e(o))}catch(e){console.warn(`aegis: could not install the microphone permission handler: ${e&&e.message}`)}if(!credentials.normalizeApiKey(process.env[credentials.KEY_ENV])){const e=await D,t=startupKeyOverride({mintedKey:_?"":e.key,hostKey:credentials.normalizeApiKey(S.aegisRawKey())});if(t)credentials.saveApiKey(t),h.setApiKey(t);else{const e=credentials.preferNewest(S.aegisRawKey(),S.aegisKeySavedAt());e.key&&(h.setApiKey(e.key),"shared"===e.source&&S.setAegisKey(e.key))}}try{j&&"function"==typeof j.stop&&j.stop(),j=sharedPresence.createPresence({apiKey:h.apiKey,app:"desktop",version:s.getVersion(),platform:process.platform,install:sharedFingerprint.machineFingerprint(),queueDepth:()=>{try{return queueModule.readQueue(queueModule.queuePath()).filter(e=>e&&"pending"===e.status).length}catch{return 0}},autonomous:!1,log:(e,t)=>{"debug"!==e&&console.warn(t)}}),j.start()}catch(e){console.warn("presence: beacon not started",e&&e.message)}try{const{backfillProviderKeys:e}=require("./lib/provider-key-mirror.js"),t=e=>console.warn(`aegis: ${e}`),r=e(S,envFile,{onWarn:t});r.mirrored.length&&console.warn(`aegis: shared ${r.mirrored.join(", ")} key(s) with the other hosts (${envFile.envFileFor()})`),k&&k.settings&&k.settings!==S&&e(k.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not backfill the shared env-file key mirror: ${e&&e.message}`)}F.setConfig(S.quickLauncherConfig());const r=G();W.start(),function(){if(K)return;const e=()=>{Promise.resolve(k.modelAutoSyncRun()).then(e=>{if(e&&e.ran){if(e.added>0&&"function"==typeof k.refreshByokModels)try{k.refreshByokModels()}catch{}for(const t of B)t.isDestroyed()||t.webContents.send("aegis:modelSyncReport",e)}}).catch(()=>{})},t=setTimeout(e,6e5);"function"==typeof t.unref&&t.unref(),K=setInterval(e,216e5),"function"==typeof K.unref&&K.unref()}(),g&&sendDeepLinkToWindow(r,g)}),s.on("window-all-closed",()=>{"darwin"!==process.platform&&s.quit()}),s.on("activate",()=>{const e=a.getAllWindows();if(0===e.length)return void G();const t=resolveTargetWindow()||e[0];t.isMinimized()&&t.restore(),t.isVisible()||t.show(),t.focus()}),s.on("second-instance",(e,t)=>{const r=resolveTargetWindow(),n=deepLink.parseDeepLinkArgv(t);if(!r){const e=G();return void(n&&sendDeepLinkToWindow(e,n))}r.isMinimized()&&r.restore(),r.isVisible()||r.show(),r.focus(),n&&sendDeepLinkToWindow(r,n)})}electron&&electron.app&&bootstrap(),module.exports={memoryIndex:memoryIndex,closeMemoryIndex:closeMemoryIndex,createIpcDispatch:createIpcDispatch,registerIpc:registerIpc,providerRouteConfigured:providerRouteConfigured,IPC_PREFIX:"aegis:",MODEL_PREFIX:"model:",SYNC_PREFIX:"sync:",watchTopupCredit:watchTopupCredit,bankAmount:bankAmount,TOPUP_POLL_MS:TOPUP_POLL_MS,TOPUP_POLL_TRIES:TOPUP_POLL_TRIES,CHAT_DELTA_CHANNEL:"aegis:chatDelta",PTY_EVENT_CHANNEL:"aegis:ptyEvent",createPtyIpc:createPtyIpc,MENU_NEW_CHAT_CHANNEL:"aegis:menuNewChat",MENU_SEARCH_CHANNEL:"aegis:menuSearch",MENU_SEARCH_MEMORY_CHANNEL:"aegis:menuSearchMemory",MENU_CREDITS_CHANNEL:"aegis:menuCredits",MENU_PALETTE_CHANNEL:"aegis:menuPalette",MENU_TOGGLE_SIDEBAR_CHANNEL:"aegis:menuToggleSidebar",MENU_EXPORT_MARKDOWN_CHANNEL:"aegis:menuExportMarkdown",MENU_EXPORT_JSON_CHANNEL:"aegis:menuExportJson",MENU_FINGERPRINT_CHANNEL:"aegis:menuFingerprint",MENU_GOOGLE_DRIVE_CHANNEL:"aegis:menuGoogleDrive",DEEP_LINK_CHANNEL:"aegis:deepLink",UPDATE_STATUS_CHANNEL:"aegis:updateStatus",UPDATE_CHECK_INTERVAL_MS:144e5,taggedChunk:taggedChunk,maskKey:maskKey,createModelDispatch:createModelDispatch,DESKTOP_CLASSES:DESKTOP_CLASSES,readTextFileForPreview:readTextFileForPreview,PREVIEW_READ_MAX_BYTES:524288,ingestAttachment:ingestAttachment,nativeImageResizer:nativeImageResizer,createSyncDispatch:createSyncDispatch,registerModelIpc:registerModelIpc,createHeartbeatRetry:createHeartbeatRetry,describeSyncError:describeSyncError,HEARTBEAT_RETRY_BASE_MS:5e3,HEARTBEAT_RETRY_MAX_MS:3e4,createEngine:createEngine,resolveUserDataDir:resolveUserDataDir,importForeignMemory:importForeignMemory,importForeignSessions:importForeignSessions,isSafeExternalUrl:isSafeExternalUrl,createUpdateManager:createUpdateManager,createNpmUpdateManager:createNpmUpdateManager,installFailureText:installFailureText,resolveUpdateOwner:resolveUpdateOwner,createUpdateDispatch:createUpdateDispatch,describeRegistryFailure:describeRegistryFailure,UPDATE_RETRY_BACKOFF_MS:UPDATE_RETRY_BACKOFF_MS,registerUpdateIpc:registerUpdateIpc,buildAppMenu:buildAppMenu,createExportDispatch:createExportDispatch,registerExportIpc:registerExportIpc,safeExportBasename:safeExportBasename,sendDeepLinkToWindow:sendDeepLinkToWindow,QUICK_PREFIX:"quick:",QUICK_LAUNCHER_PUSH_CHANNEL:"aegis:quickLauncherPush",createQuickLauncherDispatch:createQuickLauncherDispatch,registerQuickLauncherIpc:registerQuickLauncherIpc,createConfirmModeDispatch:createConfirmModeDispatch,createDevModeDispatch:createDevModeDispatch,createModelAutoSyncDispatch:createModelAutoSyncDispatch,createVaultBackendDispatch:createVaultBackendDispatch,createPermRulesDispatch:createPermRulesDispatch,createSandboxPolicyDispatch:createSandboxPolicyDispatch,withAutoRoundsSwitch:withAutoRoundsSwitch,createTelemetryDispatch:createTelemetryDispatch,registerTelemetryIpc:registerTelemetryIpc,createCovenantDispatch:createCovenantDispatch,registerCovenantIpc:registerCovenantIpc,registerConfirmModeIpc:registerConfirmModeIpc,QUEUE_PREFIX:"queue:",QUEUE_PROGRESS_CHANNEL:"queue:progress",QUEUE_CHANGED_CHANNEL:"queue:changed",QUEUE_MAX_TASK_CHARS:8e3,QUEUE_MAX_ROUNDS:200,createQueueEngine:createQueueEngine,queueEngineWithDeniedApprovals:queueEngineWithDeniedApprovals,createQueueDispatch:createQueueDispatch,registerQueueIpc:registerQueueIpc,AUTO_PREFIX:"auto:",createAutoDispatch:createAutoDispatch,registerAutoIpc:registerAutoIpc};
8
+ copyright:creditsLib.COPYRIGHT,credits:`${creditsLib.LICENCE_NAME}\n${creditsLib.COPYRIGHT}\nSource: ${creditsLib.SOURCE_URL}\nHelp > Credits & licence lists the vendored third-party code and fonts.`});const a={label:"Check for Updates…",click:()=>r.check({announce:!0})},i={label:"New Chat",accelerator:"CmdOrCtrl+N",click:()=>sendToAppWindow(n,"aegis:menuNewChat")},c={label:"Search",accelerator:"CmdOrCtrl+K",click:()=>sendToAppWindow(n,"aegis:menuSearch")},l={label:"Command palette…",accelerator:"CmdOrCtrl+P",click:()=>sendToAppWindow(n,"aegis:menuPalette")},u={label:"Toggle sidebar",accelerator:"CmdOrCtrl+B",click:()=>sendToAppWindow(n,"aegis:menuToggleSidebar")},d={label:"Find in conversation",accelerator:"CmdOrCtrl+F",click:()=>sendToAppWindow(n,"aegis:menuFind")},p={label:"Go Back",accelerator:s?"Cmd+[":"Alt+Left",enabled:navState.back,click:()=>sendToAppWindow(n,"aegis:menuGoBack")},m={label:"Go Forward",accelerator:s?"Cmd+]":"Alt+Right",enabled:navState.forward,click:()=>sendToAppWindow(n,"aegis:menuGoForward")},f={label:"Search memory",accelerator:"CmdOrCtrl+Shift+K",visible:!1,click:()=>sendToAppWindow(n,"aegis:menuSearchMemory")},g={label:"Credits & Licence…",click:()=>sendToAppWindow(n,"aegis:menuCredits")},h={label:"Source Code",click:()=>{try{require("electron").shell.openExternal(creditsLib.SOURCE_URL)}catch{}}},y={label:"Save as…",accelerator:"CmdOrCtrl+S",click:()=>sendToAppWindow(n,"aegis:menuExportMarkdown")},k={label:"Export Session…",click:()=>sendToAppWindow(n,"aegis:menuExportJson")},b={label:"Authorship Panel…",click:()=>sendToAppWindow(n,"aegis:menuFingerprint")},v={label:"Google Drive Backup…",enabled:Boolean(o),click:()=>sendToAppWindow(n,"aegis:menuGoogleDrive")},S=[...s?[{label:e.getName(),submenu:[{role:"about"},a,{type:"separator"},g,h,{type:"separator"},{role:"services"},{type:"separator"},{role:"hide"},{role:"hideOthers"},{role:"unhide"},{type:"separator"},{role:"quit"}]}]:[],{label:"File",submenu:[i,{type:"separator"},y,k,{type:"separator"},...s?[]:[a,{type:"separator"}],s?{role:"close"}:{role:"quit"}]},{label:"Edit",submenu:[{role:"undo"},{role:"redo"},{type:"separator"},{role:"cut"},{role:"copy"},{role:"paste"},{role:"selectAll"},{type:"separator"},d]},{label:"View",submenu:[l,c,f,{type:"separator"},u,{type:"separator"},p,m,{type:"separator"},b,v,{type:"separator"},{role:"reload",accelerator:"CmdOrCtrl+R"},{role:"forceReload"},{type:"separator"},{role:"toggleDevTools",accelerator:"CmdOrCtrl+Shift+I"}]},{label:"Help",submenu:[g,h,{type:"separator"},...s?[]:[{role:"about"}]]}];return t.buildFromTemplate(S)}function bootstrap(){let e=null;const t=electron&&electron.app,n=electron&&electron.BrowserWindow,r=(n,r)=>{const o=r&&(r.stack||r.message)||r&&String(r)||String(r),s=`[${(new Date).toISOString()}] ${n}: ${o}\n`;try{process.stderr.write(`aegis-desktop: ${s}`)}catch{}try{e=e||path.join(t.getPath("userData"),"crash.log"),fs.appendFileSync(e,s,{mode:384})}catch{}return o};process.on("uncaughtException",e=>{r("uncaughtException",e),process.exitCode=1,t?t.exit(1):process.exit(1)}),process.on("unhandledRejection",e=>{r("unhandledRejection",e)}),t&&"function"==typeof t.on&&t.on("render-process-gone",(e,t,o)=>{if(r("render-process-gone",new Error(JSON.stringify(o))),o&&"clean-exit"!==o.reason)try{const e=n.getFocusedWindow&&n.getFocusedWindow()||(n.getAllWindows?n.getAllWindows()[0]:null);e&&!e.isDestroyed()&&e.reload()}catch{}});let o=!1;try{o=require("./lib/local/integrity.js").armed()}catch{o=!0,process.env.AEGIS_REDUCED_MODE="1",process.stderr.write("aegis-desktop: reduced mode (d1) — this build is not the one that was published.\n")}if(o){try{const{app:e}=electron;e&&"function"==typeof e.quit&&e.quit()}catch{}return}const{app:s,BrowserWindow:a,ipcMain:i,safeStorage:c,shell:l,Menu:u,Notification:d,screen:p,dialog:m,globalShortcut:f}=electron;try{let e;try{e=require("./vendor/selfhost.js")}catch{e=require("../one/src/selfhost.js")}const t=e.plan({packaged:s.isPackaged,execPath:process.execPath,resourcesPath:process.resourcesPath,argv:process.argv.slice(1),invokedAs:path.basename(process.argv[1]||process.execPath)});if(t){const n=e.spawnOptions(t,process.env),r=require("node:child_process").spawnSync(n.exec,n.args,{stdio:"inherit",env:n.env}),o="number"==typeof r.status?r.status:1;return void s.exit(o)}}catch(e){s.isPackaged&&!/MODULE_NOT_FOUND/.test(String(e&&e.message))&&process.stderr.write(`aegis: terminal face hand-off failed: ${e&&e.message||e}\n`)}if(s.disableHardwareAcceleration(),s.commandLine.appendSwitch("disable-gpu"),s.commandLine.appendSwitch("disable-software-rasterizer"),s.commandLine.appendSwitch("disable-gpu-compositing"),s.commandLine.appendSwitch("disable-gpu-program-cache"),s.commandLine.appendSwitch("disable-features","UsePortalAccentColor,VaapiVideoDecoder,VaapiVideoEncoder"),process.argv.some(e=>/^--(log-level|enable-logging)/.test(e))||process.env.ELECTRON_ENABLE_LOGGING||s.commandLine.appendSwitch("log-level","3"),!s.requestSingleInstanceLock())return void s.quit();s.setName("aegis one");try{const e=s.getPath("userData"),t=path.dirname(e),n=["sessions.json","avatar","xp.json","queue.jsonl","memory.db","settings.json"],r=e=>{try{return fs.statSync(e).isDirectory()}catch{return!1}},o=e=>{try{return fs.statSync(e).size}catch{return-1}},a=e=>{try{return fs.readFileSync(path.join(e,"settings.json"),"utf8").includes('"__aegis"')}catch{return!1}},i=e=>{if(!r(e))return!1;let t;try{t=fs.readdirSync(e)}catch{return!1}return!!["sessions.json","avatar","xp.json","queue.jsonl"].some(e=>t.includes(e))||a(e)},c=t=>(()=>{try{return fs.realpathSync(t)===fs.realpathSync(e)}catch{return!1}})(),l=e=>r(e)&&0===fs.readdirSync(e).length,u=["AEGIS Desktop","AEGIS One","Electron","aegiscode-gui"].map(e=>path.join(t,e)).filter(e=>i(e)&&!c(e)).sort((e,t)=>o(path.join(t,"sessions.json"))-o(path.join(e,"sessions.json")))[0];if(u&&!i(e))try{if(!fs.existsSync(e)||l(e))fs.existsSync(e)&&fs.rmdirSync(e),fs.renameSync(u,e);else{const t=[];for(const r of n){const n=path.join(u,r),s=path.join(e,r);if(fs.existsSync(n)){if(fs.existsSync(s)){if(!("settings.json"===r&&a(u)&&!a(e)||"memory.db"===r&&o(n)>o(s)))continue;fs.rmSync(s,{recursive:!0,force:!0})}fs.renameSync(n,s),t.push(r)}}t.length&&console.warn(`aegis: adopted user state from ${u}: ${t.join(", ")}`)}}catch(t){console.warn(`aegis: could not move ${u} -> ${e} (${t&&t.message}); reading the old location instead`),s.setPath("userData",u)}try{const e=path.join(os.homedir(),".aegiscode","native-chat-history");if((e=>{try{return fs.statSync(e).isDirectory()}catch{return!1}})(e)){const t=fs.readdirSync(e).filter(e=>e.endsWith(".json")).sort(),n=new Set((sessionStore.listSessions(sessionStore.resolveStoreDir(null))||[]).map(e=>e&&e.id).filter(Boolean));let r=0;for(const o of t){let t=null;try{t=JSON.parse(fs.readFileSync(path.join(e,o),"utf8"))}catch{}if(!t||"object"!=typeof t||Array.isArray(t))continue;const s="string"==typeof t.createdAt&&t.createdAt||"string"==typeof t.created_at&&t.created_at||String(t.timestamp||"");if(!s)continue;let a=`native-${s.replace(/[^0-9T:.Z+-]/g,"")}`.slice(0,80);if(n.has(a)&&(a=`${a}-${o.replace(/\.json$/,"").slice(-24)}`),n.has(a))continue;const i=(Array.isArray(t.messages)?t.messages:t.history&&Array.isArray(t.history.messages)?t.history.messages:t.history&&Array.isArray(t.history)?t.history:t.entries&&Array.isArray(t.entries)?t.entries:[]).map(e=>{const t=void 0!==(e&&(e.content||e.text))?e.content||e.text:e&&"string"==typeof e.prompt?e.prompt:e&&"string"==typeof e.reply?e.reply:null;return null==t||""===t?null:{role:!e||"user"!==e.role&&"assistant"!==e.role?e&&"string"==typeof e.prompt?"user":e&&"string"==typeof e.reply?"assistant":"unknown":e.role,content:String(t)}}).filter(Boolean);if(!i.length)continue;const c=String(t.title||t.session&&t.session.title||"").trim();sessionStore.upsertSession(sessionStore.resolveStoreDir(null),{id:a,title:c||String((i.find(e=>"user"===e.role)||{}).content||"").slice(0,60),messages:i,cwd:"string"==typeof t.cwd?t.cwd:"",updatedAt:Date.parse(t.updatedAt||t.updated_at||t.createdAt||t.created_at||0)||Date.now(),origin:"native-chat",pending:!1}),n.add(a),r+=1}r&&console.warn(`aegis: imported ${r} conversation(s) from ${e}`)}}catch(e){console.warn(`aegis: native-chat import skipped: ${e&&e.message}`)}}catch(e){console.warn(`aegis: userData adoption skipped: ${e&&e.message}`)}if(envFile&&"function"==typeof envFile.loadEnvFile)try{const e=envFile.loadEnvFile();e.loose&&console.warn(`aegis: ${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it.`)}catch(e){console.warn(`aegis: could not read ${envFile.envFileFor()}: ${e&&e.message}`)}s.setAsDefaultProtocolClient(deepLink.PROTOCOL);let g=deepLink.parseDeepLinkArgv(process.argv);s.on("open-url",(e,t)=>{e.preventDefault();const n=deepLink.parseDeepLinkUrl(t);if(!n)return;const r="function"==typeof resolveTargetWindow?resolveTargetWindow():null;r&&!r.isDestroyed()?sendDeepLinkToWindow(r,n):g=n});const h=createClient(credentials.clientOptions()),y=resolveUserDataDir(s),{engine:k,sessionsDir:b,settingsDir:v,settings:S,avatar:w}=createEngine(h,{app:s,safeStorage:c,dir:y}),E=createAccountKey({aegis:h,credentials:credentials,persistKey:e=>S.setAegisKey(e),provision:(e,t)=>autoProvision.autoProvisionApiKey(e,t,{app:"desktop"}),describeFailure:autoProvision.provisionFailureText,onChange:e=>W(e)});let A=null;const M=createGoogleConnect({aegis:h,credentials:credentials,persistKey:e=>S.setAegisKey(e),openUrl:e=>!!isSafeExternalUrl(e)&&(l.openExternal(e),!0),googleSignIn:googleSignIn,driveConnect:driveConnectLib,driveUpload:driveUploadLib,conversationExport:conversationExportLib?{...conversationExportLib,toTranscript:e=>sessionStore.toMarkdown(e)}:null,getSession:e=>sessionStore.getSession(b,e),getAuthor:()=>{try{A||(A=createFingerprintService({dir:y,getVaultBackend:()=>S.vaultBackendConfig().backend}));const e=A.status();return e&&e.ok?e:null}catch{return null}},onAccountChange:()=>W(E.status()),machineFingerprint:()=>sharedFingerprint.machineFingerprint()}),_=Boolean(h.apiKey),D=autoProvision.autoProvisionApiKey(h,credentials,{app:"desktop"}).then(e=>{if(E.recordStartup(e),!e.key&&!h.apiKey){const t=e.error&&(e.error.status||e.error.message||String(e.error))||"no key returned";console.warn(`auto-provision: no account key from register-device (${t})`)}return e});try{const{wrapProviderKeyMirror:e}=require("./lib/provider-key-mirror.js"),t=e=>console.warn(`aegis: ${e}`);e(S,envFile,{onWarn:t}),k&&k.settings&&k.settings!==S&&e(k.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not wire the shared env-file key mirror: ${e&&e.message}`)}let P=null;const C=(e,t)=>{if(function(e){const t=e&&e.sender,n=t&&a.fromWebContents(t);if(!n||n.isDestroyed())return;if(n.isFocused()&&n.isVisible())return;if(!d||!d.isSupported())return;const r=new d({title:"aegis one",body:"Reply ready"});r.on("click",()=>{n.isDestroyed()||(n.isMinimized()&&n.restore(),n.isVisible()||n.show(),n.focus())}),r.show()}(e),P&&"function"==typeof P.note){const e=t&&(t.model||t.modelId)||void 0;P.note({sessionId:t&&t.sessionId||null,model:e})}};registerIpc(i,h,y,e=>{const t=S.setAegisKey(e);return e?credentials.saveApiKey(e):credentials.clearApiKey(),t},e=>l.openExternal(e),C,()=>providerRouteConfigured(k),()=>S.vaultBackendConfig().backend,w);const I=registerModelIpc(i,k,b,h,C,void 0,v,S);registerConfirmModeIpc(i,withAutoRoundsSwitch(createConfirmModeDispatch(S),I.modelDispatch)),registerConfirmModeIpc(i,createPermissionModeDispatch(S)),registerConfirmModeIpc(i,createFontScaleDispatch(S)),registerConfirmModeIpc(i,createAccentDispatch(S)),registerConfirmModeIpc(i,createDevModeDispatch(S)),registerConfirmModeIpc(i,createModelAutoSyncDispatch(S,k)),registerConfirmModeIpc(i,createVaultBackendDispatch(S)),registerConfirmModeIpc(i,createPermRulesDispatch(require("./lib/local/perm-store.js"))),registerConfirmModeIpc(i,createSandboxPolicyDispatch(S,require("./lib/local/sandbox.js"),{appDir:__dirname})),registerConfirmModeIpc(i,createCliFaceDispatch({appInfo:{packaged:s.isPackaged,resourcesPath:process.resourcesPath,appDir:__dirname,execPath:process.execPath,nodePath:process.execPath}}));const T=createPtyIpc(i,{appInfo:{packaged:s.isPackaged,resourcesPath:process.resourcesPath,appDir:__dirname,execPath:process.execPath,nodePath:process.execPath}}),x=new Set;i.handle("aegis:openPtyWindow",()=>{const e=T.hello(0);if(!(e&&e.ok&&e.r&&e.r.caps||[]).includes("pty"))return{ok:!1,reason:"no PTY backend in this build"};const t=iconForPlatform(resolveIconsDir(s.isPackaged,process.resourcesPath,__dirname),process.platform),n=x.size%6*28,r=q&&!q.isDestroyed()?q.getBounds():{x:80,y:80},o=new a({width:900,height:560,x:r.x+60+n,y:r.y+60+n,minWidth:380,minHeight:240,show:!1,backgroundColor:"#0d1117",title:"Terminal — aegiscode",icon:t,webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0}});return o.setMenuBarVisibility(!1),x.add(o),o.on("closed",()=>x.delete(o)),o.once("ready-to-show",()=>{o.isDestroyed()||o.show()}),o.loadFile(path.join(__dirname,"renderer","pty-window.html")),{ok:!0}}),i.handle("aegis:closePtyWindow",e=>{const t=e&&e.sender?a.fromWebContents(e.sender):null;return t&&x.has(t)&&!t.isDestroyed()&&t.close(),{ok:!0}}),registerTelemetryIpc(i,createTelemetryDispatch(createTelemetry({dir:v,enabled:telemetryEnabled(process.env,S),appVersion:(()=>{try{return"function"==typeof s.getVersion?s.getVersion():""}catch{return""}})()}))),registerCovenantIpc(i,createCovenantDispatch(covenantModule));const R=registerQueueIpc(i,{engine:createQueueEngine(h,S),aegis:h}),L=createAutoDrain({proceed:()=>R.proceed(),settings:S,queue:queueModule,env:process.env,log:e=>{e&&"skip"!==e.type&&(("auto-drain-armed"===e.type||"auto-drain-disarmed"===e.type)&&!process.env.ELECTRON_ENABLE_LOGGING||console.log("[auto-drain]",e.type,e.reason||e.error||""))}});let N=null;P=createAutoMint({mint:e=>(N||(N=createFingerprintService({dir:y,getVaultBackend:()=>S.vaultBackendConfig().backend})),N.mint(e||{})),settings:S}),registerAutoIpc(i,createAutoDispatch({autoDrain:L,autoMint:P})),L.start(),P.start();let q=null,U=null;function F(){return U&&!U.isDestroyed()||(U=new a({width:560,height:320,show:!1,frame:!1,alwaysOnTop:!0,skipTaskbar:!0,resizable:!1,movable:!0,fullscreenable:!1,minimizable:!1,maximizable:!1,backgroundColor:"#0d1117",icon:iconForPlatform(resolveIconsDir(s.isPackaged,process.resourcesPath,__dirname),process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0}}),U.setMenuBarVisibility(!1),U.loadFile(path.join(__dirname,"renderer","quick.html")),U.webContents.on("before-input-event",(e,t)=>{"keyDown"!==t.type||"Escape"!==t.key||U.isDestroyed()||U.hide()}),U.on("blur",()=>{!U.isDestroyed()&&U.isVisible()&&U.hide()}),U.on("closed",()=>{U=null})),U}function j(){const e=F();e.isVisible()?e.hide():function(){const e=F(),t=p.getCursorScreenPoint(),n=p.getAllDisplays(),r=e.getBounds(),o=quickLauncherLib.computeQuickLauncherBounds({cursor:t,displays:n,size:{width:r.width,height:r.height}});e.setBounds(o),e.show(),e.focus()}()}resolveTargetWindow=()=>{if(q&&!q.isDestroyed())return q;const e=a.getFocusedWindow();return e&&!e.isDestroyed()&&e!==U?e:a.getAllWindows().find(e=>e!==U)||null};const O=createQuickLauncherDispatch(S,{isPackaged:s.isPackaged,applyConfig:function(e){if(f.unregisterAll(),!quickLauncherLib.shouldEnableGlobalShortcut({isPackaged:s.isPackaged,enabled:e.enabled}))return{active:!1,reason:null};try{if(!f.register(e.shortcut,j)){const t=`"${e.shortcut}" could not be registered — it may already be in use by another application.`;return console.warn(`[quick-launcher] ${t}`),{active:!1,reason:t}}return{active:!0,reason:null}}catch(t){const n=errorText(t);return console.warn(`[quick-launcher] failed to register shortcut "${e.shortcut}": ${n}`),{active:!1,reason:n}}},pushToMain:function(e,t){const n=t&&t.sender&&a.fromWebContents(t.sender);n&&!n.isDestroyed()&&n.hide();const r=q&&!q.isDestroyed()?q:a.getAllWindows().find(e=>e!==n)||null;return r?(r.webContents.send("aegis:quickLauncherPush",e||{}),r.isMinimized()&&r.restore(),r.isVisible()||r.show(),r.focus(),{ok:!0}):{ok:!1,reason:"no main window is open"}}});registerQuickLauncherIpc(i,O);let B=null;s.on("will-quit",()=>{B&&"function"==typeof B.stop&&B.stop(),closeMemoryIndex(),f.unregisterAll(),Q&&"function"==typeof Q.stop&&Q.stop(),G&&clearInterval(G),G=null});let $=!1;s.on("before-quit",e=>{!$&&k&&"function"==typeof k.unloadLocalModels&&(e.preventDefault(),Promise.resolve().then(()=>k.unloadLocalModels()).catch(()=>{}).finally(()=>{$=!0,s.quit()}))});const H=new Set;function W(e){for(const t of H)t.isDestroyed()||t.webContents.send(ACCOUNT_STATUS_CHANNEL,e);K()}function K(){u.setApplicationMenu(buildAppMenu({app:s,Menu:u,BrowserWindow:a,updateManager:Q,loggedIn:Boolean(h.apiKey)}))}const Q=createUpdateManager({isPackaged:s.isPackaged,onStatus:function(e){for(const t of H)t.isDestroyed()||t.webContents.send("aegis:updateStatus",e)}});let G=null;registerUpdateIpc(i,Q),i.handle("aegis:accountStatus",()=>E.status()),i.handle("aegis:setNavState",(e,t)=>{const n=t&&"object"==typeof t?t:{},r=Boolean(n.back),o=Boolean(n.forward);return r===navState.back&&o===navState.forward||(navState.back=r,navState.forward=o,K()),{ok:!0}}),i.handle("aegis:registerAccount",()=>E.registerAccount()),i.handle("aegis:driveSignIn",()=>M.signInWithGoogle()),i.handle("aegis:driveConnect",()=>M.connectDrive()),i.handle("aegis:driveStatus",()=>M.status()),i.handle("aegis:driveSyncMemory",()=>M.syncMemoryNow()),i.handle("aegis:driveBackupConversation",(e,t)=>M.backupConversation({sessionId:t&&t.sessionId})),i.handle("aegis:speechStatus",()=>{try{return speechHost.status({settings:readSpeechSettings(S)})}catch(e){return{enabled:!1,engine:"none",reason:e&&e.message||"dictation status failed"}}}),i.handle("aegis:speechSet",(e,t)=>{try{const e=t&&"object"==typeof t?t:{},n={...readSpeechSettings(S)};if("boolean"==typeof e.enabled&&(n.enabled=e.enabled),"string"==typeof e.engine&&(n.engine="local"===e.engine?"local":"none"),"string"==typeof e.model&&(n.model=e.model.trim()),"string"==typeof e.language&&(n.language=e.language.trim()||"auto"),null!=e.maxSeconds&&Number.isFinite(Number(e.maxSeconds))&&(n.maxSeconds=Math.min(600,Math.max(5,Math.round(Number(e.maxSeconds))))),!0===n.enabled){const e=speechHost.status({settings:{...n,enabled:!0}});if(!e.enabled)return{ok:!1,...e,settings:e.settings}}return S.setSharedPref("speech",n),{ok:!0,...speechHost.status({settings:n})}}catch(e){return{ok:!1,error:e&&e.message||"could not save dictation settings"}}}),i.handle("aegis:speechTranscribe",(e,t)=>{const n=t&&"object"==typeof t?t:{};return speechHost.transcribe(n.audio,{settings:readSpeechSettings(S),ext:n.ext}).catch(e=>({ok:!1,reason:e&&e.message||"transcription failed"}))}),i.handle("aegis:skillsList",()=>skillsHost.list()),i.handle("aegis:skillsRead",(e,t)=>skillsHost.read(t||{})),i.handle("aegis:skillsCreate",(e,t)=>skillsHost.create(t||{})),i.handle("aegis:skillsRemove",(e,t)=>skillsHost.remove(t||{})),i.handle("aegis:skillsImport",(e,t)=>skillsHost.importFromUrl(t||{})),registerExportIpc(i,sessionStore,b,e=>m.showSaveDialog(a.getFocusedWindow(),e),(e,t)=>fs.promises.writeFile(e,t,"utf8")),i.handle("aegis:credits",()=>{try{return creditsLib.creditsFromDisk({readText:e=>{const t=[path.join(__dirname,"..",e),path.join(__dirname,e),path.join(process.resourcesPath||"","app",e)];for(const e of t)try{return{path:e,text:fs.readFileSync(e,"utf8")}}catch{}return null}})}catch(e){return{program:{licence:creditsLib.LICENCE_ID,name:creditsLib.LICENCE_NAME,url:creditsLib.LICENCE_URL,source:creditsLib.SOURCE_URL,copyright:creditsLib.COPYRIGHT,notice:creditsLib.COPYRIGHT},documents:[],code:[],fonts:[],missing:["licensing","vendor","fonts"],error:String(e&&e.message||e)}}}),K();const V=pathToFileURL(path.join(__dirname,"renderer","index.html")).href;function z(){const e=windowState.load(y),t=windowState.clampToDisplay(e,p.getAllDisplays(),{width:1080,height:720}),n=resolveIconsDir(s.isPackaged,process.resourcesPath,__dirname),r=new a({...t,minWidth:720,minHeight:480,show:!0,backgroundColor:"#0d1117",title:"aegis one",titleBarStyle:"hidden",titleBarOverlay:{color:"#111114",symbolColor:"#94a2b6",height:35},icon:iconForPlatform(n,process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0,spellcheck:!0}});e&&e.isMaximized&&r.maximize(),r.webContents.setWindowOpenHandler(({url:e})=>(isSafeExternalUrl(e)&&l.openExternal(e),{action:"deny"})),r.webContents.on("will-navigate",(e,t)=>{t!==V&&(e.preventDefault(),isSafeExternalUrl(t)&&l.openExternal(t))});let o=null;function i(){if(r.isDestroyed())return;const e=r.isMaximized(),t=e?r.getNormalBounds():r.getBounds();windowState.save(y,{...t,isMaximized:e})}function c(){o&&clearTimeout(o),o=setTimeout(i,500)}return r.on("resize",c),r.on("move",c),r.on("close",()=>{o&&clearTimeout(o),i()}),r.loadFile(path.join(__dirname,"renderer","index.html")),H.add(r),q=r,r.on("closed",()=>{H.delete(r),q===r&&(q=null)}),r}s.whenReady().then(async()=>{const e=e=>{if("string"!=typeof e||!e)return!1;try{const t=new URL(e);return"file:"===t.protocol||/^(localhost|127\.0\.0\.1)$/.test(t.hostname)}catch{return!1}},t=t=>{if(!t||"function"!=typeof t.getURL)return!1;const n=t.getURL();return!!e(n)&&!/quick\.html(?:[?#]|$)/.test(n)};try{const n=electron.session;n.defaultSession.setPermissionRequestHandler((n,r,o,s)=>{if("clipboard-sanitized-write"===r){const t=n&&"function"==typeof n.getURL?n.getURL():null;return o(e(t))}if("media"!==r)return o(!1);if(!t(n))return o(!1);const a=s&&s.mediaTypes||[];return Array.isArray(a)&&a.length&&!a.includes("audio")||Array.isArray(a)&&a.includes("video")?o(!1):o(!0)}),n.defaultSession.setPermissionCheckHandler((n,r,o)=>("clipboard-sanitized-write"===r||"media"===r&&!!t(n))&&e(o))}catch(e){console.warn(`aegis: could not install the microphone permission handler: ${e&&e.message}`)}if(!credentials.normalizeApiKey(process.env[credentials.KEY_ENV])){const e=await D,t=startupKeyOverride({mintedKey:_?"":e.key,hostKey:credentials.normalizeApiKey(S.aegisRawKey())});if(t)credentials.saveApiKey(t),h.setApiKey(t);else{const e=credentials.preferNewest(S.aegisRawKey(),S.aegisKeySavedAt());e.key&&(h.setApiKey(e.key),"shared"===e.source&&S.setAegisKey(e.key))}}try{B&&"function"==typeof B.stop&&B.stop(),B=sharedPresence.createPresence({apiKey:h.apiKey,app:"desktop",version:s.getVersion(),platform:process.platform,install:sharedFingerprint.machineFingerprint(),queueDepth:()=>{try{return queueModule.readQueue(queueModule.queuePath()).filter(e=>e&&"pending"===e.status).length}catch{return 0}},autonomous:!1,log:(e,t)=>{"debug"!==e&&console.warn(t)}}),B.start()}catch(e){console.warn("presence: beacon not started",e&&e.message)}try{const{backfillProviderKeys:e}=require("./lib/provider-key-mirror.js"),t=e=>console.warn(`aegis: ${e}`),n=e(S,envFile,{onWarn:t});n.mirrored.length&&console.warn(`aegis: shared ${n.mirrored.join(", ")} key(s) with the other hosts (${envFile.envFileFor()})`),k&&k.settings&&k.settings!==S&&e(k.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not backfill the shared env-file key mirror: ${e&&e.message}`)}O.setConfig(S.quickLauncherConfig());const n=z();Q.start(),function(){if(G)return;const e=()=>{Promise.resolve(k.modelAutoSyncRun()).then(e=>{if(e&&e.ran){if(e.added>0&&"function"==typeof k.refreshByokModels)try{k.refreshByokModels()}catch{}for(const t of H)t.isDestroyed()||t.webContents.send("aegis:modelSyncReport",e)}}).catch(()=>{})},t=setTimeout(e,6e5);"function"==typeof t.unref&&t.unref(),G=setInterval(e,216e5),"function"==typeof G.unref&&G.unref()}(),g&&sendDeepLinkToWindow(n,g)}),s.on("window-all-closed",()=>{"darwin"!==process.platform&&s.quit()}),s.on("activate",()=>{const e=a.getAllWindows();if(0===e.length)return void z();const t=resolveTargetWindow()||e[0];t.isMinimized()&&t.restore(),t.isVisible()||t.show(),t.focus()}),s.on("second-instance",(e,t)=>{const n=resolveTargetWindow(),r=deepLink.parseDeepLinkArgv(t);if(!n){const e=z();return void(r&&sendDeepLinkToWindow(e,r))}n.isMinimized()&&n.restore(),n.isVisible()||n.show(),n.focus(),r&&sendDeepLinkToWindow(n,r)})}electron&&electron.app&&bootstrap(),module.exports={memoryIndex:memoryIndex,closeMemoryIndex:closeMemoryIndex,createIpcDispatch:createIpcDispatch,registerIpc:registerIpc,providerRouteConfigured:providerRouteConfigured,IPC_PREFIX:"aegis:",MODEL_PREFIX:"model:",SYNC_PREFIX:"sync:",watchTopupCredit:watchTopupCredit,bankAmount:bankAmount,TOPUP_POLL_MS:TOPUP_POLL_MS,TOPUP_POLL_TRIES:TOPUP_POLL_TRIES,CHAT_DELTA_CHANNEL:"aegis:chatDelta",PTY_EVENT_CHANNEL:"aegis:ptyEvent",createPtyIpc:createPtyIpc,MENU_NEW_CHAT_CHANNEL:"aegis:menuNewChat",MENU_SEARCH_CHANNEL:"aegis:menuSearch",MENU_SEARCH_MEMORY_CHANNEL:"aegis:menuSearchMemory",MENU_CREDITS_CHANNEL:"aegis:menuCredits",MENU_PALETTE_CHANNEL:"aegis:menuPalette",MENU_TOGGLE_SIDEBAR_CHANNEL:"aegis:menuToggleSidebar",MENU_EXPORT_MARKDOWN_CHANNEL:"aegis:menuExportMarkdown",MENU_EXPORT_JSON_CHANNEL:"aegis:menuExportJson",MENU_FINGERPRINT_CHANNEL:"aegis:menuFingerprint",MENU_GOOGLE_DRIVE_CHANNEL:"aegis:menuGoogleDrive",DEEP_LINK_CHANNEL:"aegis:deepLink",UPDATE_STATUS_CHANNEL:"aegis:updateStatus",UPDATE_CHECK_INTERVAL_MS:144e5,taggedChunk:taggedChunk,maskKey:maskKey,createModelDispatch:createModelDispatch,DESKTOP_CLASSES:DESKTOP_CLASSES,readTextFileForPreview:readTextFileForPreview,PREVIEW_READ_MAX_BYTES:524288,ingestAttachment:ingestAttachment,nativeImageResizer:nativeImageResizer,createSyncDispatch:createSyncDispatch,registerModelIpc:registerModelIpc,createHeartbeatRetry:createHeartbeatRetry,describeSyncError:describeSyncError,HEARTBEAT_RETRY_BASE_MS:5e3,HEARTBEAT_RETRY_MAX_MS:3e4,createEngine:createEngine,resolveUserDataDir:resolveUserDataDir,importForeignMemory:importForeignMemory,importForeignSessions:importForeignSessions,isSafeExternalUrl:isSafeExternalUrl,createUpdateManager:createUpdateManager,createNpmUpdateManager:createNpmUpdateManager,installFailureText:installFailureText,resolveUpdateOwner:resolveUpdateOwner,createUpdateDispatch:createUpdateDispatch,describeRegistryFailure:describeRegistryFailure,UPDATE_RETRY_BACKOFF_MS:UPDATE_RETRY_BACKOFF_MS,registerUpdateIpc:registerUpdateIpc,buildAppMenu:buildAppMenu,createExportDispatch:createExportDispatch,registerExportIpc:registerExportIpc,safeExportBasename:safeExportBasename,sendDeepLinkToWindow:sendDeepLinkToWindow,QUICK_PREFIX:"quick:",QUICK_LAUNCHER_PUSH_CHANNEL:"aegis:quickLauncherPush",createQuickLauncherDispatch:createQuickLauncherDispatch,registerQuickLauncherIpc:registerQuickLauncherIpc,createConfirmModeDispatch:createConfirmModeDispatch,createDevModeDispatch:createDevModeDispatch,createModelAutoSyncDispatch:createModelAutoSyncDispatch,createVaultBackendDispatch:createVaultBackendDispatch,createPermRulesDispatch:createPermRulesDispatch,createSandboxPolicyDispatch:createSandboxPolicyDispatch,withAutoRoundsSwitch:withAutoRoundsSwitch,createTelemetryDispatch:createTelemetryDispatch,registerTelemetryIpc:registerTelemetryIpc,createCovenantDispatch:createCovenantDispatch,registerCovenantIpc:registerCovenantIpc,registerConfirmModeIpc:registerConfirmModeIpc,QUEUE_PREFIX:"queue:",QUEUE_PROGRESS_CHANNEL:"queue:progress",QUEUE_CHANGED_CHANNEL:"queue:changed",QUEUE_MAX_TASK_CHARS:8e3,QUEUE_MAX_ROUNDS:200,createQueueEngine:createQueueEngine,queueEngineWithDeniedApprovals:queueEngineWithDeniedApprovals,createQueueDispatch:createQueueDispatch,registerQueueIpc:registerQueueIpc,AUTO_PREFIX:"auto:",createAutoDispatch:createAutoDispatch,registerAutoIpc:registerAutoIpc};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const foreignMemory=require("../client/foreign-memory.js");function createTools(e){if(!e||"object"!=typeof e)throw new TypeError("createTools(client): a client instance is required");const t=e,o={aegis_status:{description:"Check the current AEGIS account: validates the API key and reports the plan, email, and whether cloud memory is enabled. Call this first to confirm setup.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.verifyApiKey();return["Key valid: "+(e.valid?"yes":"no"),`Plan: ${e.plan||"unknown"}`,e.email?`Account: ${e.email}`:null,"Memory: "+(e.memory_token?"enabled (cloud sync available)":"not enabled"),`API base: ${t.apiBase}`].filter(Boolean).join("\n")}},aegis_ask:{description:"Send a prompt to AEGIS pooled inference, billed against the account's token bank. List models with aegis_list_models and pass any id as `model`; omit `model` to let the server pick its default. `mode` is a legacy server-side shorthand and is never required.",inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The user prompt / question."},model:{type:"string",description:"Pin any model id from aegis_list_models — or omit for the server default."},mode:{type:"string",description:"Legacy server-side shorthand (e.g. 'fast', 'smart', 'neo'). Optional — never defaulted client-side."},system:{type:"string",description:"Optional system instruction."},max_tokens:{type:"integer",description:"Max output tokens. The server enforces the true ceiling; omit for the server default.",minimum:1,maximum:64e3}},required:["prompt"],additionalProperties:!1},async run(e){const o=await t.chatCompletion({prompt:e.prompt,system:e.system,model:e.model,mode:e.mode,maxTokens:e.max_tokens}),s=o.choices&&o.choices[0]||{};return`${s.message&&s.message.content||"(empty response)"}\n\n— ${[o.model?`model: ${o.model}`:null,o.usage?`tokens: ${o.usage.total_tokens}`:null].filter(Boolean).join(" · ")}`}},aegis_list_models:{description:"List the exact models available to pin with aegis_ask's `model` argument — the server's model list is the truth, and omitting `model` uses the server default.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await t.listModels()).models||[];return e.length?["Pass one of these as aegis_ask's `model` argument:","",...e.map(e=>` ${e.id} (${(e.capabilities||[]).join(", ")})`)].join("\n"):"No pinnable models are currently configured on AEGIS."}},aegis_balance:{description:"Check the AEGIS token bank balance and recent spend. Call this before aegis_ask if you're unsure whether the account has funds, or to see what recent calls cost.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.tokenBankBalance(),o=[`Balance: €${Number(e.balance_eur||0).toFixed(2)}`],s=(e.ledger||[]).slice(0,5);if(s.length){o.push("","Recent activity:");for(const e of s){const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6,s=Math.abs(t),r=`${t<0?"-":"+"}€${s<.01?s.toFixed(4):s.toFixed(2)}`,i="topup"===e.kind?"top-up":e.kind||"",n=e.model_key||i||"",a=e.tokens_in||e.tokens_out?` ${e.tokens_in||0}/${e.tokens_out||0} tokens`:"";o.push(` ${e.created_at||""} ${n}${a} ${r}`)}}else o.push("No spend yet.");var r;return(e.balance_eur||0)<=0&&o.push("",`Balance is empty — top up at ${r="topup","function"==typeof t.promptUrl?t.promptUrl(r,"topup_bank"):`https://aegiscloud.org/go/${r}`}, or set your own provider key with aegis_byok_set to use aegis_ask for free at cost.`),o.join("\n")}},aegis_byok_providers:{description:"List every provider that accepts a Bring-Your-Own-Key on AEGIS: the exact provider id to pass to aegis_byok_set, the models each one unlocks, where to create the key, and the prefix a valid key starts with. Call this before aegis_byok_set so the user knows which key to go get rather than guessing a provider id.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await t.byokProviders()).providers||[];if(!e.length)return"AEGIS is not advertising any BYOK providers right now.";const o=["Set one with aegis_byok_set — pass the id exactly as shown:"];for(const t of e){const e=(t.models||[]).map(e=>"string"==typeof e?e:e&&e.id).filter(Boolean),s=t.configured?" ✓ set"+(t.masked?` (${t.masked})`:""):"";o.push(""),o.push(` ${t.id}${s}`),t.label&&o.push(` ${t.label}`),e.length&&o.push(` models: ${e.join(", ")}`),t.key_prefix&&o.push(` key starts with: ${t.key_prefix}`),t.key_url&&o.push(` get a key: ${t.key_url}`)}return o.join("\n")}},aegis_byok_status:{description:"List which providers have a Bring-Your-Own-Key configured on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …). A configured BYOK key is used automatically by aegis_ask instead of the pooled balance for that provider, so calls no longer cost AEGIS token-bank funds.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.byokStatus(),o=Object.entries(e||{});if(!o.length)return"No BYOK providers are configured. Run aegis_byok_providers to see what you can set.";let s={};try{const e=await t.byokProviders();for(const t of e.providers||[])s[t.id]=t.label||""}catch{}return`BYOK keys:\n${o.map(([e,t])=>{const o=t&&t.set;return` ${e}${s[e]?` ${s[e]}`:""}: ${o?`set (${t.masked})`:"not set"}`}).join("\n")}`}},aegis_byok_set:{description:"Set or remove a Bring-Your-Own-Key API key for a provider on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …; the server validates what it supports). Once set, aegis_ask uses that key directly for that provider instead of the pooled AEGIS balance — unlimited use at the user's own cost. Omit api_key to remove a previously set key.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Which provider this key is for (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …)."},api_key:{type:"string",description:"The provider's own API key. Omit to delete the stored key instead."}},required:["provider"],additionalProperties:!1},run:async e=>(await t.byokSet(e.provider,e.api_key)).message||(e.api_key?`${e.provider} key saved.`:`${e.provider} key removed.`)},aegis_memory_search:{description:"Search the user's AEGIS cloud memory (persists across machines and sessions). Returns the most relevant stored entries for a query.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search text. Empty returns most recent."},limit:{type:"integer",description:"Max entries (1-50). Default 5.",minimum:1,maximum:50}},required:["query"],additionalProperties:!1},async run(e){const o=(await t.memorySearch(e.query,e.limit||5)).entries||[];return o.length?o.map((e,t)=>{const o=e.timestamp||e.createdAt||"",s=e.tags&&e.tags.length?` [${e.tags.join(", ")}]`:"";return`${t+1}. ${e.content}${s}${o?`\n (${o})`:""}`}).join("\n"):`No memory entries matched "${e.query}".`}},aegis_memory_save:{description:"Save a note to the user's AEGIS cloud memory so it persists across machines and future sessions. Use for durable facts, decisions, or preferences the user asks you to remember.",inputSchema:{type:"object",properties:{content:{type:"string",description:"The fact/note to store."},tags:{type:"array",items:{type:"string"},description:"Optional tags."},importance:{type:"integer",description:"Optional 1-10 salience. Default 5.",minimum:1,maximum:10},session:{type:"string",description:"Optional session/label to group under."}},required:["content"],additionalProperties:!1},async run(e){const o={id:t.randomUUID(),content:e.content,role:"assistant",source:"claude-code",session:e.session||"claude-code",tags:e.tags||[],importance:"number"==typeof e.importance?e.importance:5,timestamp:(new Date).toISOString()};return`Saved ${(await t.memorySave(o)).saved||1} memory entry (id ${o.id}).`}},aegis_memory_import:{description:"Import memory and past conversation context from OTHER AI coding tools installed on this machine (Claude Code, Codex, Cursor, Gemini CLI, Continue, Goose, opencode, Windsurf, Zed, and a local AEGIS engine) into the user's AEGIS cloud memory. Scans read-only; nothing in the other tools' directories is modified. Defaults to a DRY RUN that only reports what it found — pass confirm:true to actually save. Entries are content-addressed, so re-running never duplicates.",inputSchema:{type:"object",properties:{confirm:{type:"boolean",description:"false (default) = report only. true = actually write the entries to AEGIS memory."},sources:{type:"array",items:{type:"string"},description:'Optional subset of source ids to import (e.g. ["claude-code"]). Omit for every source found on this machine.'},limit:{type:"integer",description:"Max entries to import (1-5000). Default 1000.",minimum:1,maximum:5e3}},additionalProperties:!1},async run(e){const o=e.limit||1e3,s=foreignMemory.scan({sources:e.sources,limit:o}),r=foreignMemory.describe(s);if(!s.entries.length)return`${r}\n\nNothing to import.`;if(!e.confirm)return[r,"",`Dry run — ${s.totals.entries} entries would be saved to AEGIS memory under ${s.totals.sourcesWithEntries} session(s) (${s.totals.skipped} skipped as too short/noise).`,"Call this tool again with confirm:true to save them."].join("\n");let i=0;const n=[];for(const o of foreignMemory.chunk(s.entries,200))try{const e=await t.memorySaveBatch(o);i+=e&&e.saved||o.length}catch(e){n.push(e.message);break}return n.length?`${r}\n\nSaved ${i} of ${s.totals.entries} entries, then stopped: ${n[0]}`:`${r}\n\nSaved ${i} entries to AEGIS memory. They are searchable now with aegis_memory_search.`}},aegis_memory_list:{description:"List the most recent entries in the user's AEGIS cloud memory. Useful to review what AEGIS already remembers.",inputSchema:{type:"object",properties:{limit:{type:"integer",description:"Max entries (1-50). Default 10.",minimum:1,maximum:50}},additionalProperties:!1},async run(e){const o=(await t.memoryList(e.limit||10)).entries||[];if(!o.length)return"AEGIS cloud memory is empty.";const s=o.map((e,t)=>`${t+1}. ${e.content}`).join("\n");return`Recent ${o.length} entries:\n${s}`}}};return{TOOLS:o,toolList:function(){return Object.entries(o).map(([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema}))}}}module.exports={createTools:createTools};
3
+ "use strict";const foreignMemory=require("../client/foreign-memory.js");function createTools(e,t={}){if(!e||"object"!=typeof e)throw new TypeError("createTools(client): a client instance is required");const o=t&&"object"==typeof t.localWiki?t.localWiki:null,i=e,s={aegis_status:{description:"Check the current AEGIS account: validates the API key and reports the plan, email, and whether cloud memory is enabled. Call this first to confirm setup.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await i.verifyApiKey();return["Key valid: "+(e.valid?"yes":"no"),`Plan: ${e.plan||"unknown"}`,e.email?`Account: ${e.email}`:null,"Memory: "+(e.memory_token?"enabled (cloud sync available)":"not enabled"),`API base: ${i.apiBase}`].filter(Boolean).join("\n")}},aegis_ask:{description:"Send a prompt to AEGIS pooled inference, billed against the account's token bank. List models with aegis_list_models and pass any id as `model`; omit `model` to let the server pick its default. `mode` is a legacy server-side shorthand and is never required.",inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The user prompt / question."},model:{type:"string",description:"Pin any model id from aegis_list_models — or omit for the server default."},mode:{type:"string",description:"Legacy server-side shorthand (e.g. 'fast', 'smart', 'neo'). Optional — never defaulted client-side."},system:{type:"string",description:"Optional system instruction."},max_tokens:{type:"integer",description:"Max output tokens. The server enforces the true ceiling; omit for the server default.",minimum:1,maximum:64e3}},required:["prompt"],additionalProperties:!1},async run(e){const t=await i.chatCompletion({prompt:e.prompt,system:e.system,model:e.model,mode:e.mode,maxTokens:e.max_tokens}),o=t.choices&&t.choices[0]||{};return`${o.message&&o.message.content||"(empty response)"}\n\n— ${[t.model?`model: ${t.model}`:null,t.usage?`tokens: ${t.usage.total_tokens}`:null].filter(Boolean).join(" · ")}`}},aegis_list_models:{description:"List the exact models available to pin with aegis_ask's `model` argument — the server's model list is the truth, and omitting `model` uses the server default.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await i.listModels()).models||[];return e.length?["Pass one of these as aegis_ask's `model` argument:","",...e.map(e=>` ${e.id} (${(e.capabilities||[]).join(", ")})`)].join("\n"):"No pinnable models are currently configured on AEGIS."}},aegis_balance:{description:"Check the AEGIS token bank balance and recent spend. Call this before aegis_ask if you're unsure whether the account has funds, or to see what recent calls cost.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await i.tokenBankBalance(),t=[`Balance: €${Number(e.balance_eur||0).toFixed(2)}`],o=(e.ledger||[]).slice(0,5);if(o.length){t.push("","Recent activity:");for(const e of o){const o=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6,i=Math.abs(o),s=`${o<0?"-":"+"}€${i<.01?i.toFixed(4):i.toFixed(2)}`,r="topup"===e.kind?"top-up":e.kind||"",n=e.model_key||r||"",a=e.tokens_in||e.tokens_out?` ${e.tokens_in||0}/${e.tokens_out||0} tokens`:"";t.push(` ${e.created_at||""} ${n}${a} ${s}`)}}else t.push("No spend yet.");var s;return(e.balance_eur||0)<=0&&t.push("",`Balance is empty — top up at ${s="topup","function"==typeof i.promptUrl?i.promptUrl(s,"topup_bank"):`https://aegiscloud.org/go/${s}`}, or set your own provider key with aegis_byok_set to use aegis_ask for free at cost.`),t.join("\n")}},aegis_byok_providers:{description:"List every provider that accepts a Bring-Your-Own-Key on AEGIS: the exact provider id to pass to aegis_byok_set, the models each one unlocks, where to create the key, and the prefix a valid key starts with. Call this before aegis_byok_set so the user knows which key to go get rather than guessing a provider id.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await i.byokProviders()).providers||[];if(!e.length)return"AEGIS is not advertising any BYOK providers right now.";const t=["Set one with aegis_byok_set — pass the id exactly as shown:"];for(const o of e){const e=(o.models||[]).map(e=>"string"==typeof e?e:e&&e.id).filter(Boolean),i=o.configured?" ✓ set"+(o.masked?` (${o.masked})`:""):"";t.push(""),t.push(` ${o.id}${i}`),o.label&&t.push(` ${o.label}`),e.length&&t.push(` models: ${e.join(", ")}`),o.key_prefix&&t.push(` key starts with: ${o.key_prefix}`),o.key_url&&t.push(` get a key: ${o.key_url}`)}return t.join("\n")}},aegis_byok_status:{description:"List which providers have a Bring-Your-Own-Key configured on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …). A configured BYOK key is used automatically by aegis_ask instead of the pooled balance for that provider, so calls no longer cost AEGIS token-bank funds.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await i.byokStatus(),t=Object.entries(e||{});if(!t.length)return"No BYOK providers are configured. Run aegis_byok_providers to see what you can set.";let o={};try{const e=await i.byokProviders();for(const t of e.providers||[])o[t.id]=t.label||""}catch{}return`BYOK keys:\n${t.map(([e,t])=>{const i=t&&t.set;return` ${e}${o[e]?` ${o[e]}`:""}: ${i?`set (${t.masked})`:"not set"}`}).join("\n")}`}},aegis_byok_set:{description:"Set or remove a Bring-Your-Own-Key API key for a provider on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …; the server validates what it supports). Once set, aegis_ask uses that key directly for that provider instead of the pooled AEGIS balance — unlimited use at the user's own cost. Omit api_key to remove a previously set key.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Which provider this key is for (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …)."},api_key:{type:"string",description:"The provider's own API key. Omit to delete the stored key instead."}},required:["provider"],additionalProperties:!1},run:async e=>(await i.byokSet(e.provider,e.api_key)).message||(e.api_key?`${e.provider} key saved.`:`${e.provider} key removed.`)},aegis_memory_search:{description:"Search the user's AEGIS cloud memory (persists across machines and sessions). Returns the most relevant stored entries for a query.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search text. Empty returns most recent."},limit:{type:"integer",description:"Max entries (1-50). Default 5.",minimum:1,maximum:50}},required:["query"],additionalProperties:!1},async run(e){const t=(await i.memorySearch(e.query,e.limit||5)).entries||[],s=o?o.search(e.query,e.limit||5):[];if(!s.length&&!t.length)return`No memory entries matched "${e.query}".`;const r=[];let n=0;for(const e of s)r.push(`${++n}. [wiki] ${e.title}: ${e.value??""}\n ${e.body}`);for(const e of t){const t=e.timestamp||e.createdAt||"",o=e.tags&&e.tags.length?` [${e.tags.join(", ")}]`:"";r.push(`${++n}. ${e.content}${o}${t?`\n (${t})`:""}`)}return r.join("\n")}},aegis_memory_save:{description:"Save a note to the user's AEGIS cloud memory so it persists across machines and future sessions. Use for durable facts, decisions, or preferences the user asks you to remember.",inputSchema:{type:"object",properties:{content:{type:"string",description:"The fact/note to store."},tags:{type:"array",items:{type:"string"},description:"Optional tags."},importance:{type:"integer",description:"Optional 1-10 salience. Default 5.",minimum:1,maximum:10},session:{type:"string",description:"Optional session/label to group under."}},required:["content"],additionalProperties:!1},async run(e){const t={id:i.randomUUID(),content:e.content,role:"assistant",source:"claude-code",session:e.session||"claude-code",tags:e.tags||[],importance:"number"==typeof e.importance?e.importance:5,timestamp:(new Date).toISOString()};return`Saved ${(await i.memorySave(t)).saved||1} memory entry (id ${t.id}).`}},aegis_memory_import:{description:"Import memory and past conversation context from OTHER AI coding tools installed on this machine (Claude Code, Codex, Cursor, Gemini CLI, Continue, Goose, opencode, Windsurf, Zed, and a local AEGIS engine) into the user's AEGIS cloud memory. Scans read-only; nothing in the other tools' directories is modified. Defaults to a DRY RUN that only reports what it found — pass confirm:true to actually save. Entries are content-addressed, so re-running never duplicates.",inputSchema:{type:"object",properties:{confirm:{type:"boolean",description:"false (default) = report only. true = actually write the entries to AEGIS memory."},sources:{type:"array",items:{type:"string"},description:'Optional subset of source ids to import (e.g. ["claude-code"]). Omit for every source found on this machine.'},limit:{type:"integer",description:"Max entries to import (1-5000). Default 1000.",minimum:1,maximum:5e3}},additionalProperties:!1},async run(e){const t=e.limit||1e3,o=foreignMemory.scan({sources:e.sources,limit:t}),s=foreignMemory.describe(o);if(!o.entries.length)return`${s}\n\nNothing to import.`;if(!e.confirm)return[s,"",`Dry run — ${o.totals.entries} entries would be saved to AEGIS memory under ${o.totals.sourcesWithEntries} session(s) (${o.totals.skipped} skipped as too short/noise).`,"Call this tool again with confirm:true to save them."].join("\n");let r=0;const n=[];for(const t of foreignMemory.chunk(o.entries,200))try{const e=await i.memorySaveBatch(t);r+=e&&e.saved||t.length}catch(e){n.push(e.message);break}return n.length?`${s}\n\nSaved ${r} of ${o.totals.entries} entries, then stopped: ${n[0]}`:`${s}\n\nSaved ${r} entries to AEGIS memory. They are searchable now with aegis_memory_search.`}},aegis_memory_list:{description:"List the most recent entries in the user's AEGIS cloud memory. Useful to review what AEGIS already remembers.",inputSchema:{type:"object",properties:{limit:{type:"integer",description:"Max entries (1-50). Default 10.",minimum:1,maximum:50}},additionalProperties:!1},async run(e){const t=(await i.memoryList(e.limit||10)).entries||[];if(!t.length)return"AEGIS cloud memory is empty.";const o=t.map((e,t)=>`${t+1}. ${e.content}`).join("\n");return`Recent ${t.length} entries:\n${o}`}}};return{TOOLS:s,toolList:function(){return Object.entries(s).map(([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema}))}}}module.exports={createTools:createTools};