aegisone 1.0.63 → 1.0.65
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/aegis.js +1 -1
- package/package.json +1 -1
- package/scripts/bump.mjs +1 -1
- package/scripts/bundle.js +1 -1
- package/scripts/postinstall.mjs +1 -1
- package/scripts/predist.mjs +1 -1
- package/src/child.js +1 -1
- package/src/dispatch.js +1 -1
- package/src/doctor.js +1 -1
- package/src/probes.js +1 -1
- package/src/productupdate.js +1 -1
- package/src/protocol.js +1 -1
- package/src/release.js +1 -1
- package/src/selfhost.js +1 -1
- package/vendor/cli/package.json +1 -1
- package/vendor/cli/scripts/check.mjs +1 -1
- package/vendor/cli/scripts/demo.mjs +1 -1
- package/vendor/cli/scripts/postinstall.mjs +1 -1
- package/vendor/cli/scripts/predist.mjs +1 -1
- package/vendor/cli/scripts/runtests.mjs +1 -1
- package/vendor/cli/src/app.js +1 -1
- package/vendor/cli/src/art.js +1 -1
- package/vendor/cli/src/chatflow.js +1 -1
- package/vendor/cli/src/checkpoint.js +1 -1
- package/vendor/cli/src/clipboard.js +1 -1
- package/vendor/cli/src/cloudsync.js +1 -1
- package/vendor/cli/src/commands.js +2 -2
- package/vendor/cli/src/config.js +1 -1
- package/vendor/cli/src/connect.js +1 -1
- package/vendor/cli/src/devrun.js +1 -1
- package/vendor/cli/src/diff.js +1 -1
- package/vendor/cli/src/diffview.js +1 -1
- package/vendor/cli/src/dream.js +1 -1
- package/vendor/cli/src/engine.js +1 -1
- package/vendor/cli/src/events.js +1 -1
- package/vendor/cli/src/export.js +1 -1
- package/vendor/cli/src/fingerprint.js +1 -1
- package/vendor/cli/src/format.js +1 -1
- package/vendor/cli/src/fuzzy.js +1 -1
- package/vendor/cli/src/history.js +1 -1
- package/vendor/cli/src/init.js +1 -1
- package/vendor/cli/src/markdown.js +1 -1
- package/vendor/cli/src/models.js +1 -1
- package/vendor/cli/src/overlays.js +1 -1
- package/vendor/cli/src/panels.js +1 -1
- package/vendor/cli/src/ping.js +1 -1
- package/vendor/cli/src/presence.js +1 -1
- package/vendor/cli/src/render.js +1 -1
- package/vendor/cli/src/screen.js +1 -1
- package/vendor/cli/src/screens.js +1 -1
- package/vendor/cli/src/secret.js +1 -1
- package/vendor/cli/src/securefs.js +1 -1
- package/vendor/cli/src/settings.js +1 -1
- package/vendor/cli/src/signup.js +1 -1
- package/vendor/cli/src/summarize.js +1 -1
- package/vendor/cli/src/sysdiag.js +1 -1
- package/vendor/cli/src/theme.js +1 -1
- package/vendor/cli/src/title.js +1 -1
- package/vendor/cli/src/todos.js +1 -1
- package/vendor/cli/src/tokens.js +1 -1
- package/vendor/cli/src/topup.js +1 -1
- package/vendor/cli/src/update.js +1 -1
- package/vendor/cli/vendor/client/aegis.js +1 -1
- package/vendor/cli/vendor/client/attest.js +1 -1
- package/vendor/cli/vendor/client/authorship-key.js +1 -1
- package/vendor/cli/vendor/client/auto-provision.js +1 -1
- package/vendor/cli/vendor/client/brain-catalog.js +1 -1
- package/vendor/cli/vendor/client/byok-catalog.js +1 -1
- package/vendor/cli/vendor/client/catalog-client.js +1 -1
- package/vendor/cli/vendor/client/conversation-export.js +1 -1
- package/vendor/cli/vendor/client/credentials.js +1 -1
- package/vendor/cli/vendor/client/credits.js +1 -1
- package/vendor/cli/vendor/client/drive-connect.js +1 -1
- package/vendor/cli/vendor/client/env-file.js +1 -1
- package/vendor/cli/vendor/client/fingerprint.js +1 -1
- package/vendor/cli/vendor/client/foreign-memory.js +1 -1
- package/vendor/cli/vendor/client/foreign-sessions.js +1 -1
- package/vendor/cli/vendor/client/google-signin.js +1 -1
- package/vendor/cli/vendor/client/hooks.js +1 -1
- package/vendor/cli/vendor/client/model-discovery.js +1 -1
- package/vendor/cli/vendor/client/model-sync.js +1 -1
- package/vendor/cli/vendor/client/naming.js +1 -1
- package/vendor/cli/vendor/client/platform.js +1 -1
- package/vendor/cli/vendor/client/prefs.js +1 -1
- package/vendor/cli/vendor/client/presence.js +1 -1
- package/vendor/cli/vendor/client/record-vault.js +2 -2
- package/vendor/cli/vendor/client/session-search.js +1 -1
- package/vendor/cli/vendor/client/session-store.js +1 -1
- package/vendor/cli/vendor/client/skills.js +1 -1
- package/vendor/cli/vendor/client/topup.js +1 -1
- package/vendor/cli/vendor/client/touch.js +1 -1
- package/vendor/cli/vendor/client/update.js +1 -1
- package/vendor/cli/vendor/client/user-models.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/attachments.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/context.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/local.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/perm-rules.js +5 -0
- package/vendor/cli/vendor/desktop/lib/local/perm-store.js +5 -0
- package/vendor/cli/vendor/desktop/lib/local/perm-write.js +5 -0
- package/vendor/cli/vendor/desktop/lib/local/pro-sessions.js +3 -1
- package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/repeat-guard.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/spill.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/verify-stop.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -1
- package/vendor/cli/vendor/desktop/lib/settings.js +1 -1
- package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/cli/vendor/hosts/install.js +1 -1
- package/vendor/cli/vendor/hosts/openai-shim.js +1 -1
- package/vendor/cli/vendor/hosts/spec.js +1 -1
- package/vendor/cli/vendor/hosts/targets.js +1 -1
- package/vendor/cli/vendor/mcp/admission.js +1 -1
- package/vendor/cli/vendor/mcp/server.js +1 -1
- package/vendor/cli/vendor/mcp/tools.js +1 -1
- package/vendor/cli/vendor/one/src/child.js +1 -1
- package/vendor/cli/vendor/one/src/protocol.js +1 -1
- package/vendor/cli/vendor/one/src/selfhost.js +1 -1
- package/vendor/desktop/bin/aegis.js +1 -1
- package/vendor/desktop/lib/auto.js +1 -1
- package/vendor/desktop/lib/avatar/companion.js +1 -1
- package/vendor/desktop/lib/avatar/cosmetics.js +1 -1
- package/vendor/desktop/lib/avatar/holder-turn.js +1 -1
- package/vendor/desktop/lib/avatar/holders.js +1 -1
- package/vendor/desktop/lib/avatar/identity.js +1 -1
- package/vendor/desktop/lib/avatar/level.js +1 -1
- package/vendor/desktop/lib/avatar/mirror.js +1 -1
- package/vendor/desktop/lib/avatar/persona.js +1 -1
- package/vendor/desktop/lib/avatar/profile.js +1 -1
- package/vendor/desktop/lib/avatar/register.js +1 -1
- package/vendor/desktop/lib/avatar/store.js +1 -1
- package/vendor/desktop/lib/avatar/transfer.js +1 -1
- package/vendor/desktop/lib/avatar/turn.js +1 -1
- package/vendor/desktop/lib/avatar/voice.js +1 -1
- package/vendor/desktop/lib/avatar/xp.js +1 -1
- package/vendor/desktop/lib/deep-link.js +1 -1
- package/vendor/desktop/lib/local/attachments.js +1 -1
- package/vendor/desktop/lib/local/autonomous.js +1 -1
- package/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/desktop/lib/local/cli-face.js +1 -1
- package/vendor/desktop/lib/local/context.js +1 -1
- package/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/lib/local/entitlement.js +1 -1
- package/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/lib/local/local.js +1 -1
- package/vendor/desktop/lib/local/perm-rules.js +5 -0
- package/vendor/desktop/lib/local/perm-store.js +5 -0
- package/vendor/desktop/lib/local/perm-write.js +5 -0
- package/vendor/desktop/lib/local/pro-sessions.js +3 -1
- package/vendor/desktop/lib/local/prompt.js +1 -1
- package/vendor/desktop/lib/local/pty-host.js +1 -1
- package/vendor/desktop/lib/local/queue.js +1 -1
- package/vendor/desktop/lib/local/repeat-guard.js +1 -1
- package/vendor/desktop/lib/local/session-rounds.js +1 -1
- package/vendor/desktop/lib/local/spill.js +1 -1
- package/vendor/desktop/lib/local/telemetry.js +1 -1
- package/vendor/desktop/lib/local/turn-guard.js +1 -1
- package/vendor/desktop/lib/local/verify-stop.js +1 -1
- package/vendor/desktop/lib/local/worktree-lock.js +1 -1
- package/vendor/desktop/lib/provider-key-mirror.js +1 -1
- package/vendor/desktop/lib/quick-launcher.js +1 -1
- package/vendor/desktop/lib/settings.js +1 -1
- package/vendor/desktop/lib/skills-host.js +1 -1
- package/vendor/desktop/lib/speech-host.js +1 -1
- package/vendor/desktop/lib/sync/memory-store.js +1 -1
- package/vendor/desktop/lib/sync/persist-gate.js +1 -1
- package/vendor/desktop/lib/window-state.js +1 -1
- package/vendor/desktop/package.json +1 -1
- package/vendor/desktop/preload.js +3 -1
- package/vendor/desktop/renderer/app.js +3 -3
- package/vendor/desktop/renderer/avatar/assemble.js +1 -1
- package/vendor/desktop/renderer/avatar/avatar.js +1 -1
- package/vendor/desktop/renderer/avatar/cards.js +1 -1
- package/vendor/desktop/renderer/avatar/hud.js +1 -1
- package/vendor/desktop/renderer/avatar/pane.js +1 -1
- package/vendor/desktop/renderer/avatar/parts.js +1 -1
- package/vendor/desktop/renderer/commands.js +1 -1
- package/vendor/desktop/renderer/companion.js +1 -1
- package/vendor/desktop/renderer/composer-triggers.js +1 -1
- package/vendor/desktop/renderer/dictation.js +1 -1
- package/vendor/desktop/renderer/diff.js +1 -1
- package/vendor/desktop/renderer/diffview.js +1 -1
- package/vendor/desktop/renderer/fingerprint.js +2 -2
- package/vendor/desktop/renderer/index.html +10 -4
- package/vendor/desktop/renderer/library.js +1 -1
- package/vendor/desktop/renderer/markdown.js +1 -1
- package/vendor/desktop/renderer/palette-filter.js +1 -1
- package/vendor/desktop/renderer/provider-toolbar.js +1 -1
- package/vendor/desktop/renderer/providers.js +1 -1
- package/vendor/desktop/renderer/pty-frame.css +35 -0
- package/vendor/desktop/renderer/pty-frame.html +47 -0
- package/vendor/desktop/renderer/pty-panel.js +1 -1
- package/vendor/desktop/renderer/quick.js +1 -1
- package/vendor/desktop/renderer/settings-skills.js +1 -1
- package/vendor/desktop/renderer/shortcuts.js +1 -1
- package/vendor/desktop/renderer/stream-policy.js +1 -1
- package/vendor/desktop/renderer/style.css +22 -0
- package/vendor/desktop/renderer/transcript-view.js +1 -1
- package/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/desktop/renderer/welcome-rows.js +1 -1
- package/vendor/desktop/vendor/aegis.js +1 -1
- package/vendor/desktop/vendor/attest.js +1 -1
- package/vendor/desktop/vendor/authorship-key.js +1 -1
- package/vendor/desktop/vendor/auto-provision.js +1 -1
- package/vendor/desktop/vendor/brain-catalog.js +1 -1
- package/vendor/desktop/vendor/byok-catalog.js +1 -1
- package/vendor/desktop/vendor/catalog-client.js +1 -1
- package/vendor/desktop/vendor/conversation-export.js +1 -1
- package/vendor/desktop/vendor/credentials.js +1 -1
- package/vendor/desktop/vendor/credits.js +1 -1
- package/vendor/desktop/vendor/drive-connect.js +1 -1
- package/vendor/desktop/vendor/env-file.js +1 -1
- package/vendor/desktop/vendor/faces/cli/bin/aegiscode.js +2 -2
- package/vendor/desktop/vendor/faces/cli/package.json +1 -1
- package/vendor/desktop/vendor/faces/cli/scripts/check.mjs +1 -1
- package/vendor/desktop/vendor/faces/cli/scripts/demo.mjs +1 -1
- package/vendor/desktop/vendor/faces/cli/scripts/postinstall.mjs +1 -1
- package/vendor/desktop/vendor/faces/cli/scripts/predist.mjs +1 -1
- package/vendor/desktop/vendor/faces/cli/scripts/runtests.mjs +1 -1
- package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/art.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/autonomous.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/caps.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/chatflow.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/checkpoint.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/clipboard.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/cloudsync.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/commands.js +2 -2
- package/vendor/desktop/vendor/faces/cli/src/config.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/connect.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/devrun.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/diff.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/diffview.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/dream.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/engine.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/events.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/export.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/fingerprint.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/format.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/fuzzy.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/history.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/init.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/limits.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/markdown.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/mcp.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/models.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/overlays.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/panels.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/permissions.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/ping.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/presence.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/provenance.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/render.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/screen.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/screens.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/secret.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/securefs.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/settings.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/signup.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/summarize.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/sysdiag.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/theme.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/title.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/todos.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/tokens.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/topup.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/update.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/aegis.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/attest.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/authorship-key.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/auto-provision.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/brain-catalog.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/catalog-client.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/conversation-export.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/credentials.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/credits.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/drive-connect.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/env-file.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/fingerprint.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-memory.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-sessions.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/google-signin.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/hooks.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/model-discovery.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/model-sync.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/platform.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/presence.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/record-vault.js +2 -2
- package/vendor/desktop/vendor/faces/cli/vendor/client/session-search.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/session-store.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/skills.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/topup.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/touch.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/update.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/user-models.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/attachments.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/autonomous.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/context.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/entitlement.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/exec-plan.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/local.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-rules.js +2 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-store.js +3 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-write.js +2 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/pro-sessions.js +3 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/queue.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/repeat-guard.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/session-rounds.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/shell.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/spill.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/turn-guard.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/verify-stop.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/worktree-lock.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +3 -3
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/hosts/install.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/hosts/openai-shim.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/hosts/spec.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/hosts/targets.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/admission.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/server.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/tools.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/child.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/protocol.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/selfhost.js +1 -1
- package/vendor/desktop/vendor/fingerprint.js +1 -1
- package/vendor/desktop/vendor/foreign-memory.js +1 -1
- package/vendor/desktop/vendor/foreign-sessions.js +1 -1
- package/vendor/desktop/vendor/google-signin.js +1 -1
- package/vendor/desktop/vendor/hooks.js +1 -1
- package/vendor/desktop/vendor/model-discovery.js +1 -1
- package/vendor/desktop/vendor/model-sync.js +1 -1
- package/vendor/desktop/vendor/naming.js +1 -1
- package/vendor/desktop/vendor/platform.js +1 -1
- package/vendor/desktop/vendor/prefs.js +1 -1
- package/vendor/desktop/vendor/presence.js +1 -1
- package/vendor/desktop/vendor/protocol.js +1 -1
- package/vendor/desktop/vendor/record-vault.js +2 -2
- package/vendor/desktop/vendor/selfhost.js +1 -1
- package/vendor/desktop/vendor/session-search.js +1 -1
- package/vendor/desktop/vendor/session-store.js +1 -1
- package/vendor/desktop/vendor/skills.js +1 -1
- package/vendor/desktop/vendor/topup.js +1 -1
- package/vendor/desktop/vendor/touch.js +1 -1
- package/vendor/desktop/vendor/update.js +1 -1
- package/vendor/desktop/vendor/user-models.js +1 -1
|
@@ -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{gitRoot:gitRoot,gitStatusSnapshot:gitStatusSnapshot}=require("./git-scope.js"),GIT_FLAGS_WITH_ARG=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path"]);function tokenize(t){const e=[];for(const n of String(t||"").split(/[|;&\n]+/)){const t=[],r=/"([^"]*)"|'([^']*)'|(\S+)/g;let s;for(;s=r.exec(n);)t.push(s[1]??s[2]??s[3]);t.length&&e.push(t)}return e}function gitInvocation(t){const e=t.findIndex(
|
|
3
|
+
"use strict";const{gitRoot:gitRoot,gitStatusSnapshot:gitStatusSnapshot}=require("./git-scope.js"),GIT_FLAGS_WITH_ARG=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path"]);function tokenize(t){const e=[];for(const n of String(t||"").split(/[|;&\n]+/)){const t=[],r=/"([^"]*)"|'([^']*)'|(\S+)/g;let s;for(;s=r.exec(n);)t.push(s[1]??s[2]??s[3]);t.length&&e.push(t)}return e}function gitInvocation(t){const e=t.findIndex(t=>"git"===t||t.endsWith("/git"));if(-1===e)return null;let n=e+1;for(;n<t.length&&t[n].startsWith("-");)n+=GIT_FLAGS_WITH_ARG.has(t[n])?2:1;return n>=t.length?null:{sub:t[n],args:t.slice(n+1)}}function namedPaths(t){const e=t.indexOf("--");return-1!==e?t.slice(e+1).filter(t=>!t.startsWith("-")):t.filter(t=>!t.startsWith("-"))}const isTreeMark=t=>"."===t||"./"===t||"*"===t||"./*"===t,hasForce=t=>t.some(t=>"-f"===t||"--force"===t||/^-[a-zA-Z]*f/.test(t));function judge(t,e){const n=namedPaths(e),r=0===n.length||n.some(isTreeMark);switch(t){case"checkout":return e.includes("--")||hasForce(e)?{what:"checkout of uncommitted changes",scope:r?"tree":"paths",paths:n}:r&&n.length?{what:"checkout . (tree-wide restore)",scope:"tree",paths:n}:null;case"restore":return{what:"restore (discards uncommitted changes)",scope:r?"tree":"paths",paths:n};case"reset":return e.includes("--hard")?{what:"reset --hard",scope:"tree",paths:[]}:null;case"clean":return hasForce(e)?{what:"clean -f (deletes untracked files)",scope:"tree",paths:[]}:null;case"stash":{const t=e.find(t=>!t.startsWith("-"));return"list"===t||"show"===t?null:{what:`stash ${t||"push"} (uncommitted changes across the tree)`,scope:"tree",paths:[]}}case"worktree":{const t=e.find(t=>!t.startsWith("-"));return"remove"===t||"prune"===t?{what:`worktree ${t}`,scope:"tree",paths:[]}:null}default:return null}}function classifyDestructive(t){for(const e of tokenize(t)){const t=gitInvocation(e);if(!t)continue;const n=judge(t.sub,t.args);if(n)return{destructive:!0,...n}}return{destructive:!1}}function beginTurnGuard(t){const e=gitRoot(t),n=e?gitStatusSnapshot(t):null;return{root:e,cwd:t,before:n,startedAt:Date.now(),written:new Set,active:Boolean(e&&n)}}function toRel(t,e){let n=String(e||"");return n?(t.root&&n.startsWith(t.root)&&(n=n.slice(t.root.length).replace(/^[/\\]/,"")),n.split("\\").join("/")):null}function recordWrite(t,e){if(!t||!t.active)return;const n=toRel(t,e);n&&t.written.add(n)}function foreignSince(t){if(!t||!t.active)return[];const e=gitStatusSnapshot(t.cwd);if(!e)return[];const n=[];for(const[r,s]of e)t.written.has(r)||t.before.has(r)&&t.before.get(r)===s&&n.push(r);return n.sort()}function concurrentSince(t){if(!t||!t.active)return[];const e=gitStatusSnapshot(t.cwd);if(!e)return[];const n=[];for(const[r]of e)t.written.has(r)||t.before.has(r)||n.push(r);return n.sort()}function blocksDestructive(t,e){const n=classifyDestructive(e);if(!n.destructive)return{ok:!0};if(!t||!t.active)return{ok:!0};let r=foreignSince(t),s=concurrentSince(t).filter(t=>!r.includes(t)),o=[];if("tree"===n.scope)o=[...r,...s];else{const t=new Set(n.paths.map(t=>t.replace(/^\.\//,""))),e=e=>e.filter(e=>t.has(e)||t.has("./"+e));r=e(r),s=e(s),o=[...r,...s]}if(!o.length)return{ok:!0,what:n.what};const i=[];return r.length&&i.push(`${r.length} hold another agent's uncommitted work: `+r.slice(0,8).join(", ")+(r.length>8?` (+${r.length-8} more)`:"")),s.length&&i.push(`${s.length} changed since this turn began and were not written by this session: ${s.slice(0,8).join(", ")}`+(s.length>8?` (+${s.length-8} more)`:"")),{ok:!1,what:n.what,scope:n.scope,foreign:r,unattributed:s,reason:`refusing \`${n.what}\` in ${t.root}: `+("tree"===n.scope?"it is tree-scoped and would discard work it did not create — ":"it targets a path that is not yours to discard — ")+i.join("; ")+". Name only the paths you mean, or take the worktree lock first."}}module.exports={classifyDestructive:classifyDestructive,beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,foreignSince:foreignSince,concurrentSince:concurrentSince,blocksDestructive:blocksDestructive};
|
|
@@ -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 CODE_EXT=new Set([".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts",".py",".rb",".go",".rs",".java",".kt",".kts",".scala",".swift",".c",".h",".cc",".cpp",".hpp",".cxx",".hh",".m",".mm",".cs",".fs",".php",".pl",".pm",".lua",".r",".jl",".dart",".ex",".exs",".erl",".hrl",".hs",".clj",".cljs",".ml",".mli",".sh",".bash",".zsh",".fish",".ps1",".sql",".vue",".svelte",".zig",".nim",".cr",".v",".sv",".sol",".tf"]),EXEC_TOOLS=new Set(["exec"]),NUDGE="You edited %s and the turn is ending, but no command has been run since that edit. Editing a file proves it compiles no more than describing it did. Run the project's check now — its tests, a type check, or at minimum the file's own linter — and report what it printed. If you already know the change cannot be checked by a command (a comment, a docs string, a config value), say so explicitly and finish; do not claim the change \"works\" without evidence.",NUDGE_WITH_CMD='You edited %s and the turn is ending, but no command has been run since that edit. Editing a file proves it compiles no more than describing it did. The check for this repo is likely `%s` (%s) — run it and report what it printed. If you disagree with that command, run what actually checks this change. If the change cannot be checked by a command (a comment, a docs string, a config value), say so explicitly and finish; do not claim the change "works" without evidence.',MODES=new Set(["off","dark","enforce"]);function resolveMode(e){const t=String(e&&e.mode||"").trim().toLowerCase();if(MODES.has(t))return t;const n=String(process.env.AEGIS_VERIFY_STOP||"").trim().toLowerCase();return MODES.has(n)?n:"dark"}function beginVerifyGuard(e){const t=resolveMode(e);return{mode:t,cwd:e&&e.cwd||null,active:"off"!==t,dirty:[],ranSince:!1,nudged:!1,fired:0}}function extOf(e){const t=String(e||"").split(/[/\\]/).pop()||"",n=t.lastIndexOf(".");return n<=0?"":t.slice(n).toLowerCase()}function isCodePath(e){return CODE_EXT.has(extOf(e))}function recordMutation(e,t){e&&e.active&&isCodePath(t)&&(e.dirty.push(String(t)),e.ranSince=!1)}function recordExec(e){e&&e.active&&(e.ranSince=!0,e.dirty=[])}function shouldNudge(e){if(!e||!e.active)return{nudge:!1};if(!e.dirty.length)return{nudge:!1};if(e.ranSince)return{nudge:!1};if(e.nudged)return{nudge:!1};const t=e.dirty.slice(-3),n=t.join(", ")+(e.dirty.length>3?` (+${e.dirty.length-3} more)`:"");if(e.fired=1,"enforce"!==e.mode)return{nudge:!1,fired:!0,paths:t};e.nudged=!0;let i=null;if(e.cwd)try{const{detectCheckCommand:t}=require("./check-command.js");i=t(e.cwd,e.dirty[e.dirty.length-1])}catch{i=null}if(i){const e=[n,i.cmd,i.why];let r=0;return{nudge:!0,text:NUDGE_WITH_CMD.replace(/%s/g,(
|
|
3
|
+
"use strict";const CODE_EXT=new Set([".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts",".py",".rb",".go",".rs",".java",".kt",".kts",".scala",".swift",".c",".h",".cc",".cpp",".hpp",".cxx",".hh",".m",".mm",".cs",".fs",".php",".pl",".pm",".lua",".r",".jl",".dart",".ex",".exs",".erl",".hrl",".hs",".clj",".cljs",".ml",".mli",".sh",".bash",".zsh",".fish",".ps1",".sql",".vue",".svelte",".zig",".nim",".cr",".v",".sv",".sol",".tf"]),EXEC_TOOLS=new Set(["exec"]),NUDGE="You edited %s and the turn is ending, but no command has been run since that edit. Editing a file proves it compiles no more than describing it did. Run the project's check now — its tests, a type check, or at minimum the file's own linter — and report what it printed. If you already know the change cannot be checked by a command (a comment, a docs string, a config value), say so explicitly and finish; do not claim the change \"works\" without evidence.",NUDGE_WITH_CMD='You edited %s and the turn is ending, but no command has been run since that edit. Editing a file proves it compiles no more than describing it did. The check for this repo is likely `%s` (%s) — run it and report what it printed. If you disagree with that command, run what actually checks this change. If the change cannot be checked by a command (a comment, a docs string, a config value), say so explicitly and finish; do not claim the change "works" without evidence.',MODES=new Set(["off","dark","enforce"]);function resolveMode(e){const t=String(e&&e.mode||"").trim().toLowerCase();if(MODES.has(t))return t;const n=String(process.env.AEGIS_VERIFY_STOP||"").trim().toLowerCase();return MODES.has(n)?n:"dark"}function beginVerifyGuard(e){const t=resolveMode(e);return{mode:t,cwd:e&&e.cwd||null,active:"off"!==t,dirty:[],ranSince:!1,nudged:!1,fired:0}}function extOf(e){const t=String(e||"").split(/[/\\]/).pop()||"",n=t.lastIndexOf(".");return n<=0?"":t.slice(n).toLowerCase()}function isCodePath(e){return CODE_EXT.has(extOf(e))}function recordMutation(e,t){e&&e.active&&isCodePath(t)&&(e.dirty.push(String(t)),e.ranSince=!1)}function recordExec(e){e&&e.active&&(e.ranSince=!0,e.dirty=[])}function shouldNudge(e){if(!e||!e.active)return{nudge:!1};if(!e.dirty.length)return{nudge:!1};if(e.ranSince)return{nudge:!1};if(e.nudged)return{nudge:!1};const t=e.dirty.slice(-3),n=t.join(", ")+(e.dirty.length>3?` (+${e.dirty.length-3} more)`:"");if(e.fired=1,"enforce"!==e.mode)return{nudge:!1,fired:!0,paths:t};e.nudged=!0;let i=null;if(e.cwd)try{const{detectCheckCommand:t}=require("./check-command.js");i=t(e.cwd,e.dirty[e.dirty.length-1])}catch{i=null}if(i){const e=[n,i.cmd,i.why];let r=0;return{nudge:!0,text:NUDGE_WITH_CMD.replace(/%s/g,()=>String(e[r++])),paths:t,cmd:i.cmd}}return{nudge:!0,text:NUDGE.replace("%s",n),paths:t}}module.exports={beginVerifyGuard:beginVerifyGuard,recordMutation:recordMutation,recordExec:recordExec,shouldNudge:shouldNudge,resolveMode:resolveMode,isCodePath:isCodePath,extOf:extOf,EXEC_TOOLS:EXEC_TOOLS,CODE_EXT:CODE_EXT,NUDGE:NUDGE};
|
|
@@ -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 fs=require("node:fs"),path=require("node:path"),os=require("node:os"),crypto=require("node:crypto");function worktreeLockDir(){if(process.env.AEGISCODE_WORKTREE_LOCK_DIR)return process.env.AEGISCODE_WORKTREE_LOCK_DIR;if(process.env.AEGISCODEX_WORKTREE_LOCK_DIR)return process.env.AEGISCODEX_WORKTREE_LOCK_DIR;const r=process.env.AEGISCODE_HOME||process.env.AEGISCODEX_HOME||path.join(os.homedir(),".aegiscode");return path.join(r,"worktree-locks")}const DEFAULT_WORKTREE_WAIT_MS=66e4,NOOP_TOKEN="(no-worktree)";function canonical(r){if(!r)return null;const e=path.resolve(String(r));try{return fs.realpathSync(e)}catch{return e}}function worktreeLockPath(r){if(!r)return null;const e=crypto.createHash("sha1").update(canonical(r)).digest("hex").slice(0,16);return path.join(worktreeLockDir(),e+".lock")}function pidAlive(r){try{return process.kill(r,0),!0}catch{return!1}}function readHolder(r){try{return JSON.parse(fs.readFileSync(worktreeLockPath(r),"utf8"))}catch{return null}}function worktreeLockHolder(r){if(!r)return null;const e=readHolder(r);return e?{pid:e.pid,token:e.token,since:e.since,root:e.root||canonical(r),session:e.session||null}:null}function isWorktreeLocked(r){if(!r)return!1;const e=readHolder(r),o=Number(e&&e.pid);if(!Number.isInteger(o)||o<=0||!pidAlive(o)){try{fs.unlinkSync(worktreeLockPath(r))}catch{}return!1}return!0}function tryAcquire(r,e,o){try{fs.mkdirSync(worktreeLockDir(),{recursive:!0});const t=fs.openSync(worktreeLockPath(r),"wx");return fs.writeFileSync(t,JSON.stringify({pid:process.pid,token:e,since:Date.now(),root:canonical(r),session:o&&o.session||null})),fs.closeSync(t),!0}catch(r){return!r||"EEXIST"!==r.code}}function releaseWorktreeLock(r,e){if(!r||!e||e===NOOP_TOKEN)return;const o=readHolder(r);if(o&&o.token===e)try{fs.unlinkSync(worktreeLockPath(r))}catch{}}async function acquireWorktreeLock(r,{waitMs:e=
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),os=require("node:os"),crypto=require("node:crypto");function worktreeLockDir(){if(process.env.AEGISCODE_WORKTREE_LOCK_DIR)return process.env.AEGISCODE_WORKTREE_LOCK_DIR;if(process.env.AEGISCODEX_WORKTREE_LOCK_DIR)return process.env.AEGISCODEX_WORKTREE_LOCK_DIR;const r=process.env.AEGISCODE_HOME||process.env.AEGISCODEX_HOME||path.join(os.homedir(),".aegiscode");return path.join(r,"worktree-locks")}const DEFAULT_WORKTREE_WAIT_MS=66e4,NOOP_TOKEN="(no-worktree)";function canonical(r){if(!r)return null;const e=path.resolve(String(r));try{return fs.realpathSync(e)}catch{return e}}function worktreeLockPath(r){if(!r)return null;const e=crypto.createHash("sha1").update(canonical(r)).digest("hex").slice(0,16);return path.join(worktreeLockDir(),e+".lock")}function pidAlive(r){try{return process.kill(r,0),!0}catch{return!1}}function readHolder(r){try{return JSON.parse(fs.readFileSync(worktreeLockPath(r),"utf8"))}catch{return null}}function worktreeLockHolder(r){if(!r)return null;const e=readHolder(r);return e?{pid:e.pid,token:e.token,since:e.since,root:e.root||canonical(r),session:e.session||null}:null}function isWorktreeLocked(r){if(!r)return!1;const e=readHolder(r),o=Number(e&&e.pid);if(!Number.isInteger(o)||o<=0||!pidAlive(o)){try{fs.unlinkSync(worktreeLockPath(r))}catch{}return!1}return!0}function tryAcquire(r,e,o){try{fs.mkdirSync(worktreeLockDir(),{recursive:!0});const t=fs.openSync(worktreeLockPath(r),"wx");return fs.writeFileSync(t,JSON.stringify({pid:process.pid,token:e,since:Date.now(),root:canonical(r),session:o&&o.session||null})),fs.closeSync(t),!0}catch(r){return!r||"EEXIST"!==r.code}}function releaseWorktreeLock(r,e){if(!r||!e||e===NOOP_TOKEN)return;const o=readHolder(r);if(o&&o.token===e)try{fs.unlinkSync(worktreeLockPath(r))}catch{}}async function acquireWorktreeLock(r,{waitMs:e=66e4,pollMs:o=200,signal:t,session:n=null}={}){if(!r)return NOOP_TOKEN;const c=crypto.randomUUID(),i=Date.now()+e;for(;;){if(t&&t.aborted)return null;if(tryAcquire(r,c,{session:n}))return c;if(isWorktreeLocked(r)){if(Date.now()>=i)return null;await new Promise(r=>setTimeout(r,o))}}}class WorktreeBusyError extends Error{constructor(r,e){super(`working tree ${r} is locked by pid ${e?e.pid:"?"}`),this.name="WorktreeBusyError",this.root=r,this.holder=e||null}}async function withWorktreeLock(r,e,o){const t=await acquireWorktreeLock(r,e);if(!t)throw new WorktreeBusyError(r,worktreeLockHolder(r));try{return await o()}finally{releaseWorktreeLock(r,t)}}module.exports={DEFAULT_WORKTREE_WAIT_MS:66e4,worktreeLockDir:worktreeLockDir,worktreeLockPath:worktreeLockPath,worktreeLockHolder:worktreeLockHolder,isWorktreeLocked:isWorktreeLocked,releaseWorktreeLock:releaseWorktreeLock,acquireWorktreeLock:acquireWorktreeLock,WorktreeBusyError:WorktreeBusyError,withWorktreeLock:withWorktreeLock};
|
|
@@ -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 fs=require("node:fs"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),prefs=(()=>{try{return require("../../client/prefs.js")}catch{return require("../vendor/prefs.js")}})(),credentials=(()=>{try{return require("../../client/credentials.js")}catch{return require("../vendor/credentials.js")}})(),localTransport=require("./local/local.js"),LOCAL_NAMESPACE="local",SETTINGS_FILE="settings.json",AEGIS_KEY_NAMESPACE="__aegis",LEGACY_AEGIS_NAMESPACE="aegis",QUICK_LAUNCHER_NAMESPACE="__quickLauncher",DEFAULT_QUICK_LAUNCHER_SHORTCUT="CmdOrCtrl+Shift+Space",VAULT_BACKEND_NAMESPACE="__vaultBackend",DEFAULT_VAULT_BACKEND="aegiscloud",VAULT_BACKEND_VALUES=Object.freeze(["aegiscloud","drive","off"]),CONFIRM_MODE_NAMESPACE="__confirmMode",FONT_SCALE_NAMESPACE="__fontScale",ACCENT_NAMESPACE="__accent",MEMORY_PERSIST_NAMESPACE="__memoryPersist",AVATAR_NAMESPACE="__avatar",TELEMETRY_NAMESPACE="__telemetry",AUTO_DRAIN_NAMESPACE="__autoDrain",AUTO_MINT_NAMESPACE="__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS=6e4,AUTO_DRAIN_INTERVAL_MIN_MS=15e3,AUTO_DRAIN_INTERVAL_MAX_MS=18e5,RESERVED_NAMESPACES=Object.freeze(["__aegis","aegis","__quickLauncher","__vaultBackend","__confirmMode","__memoryPersist","__avatar","__telemetry","__autoDrain","__autoMint"]),AVATAR_MOTION_MODES=Object.freeze(["system","full","minimal"]);function isReservedNamespace(e){return RESERVED_NAMESPACES.includes(e)}function maskKey(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}const IS_WIN32="win32"===process.platform;function restrictFile(e){if(IS_WIN32){const n=process.env.USERNAME||process.env.USER||process.env.USERDOMAIN;if(!n)return void console.error(`[settings] cannot restrict ${e}: no current user to grant (USERNAME unset)`);try{execFileSync("icacls",[e,"/inheritance:r","/grant:r",`${n}:(F)`],{stdio:"ignore"})}catch(n){console.error(`[settings] failed to restrict ACL on ${e}: ${n.message}`)}}else try{fs.chmodSync(e,384)}catch(n){console.error(`[settings] failed to chmod ${e} to 0600: ${n.message}`)}}function createSettingsStore({dir:e,safeStorage:n,prefsDir:t,env:r}={}){if(!e)throw new Error("createSettingsStore requires a storage dir");const o=path.join(e,SETTINGS_FILE),i=(()=>{const e=null==t?"":String(t).trim();return e?path.resolve(e):credentials.aegisHome(r)})(),s=(()=>{try{return prefs.adopt({dir:i,legacyDir:e})}catch(e){return(process.env.AEGISCODE_DEBUG||process.env.AEGIS_HIST_DEBUG)&&process.stderr.write(`aegis-desktop: shared-preference adoption failed: ${e.message}\n`),{adopted:!1,keys:[],reason:`adoption failed: ${e.message}`}}})();function a(){try{return prefs.load({dir:i})}catch{return{}}}function c(e){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);const n=a()[e];return void 0===n?null:n}const u=()=>Boolean(n&&"function"==typeof n.isEncryptionAvailable&&n.isEncryptionAvailable());function l(e){return null==e?null:u()?n.encryptString(String(e)).toString("base64"):Buffer.from(String(e),"utf8").toString("base64")}function _(e){if(!e)return null;try{const t=Buffer.from(String(e),"base64");return u()?n.decryptString(t):t.toString("utf8")}catch{return null}}function d(){try{return JSON.parse(fs.readFileSync(o,"utf8"))||{}}catch{return{}}}function f(e){fs.mkdirSync(path.dirname(o),{recursive:!0});const n=`${o}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(e,null,2),{mode:384}),fs.renameSync(n,o),restrictFile(o)}function A(e){if(isReservedNamespace(e))throw new Error(`reserved namespace "${e}" is not a provider config — use setAegisKey()/aegisRawKey() for the AEGIS key`)}function E(e){const n=d()[e]||{},t=_(n.key);return{provider:e,baseURL:n.baseURL||"",configured:Boolean(t),keyMask:maskKey(t)}}function S(){const e=_((d().__aegis||{}).key);return{configured:Boolean(e),keyMask:maskKey(e)}}function m(e){return Number.isFinite(e)?Math.min(1.3,Math.max(.85,Math.round(100*e)/100)):1}function M(){return m((d().__fontScale||{}).scale)}const p=["default","cobalt","amber"];function g(e){const n="string"==typeof e?e.trim().toLowerCase():"";return p.includes(n)?n:"default"}function y(){return g((d().__accent||{}).name)}function N(){const e=d().__quickLauncher||{},n="string"==typeof e.shortcut&&e.shortcut.trim()?e.shortcut.trim():"CmdOrCtrl+Shift+Space";return{enabled:Boolean(e.enabled),shortcut:n}}function b(){const e=d().__vaultBackend||{};return{backend:VAULT_BACKEND_VALUES.includes(e.backend)?e.backend:"aegiscloud"}}function v(){const e=a();if("boolean"==typeof e.confirmMode)return{enabled:e.confirmMode,source:"config"};const n=d().__confirmMode||{};return void 0===n.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(n.enabled),source:"config"}}function C(){const e=a().sandboxPolicy;return e&&"object"==typeof e?e:null}function T(){return!0===a().devMode}function h(){const e=a().accountUsername;return"string"==typeof e?e:null}function R(){const e=a();return"string"==typeof e.permissionMode?e.permissionMode:null}function I(){return!0===(d().__telemetry||{}).enabled}function L(){const e=a();if("boolean"==typeof e.memoryPersist)return{enabled:e.memoryPersist,source:"config"};const n=d().__memoryPersist||{};return void 0===n.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(n.enabled),source:"config"}}function D(){const e=d().__avatar||{};return{enabled:void 0===e.enabled||Boolean(e.enabled),showLevel:void 0===e.showLevel||Boolean(e.showLevel),motion:AVATAR_MOTION_MODES.includes(e.motion)?e.motion:"system"}}function P(){const e=d().__avatar||{};return{...D(),source:void 0===e.enabled?"default":"config"}}function O(e){const n=Number(e);if(!Number.isFinite(n))return 6e4;const t=Math.round(n);return t<15e3||t>18e5?6e4:t}function U(){const e=d().__autoDrain||{};return{enabled:!1!==e.enabled,intervalMs:O(e.intervalMs)}}function k(){const e=d().__autoDrain||{};return{...U(),source:void 0===e.enabled?"default":"config"}}function B(){const e=d().__autoMint||{};return{enabled:!1!==e.enabled,publish:!0===e.publish}}function K(){const e=d().__autoMint||{};return{...B(),source:void 0===e.enabled?"default":"config"}}return{file:o,sharedDir:i,adoption:s,sharedFile:function(){return prefs.prefsFile({dir:i})},getSharedPref:c,setSharedPref:function(e,n){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);return prefs.set({[e]:n},{dir:i}),c(e)},getDevMode:T,setDevMode:function(e){return prefs.set({devMode:Boolean(e)},{dir:i}),T()},getAccountUsername:h,setAccountUsername:function(e){return prefs.set({accountUsername:"string"==typeof e?e:null},{dir:i}),h()},get:E,set:function(e,{baseURL:n,key:t}={}){A(e);let r=n;if("local"===e&&n){const e=localTransport.remoteRefusal(n);if(e)throw e;r=localTransport.normalizeBase(n)}const o=d(),i=o[e]||{};return void 0!==r&&(i.baseURL=r),void 0!==t&&(i.key=t?l(t):null),o[e]=i,f(o),E(e)},rawKey:function(e){return _((d()[e]||{}).key)},remove:function(e){A(e);const n=d();return delete n[e],f(n),{ok:!0}},list:function(){const e=d();return Object.keys(e).filter((e=>!isReservedNamespace(e))).map((e=>E(e)))},maskKey:maskKey,aegisKey:S,aegisRawKey:function(){return _((d().__aegis||{}).key)},aegisKeySavedAt:function(){return(d().__aegis||{}).savedAt||null},setAegisKey:function(e){const n=d();return n.__aegis={...n.__aegis||{},key:e?l(e):null,savedAt:e?(new Date).toISOString():null},f(n),S()},migrateLegacyAegisKey:function(){try{const e=d();if(!e.aegis)return{migrated:!1};const n=e.aegis||{},t=e.__aegis||{},r={...e};return n.key&&!t.key&&(r.__aegis={...t,key:n.key}),delete r.aegis,f(r),{migrated:!0}}catch{return{migrated:!1}}},quickLauncherConfig:N,setQuickLauncherConfig:function({enabled:e,shortcut:n}={}){const t=d();return t.__quickLauncher={enabled:Boolean(e),shortcut:"string"==typeof n&&n.trim()?n.trim():"CmdOrCtrl+Shift+Space"},f(t),N()},vaultBackendConfig:b,setVaultBackendConfig:function(e){if(!VAULT_BACKEND_VALUES.includes(e))return b();const n=d();return n.__vaultBackend={backend:e},f(n),b()},getConfirmMode:function(){return v().enabled},setConfirmMode:function(e){prefs.set({confirmMode:Boolean(e)},{dir:i});const n=d();return void 0!==n.__confirmMode&&(delete n.__confirmMode,f(n)),v().enabled},confirmModeState:v,getFontScale:M,setFontScale:function(e){const n=d();return n.__fontScale={scale:m(e)},f(n),M()},clampFontScale:m,getAccent:y,setAccent:function(e){const n=d();return n.__accent={name:g(e)},f(n),y()},clampAccent:g,ACCENT_SKINS:p,getPermissionMode:R,setPermissionMode:function(e){if(null==e||""===e||"off"===e||"none"===e)return prefs.remove("permissionMode",{dir:i}),null;const n=String(e),t=function(){const e=[path.join(__dirname,"..","..","one","src","permissions.js"),path.join(__dirname,"..","vendor","one","src","permissions.js")];for(const n of e)try{const e=require(n);if(e&&Array.isArray(e.PERMISSION_MODES)&&e.PERMISSION_MODES.length)return[...e.PERMISSION_MODES]}catch{}return["acceptEdits","auto","bypassPermissions","manual","dontAsk","plan"]}();if(!t.includes(n))throw new Error(`"${n}" is not one of ${t.join("|")} (or 'off' to clear it)`);return prefs.set({permissionMode:n},{dir:i}),R()},getSandboxPolicy:C,setSandboxPolicy:function(e){return e&&"object"==typeof e?(prefs.set({sandboxPolicy:e},{dir:i}),C()):(prefs.set({sandboxPolicy:null},{dir:i}),null)},getTelemetryOptIn:I,setTelemetryOptIn:function(e){const n=d();return n.__telemetry={enabled:Boolean(e)},f(n),I()},getMemoryPersist:function(){return L().enabled},memoryPersistState:L,setMemoryPersist:function(e){prefs.set({memoryPersist:Boolean(e)},{dir:i});const n=d();return void 0!==n.__memoryPersist&&(delete n.__memoryPersist,f(n)),L()},getAvatar:D,avatarState:P,setAvatar:function(e={}){const n=D(),t=e&&"object"==typeof e?e:{},r={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),showLevel:void 0===t.showLevel?n.showLevel:Boolean(t.showLevel),motion:AVATAR_MOTION_MODES.includes(t.motion)?t.motion:n.motion},o=d();return o.__avatar=r,f(o),P()},getAutoDrain:U,autoDrainState:k,setAutoDrain:function(e={}){const n=U(),t=e&&"object"==typeof e?e:{},r=d();return r.__autoDrain={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),intervalMs:void 0===t.intervalMs?n.intervalMs:O(t.intervalMs)},f(r),k()},getAutoMint:B,autoMintState:K,setAutoMint:function(e={}){const n=B(),t=e&&"object"==typeof e?e:{},r=d();return r.__autoMint={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),publish:void 0===t.publish?n.publish:Boolean(t.publish)},f(r),K()},clampAutoDrainInterval:O}}module.exports={SETTINGS_FILE:SETTINGS_FILE,AEGIS_KEY_NAMESPACE:"__aegis",LEGACY_AEGIS_NAMESPACE:"aegis",QUICK_LAUNCHER_NAMESPACE:"__quickLauncher",VAULT_BACKEND_NAMESPACE:"__vaultBackend",CONFIRM_MODE_NAMESPACE:"__confirmMode",MEMORY_PERSIST_NAMESPACE:"__memoryPersist",AVATAR_NAMESPACE:"__avatar",TELEMETRY_NAMESPACE:"__telemetry",AUTO_DRAIN_NAMESPACE:"__autoDrain",AUTO_MINT_NAMESPACE:"__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS:6e4,AUTO_DRAIN_INTERVAL_MIN_MS:15e3,AUTO_DRAIN_INTERVAL_MAX_MS:18e5,AVATAR_MOTION_MODES:AVATAR_MOTION_MODES,DEFAULT_QUICK_LAUNCHER_SHORTCUT:"CmdOrCtrl+Shift+Space",DEFAULT_VAULT_BACKEND:"aegiscloud",VAULT_BACKEND_VALUES:VAULT_BACKEND_VALUES,RESERVED_NAMESPACES:RESERVED_NAMESPACES,isReservedNamespace:isReservedNamespace,maskKey:maskKey,createSettingsStore:createSettingsStore};
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),prefs=(()=>{try{return require("../../client/prefs.js")}catch{return require("../vendor/prefs.js")}})(),credentials=(()=>{try{return require("../../client/credentials.js")}catch{return require("../vendor/credentials.js")}})(),localTransport=require("./local/local.js"),LOCAL_NAMESPACE="local",SETTINGS_FILE="settings.json",AEGIS_KEY_NAMESPACE="__aegis",LEGACY_AEGIS_NAMESPACE="aegis",QUICK_LAUNCHER_NAMESPACE="__quickLauncher",DEFAULT_QUICK_LAUNCHER_SHORTCUT="CmdOrCtrl+Shift+Space",VAULT_BACKEND_NAMESPACE="__vaultBackend",DEFAULT_VAULT_BACKEND="aegiscloud",VAULT_BACKEND_VALUES=Object.freeze(["aegiscloud","drive","off"]),CONFIRM_MODE_NAMESPACE="__confirmMode",FONT_SCALE_NAMESPACE="__fontScale",ACCENT_NAMESPACE="__accent",MEMORY_PERSIST_NAMESPACE="__memoryPersist",AVATAR_NAMESPACE="__avatar",TELEMETRY_NAMESPACE="__telemetry",AUTO_DRAIN_NAMESPACE="__autoDrain",AUTO_MINT_NAMESPACE="__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS=6e4,AUTO_DRAIN_INTERVAL_MIN_MS=15e3,AUTO_DRAIN_INTERVAL_MAX_MS=18e5,RESERVED_NAMESPACES=Object.freeze(["__aegis","aegis","__quickLauncher","__vaultBackend","__confirmMode","__memoryPersist","__avatar","__telemetry","__autoDrain","__autoMint"]),AVATAR_MOTION_MODES=Object.freeze(["system","full","minimal"]);function isReservedNamespace(e){return RESERVED_NAMESPACES.includes(e)}function maskKey(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}const IS_WIN32="win32"===process.platform;function restrictFile(e){if(IS_WIN32){const n=process.env.USERNAME||process.env.USER||process.env.USERDOMAIN;if(!n)return void console.error(`[settings] cannot restrict ${e}: no current user to grant (USERNAME unset)`);try{execFileSync("icacls",[e,"/inheritance:r","/grant:r",`${n}:(F)`],{stdio:"ignore"})}catch(n){console.error(`[settings] failed to restrict ACL on ${e}: ${n.message}`)}return}try{fs.chmodSync(e,384)}catch(n){console.error(`[settings] failed to chmod ${e} to 0600: ${n.message}`)}}function createSettingsStore({dir:e,safeStorage:n,prefsDir:t,env:r}={}){if(!e)throw new Error("createSettingsStore requires a storage dir");const o=path.join(e,SETTINGS_FILE),i=(()=>{const e=null==t?"":String(t).trim();return e?path.resolve(e):credentials.aegisHome(r)})(),s=(()=>{try{return prefs.adopt({dir:i,legacyDir:e})}catch(e){return(process.env.AEGISCODE_DEBUG||process.env.AEGIS_HIST_DEBUG)&&process.stderr.write(`aegis-desktop: shared-preference adoption failed: ${e.message}\n`),{adopted:!1,keys:[],reason:`adoption failed: ${e.message}`}}})();function a(){try{return prefs.load({dir:i})}catch{return{}}}function c(e){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);const n=a()[e];return void 0===n?null:n}const u=()=>Boolean(n&&"function"==typeof n.isEncryptionAvailable&&n.isEncryptionAvailable());function _(e){return null==e?null:u()?n.encryptString(String(e)).toString("base64"):Buffer.from(String(e),"utf8").toString("base64")}function l(e){if(!e)return null;try{const t=Buffer.from(String(e),"base64");return u()?n.decryptString(t):t.toString("utf8")}catch{return null}}function d(){try{return JSON.parse(fs.readFileSync(o,"utf8"))||{}}catch{return{}}}function f(e){fs.mkdirSync(path.dirname(o),{recursive:!0});const n=`${o}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(e,null,2),{mode:384}),fs.renameSync(n,o),restrictFile(o)}function A(e){if(isReservedNamespace(e))throw new Error(`reserved namespace "${e}" is not a provider config — use setAegisKey()/aegisRawKey() for the AEGIS key`)}function E(e){const n=d()[e]||{},t=l(n.key);return{provider:e,baseURL:n.baseURL||"",configured:Boolean(t),keyMask:maskKey(t)}}function S(){const e=l((d().__aegis||{}).key);return{configured:Boolean(e),keyMask:maskKey(e)}}function m(e){return Number.isFinite(e)?Math.min(1.3,Math.max(.85,Math.round(100*e)/100)):1}function M(){return m((d().__fontScale||{}).scale)}const p=["default","cobalt","amber"];function g(e){const n="string"==typeof e?e.trim().toLowerCase():"";return p.includes(n)?n:"default"}function y(){return g((d().__accent||{}).name)}function N(){const e=d().__quickLauncher||{},n="string"==typeof e.shortcut&&e.shortcut.trim()?e.shortcut.trim():"CmdOrCtrl+Shift+Space";return{enabled:Boolean(e.enabled),shortcut:n}}function b(){const e=d().__vaultBackend||{};return{backend:VAULT_BACKEND_VALUES.includes(e.backend)?e.backend:"aegiscloud"}}function v(){const e=a();if("boolean"==typeof e.confirmMode)return{enabled:e.confirmMode,source:"config"};const n=d().__confirmMode||{};return void 0===n.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(n.enabled),source:"config"}}function C(){const e=a().sandboxPolicy;return e&&"object"==typeof e?e:null}function T(){return!0===a().devMode}function h(){const e=a().accountUsername;return"string"==typeof e?e:null}function R(){const e=a();return"string"==typeof e.permissionMode?e.permissionMode:null}function I(){return!0===(d().__telemetry||{}).enabled}function L(){const e=a();if("boolean"==typeof e.memoryPersist)return{enabled:e.memoryPersist,source:"config"};const n=d().__memoryPersist||{};return void 0===n.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(n.enabled),source:"config"}}function D(){const e=d().__avatar||{};return{enabled:void 0===e.enabled||Boolean(e.enabled),showLevel:void 0===e.showLevel||Boolean(e.showLevel),motion:AVATAR_MOTION_MODES.includes(e.motion)?e.motion:"system"}}function P(){const e=d().__avatar||{};return{...D(),source:void 0===e.enabled?"default":"config"}}function O(e){const n=Number(e);if(!Number.isFinite(n))return 6e4;const t=Math.round(n);return t<15e3||t>18e5?6e4:t}function U(){const e=d().__autoDrain||{};return{enabled:!1!==e.enabled,intervalMs:O(e.intervalMs)}}function k(){const e=d().__autoDrain||{};return{...U(),source:void 0===e.enabled?"default":"config"}}function B(){const e=d().__autoMint||{};return{enabled:!1!==e.enabled,publish:!0===e.publish}}function K(){const e=d().__autoMint||{};return{...B(),source:void 0===e.enabled?"default":"config"}}return{file:o,sharedDir:i,adoption:s,sharedFile:function(){return prefs.prefsFile({dir:i})},getSharedPref:c,setSharedPref:function(e,n){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);return prefs.set({[e]:n},{dir:i}),c(e)},getDevMode:T,setDevMode:function(e){return prefs.set({devMode:Boolean(e)},{dir:i}),T()},getAccountUsername:h,setAccountUsername:function(e){return prefs.set({accountUsername:"string"==typeof e?e:null},{dir:i}),h()},get:E,set:function(e,{baseURL:n,key:t}={}){A(e);let r=n;if("local"===e&&n){const e=localTransport.remoteRefusal(n);if(e)throw e;r=localTransport.normalizeBase(n)}const o=d(),i=o[e]||{};return void 0!==r&&(i.baseURL=r),void 0!==t&&(i.key=t?_(t):null),o[e]=i,f(o),E(e)},rawKey:function(e){return l((d()[e]||{}).key)},remove:function(e){A(e);const n=d();return delete n[e],f(n),{ok:!0}},list:function(){const e=d();return Object.keys(e).filter(e=>!isReservedNamespace(e)).map(e=>E(e))},maskKey:maskKey,aegisKey:S,aegisRawKey:function(){return l((d().__aegis||{}).key)},aegisKeySavedAt:function(){return(d().__aegis||{}).savedAt||null},setAegisKey:function(e){const n=d();return n.__aegis={...n.__aegis||{},key:e?_(e):null,savedAt:e?(new Date).toISOString():null},f(n),S()},migrateLegacyAegisKey:function(){try{const e=d();if(!e.aegis)return{migrated:!1};const n=e.aegis||{},t=e.__aegis||{},r={...e};return n.key&&!t.key&&(r.__aegis={...t,key:n.key}),delete r.aegis,f(r),{migrated:!0}}catch{return{migrated:!1}}},quickLauncherConfig:N,setQuickLauncherConfig:function({enabled:e,shortcut:n}={}){const t=d();return t.__quickLauncher={enabled:Boolean(e),shortcut:"string"==typeof n&&n.trim()?n.trim():"CmdOrCtrl+Shift+Space"},f(t),N()},vaultBackendConfig:b,setVaultBackendConfig:function(e){if(!VAULT_BACKEND_VALUES.includes(e))return b();const n=d();return n.__vaultBackend={backend:e},f(n),b()},getConfirmMode:function(){return v().enabled},setConfirmMode:function(e){prefs.set({confirmMode:Boolean(e)},{dir:i});const n=d();return void 0!==n.__confirmMode&&(delete n.__confirmMode,f(n)),v().enabled},confirmModeState:v,getFontScale:M,setFontScale:function(e){const n=d();return n.__fontScale={scale:m(e)},f(n),M()},clampFontScale:m,getAccent:y,setAccent:function(e){const n=d();return n.__accent={name:g(e)},f(n),y()},clampAccent:g,ACCENT_SKINS:p,getPermissionMode:R,setPermissionMode:function(e){if(null==e||""===e||"off"===e||"none"===e)return prefs.remove("permissionMode",{dir:i}),null;const n=String(e),t=function(){const e=[path.join(__dirname,"..","..","one","src","permissions.js"),path.join(__dirname,"..","vendor","one","src","permissions.js")];for(const n of e)try{const e=require(n);if(e&&Array.isArray(e.PERMISSION_MODES)&&e.PERMISSION_MODES.length)return[...e.PERMISSION_MODES]}catch{}return["acceptEdits","auto","bypassPermissions","manual","dontAsk","plan"]}();if(!t.includes(n))throw new Error(`"${n}" is not one of ${t.join("|")} (or 'off' to clear it)`);return prefs.set({permissionMode:n},{dir:i}),R()},getSandboxPolicy:C,setSandboxPolicy:function(e){return e&&"object"==typeof e?(prefs.set({sandboxPolicy:e},{dir:i}),C()):(prefs.set({sandboxPolicy:null},{dir:i}),null)},getTelemetryOptIn:I,setTelemetryOptIn:function(e){const n=d();return n.__telemetry={enabled:Boolean(e)},f(n),I()},getMemoryPersist:function(){return L().enabled},memoryPersistState:L,setMemoryPersist:function(e){prefs.set({memoryPersist:Boolean(e)},{dir:i});const n=d();return void 0!==n.__memoryPersist&&(delete n.__memoryPersist,f(n)),L()},getAvatar:D,avatarState:P,setAvatar:function(e={}){const n=D(),t=e&&"object"==typeof e?e:{},r={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),showLevel:void 0===t.showLevel?n.showLevel:Boolean(t.showLevel),motion:AVATAR_MOTION_MODES.includes(t.motion)?t.motion:n.motion},o=d();return o.__avatar=r,f(o),P()},getAutoDrain:U,autoDrainState:k,setAutoDrain:function(e={}){const n=U(),t=e&&"object"==typeof e?e:{},r=d();return r.__autoDrain={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),intervalMs:void 0===t.intervalMs?n.intervalMs:O(t.intervalMs)},f(r),k()},getAutoMint:B,autoMintState:K,setAutoMint:function(e={}){const n=B(),t=e&&"object"==typeof e?e:{},r=d();return r.__autoMint={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),publish:void 0===t.publish?n.publish:Boolean(t.publish)},f(r),K()},clampAutoDrainInterval:O}}module.exports={SETTINGS_FILE:SETTINGS_FILE,AEGIS_KEY_NAMESPACE:"__aegis",LEGACY_AEGIS_NAMESPACE:"aegis",QUICK_LAUNCHER_NAMESPACE:"__quickLauncher",VAULT_BACKEND_NAMESPACE:"__vaultBackend",CONFIRM_MODE_NAMESPACE:"__confirmMode",MEMORY_PERSIST_NAMESPACE:"__memoryPersist",AVATAR_NAMESPACE:"__avatar",TELEMETRY_NAMESPACE:"__telemetry",AUTO_DRAIN_NAMESPACE:"__autoDrain",AUTO_MINT_NAMESPACE:"__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS:6e4,AUTO_DRAIN_INTERVAL_MIN_MS:15e3,AUTO_DRAIN_INTERVAL_MAX_MS:18e5,AVATAR_MOTION_MODES:AVATAR_MOTION_MODES,DEFAULT_QUICK_LAUNCHER_SHORTCUT:"CmdOrCtrl+Shift+Space",DEFAULT_VAULT_BACKEND:"aegiscloud",VAULT_BACKEND_VALUES:VAULT_BACKEND_VALUES,RESERVED_NAMESPACES:RESERVED_NAMESPACES,isReservedNamespace:isReservedNamespace,maskKey:maskKey,createSettingsStore:createSettingsStore};
|
|
@@ -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=`${IPC_PREFIX}chatDelta`,PTY_EVENT_CHANNEL=`${IPC_PREFIX}ptyEvent`,MENU_NEW_CHAT_CHANNEL=`${IPC_PREFIX}menuNewChat`,MENU_SEARCH_CHANNEL=`${IPC_PREFIX}menuSearch`,MENU_SEARCH_MEMORY_CHANNEL=`${IPC_PREFIX}menuSearchMemory`,MENU_CREDITS_CHANNEL=`${IPC_PREFIX}menuCredits`,MENU_PALETTE_CHANNEL=`${IPC_PREFIX}menuPalette`,MENU_TOGGLE_SIDEBAR_CHANNEL=`${IPC_PREFIX}menuToggleSidebar`,MENU_FIND_CHANNEL=`${IPC_PREFIX}menuFind`,MENU_GO_BACK_CHANNEL=`${IPC_PREFIX}menuGoBack`,MENU_GO_FORWARD_CHANNEL=`${IPC_PREFIX}menuGoForward`,navState={back:!1,forward:!1},MENU_EXPORT_MARKDOWN_CHANNEL=`${IPC_PREFIX}menuExportMarkdown`,MENU_EXPORT_JSON_CHANNEL=`${IPC_PREFIX}menuExportJson`,MENU_FINGERPRINT_CHANNEL=`${IPC_PREFIX}menuFingerprint`,MENU_GOOGLE_DRIVE_CHANNEL=`${IPC_PREFIX}menuGoogleDrive`,DEEP_LINK_CHANNEL=`${IPC_PREFIX}deepLink`,QUICK_LAUNCHER_PUSH_CHANNEL=`${IPC_PREFIX}quickLauncherPush`,QUEUE_PROGRESS_CHANNEL=`${QUEUE_PREFIX}progress`,QUEUE_CHANGED_CHANNEL=`${QUEUE_PREFIX}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,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||{}),
|
|
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(`${IPC_PREFIX}${t}`,((e,t)=>r(t))):e.handle(`${IPC_PREFIX}${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(CHAT_DELTA_CHANNEL,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(`${IPC_PREFIX}ptyHello`,((e,t)=>s.hello(t&&t.id||0))),e.handle(`${IPC_PREFIX}ptyExec`,((e,t)=>{const r=t||{},n=e&&e.sender;return s.exec(r.id,r.params,(e=>{n&&!n.isDestroyed()&&n.send(PTY_EVENT_CHANNEL,e)}))})),e.handle(`${IPC_PREFIX}ptyWrite`,((e,t)=>{const r=t||{};return s.write(r.id,r.data)})),e.handle(`${IPC_PREFIX}ptyResize`,((e,t)=>{const r=t||{};return s.resize(r.id,r.cols,r.rows)})),e.handle(`${IPC_PREFIX}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(`${IPC_PREFIX}${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(`${IPC_PREFIX}${r}`,((e,t)=>n(t)));return t}function registerTelemetryIpc(e,t){for(const[r,n]of Object.entries(t))e.handle(`${IPC_PREFIX}${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(`${IPC_PREFIX}${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_PREFIX}${r}`,((e,t)=>n(t))):e.handle(`${QUICK_PREFIX}${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<=PREVIEW_READ_MAX_BYTES)return{text:fs.readFileSync(o,"utf8"),truncated:!1};const i=fs.openSync(o,"r");try{const e=Buffer.alloc(PREVIEW_READ_MAX_BYTES),t=fs.readSync(i,e,0,PREVIEW_READ_MAX_BYTES,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):HEARTBEAT_RETRY_BASE_MS,o=Number(t.maxMs)>0?Number(t.maxMs):HEARTBEAT_RETRY_MAX_MS;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_PREFIX}${t}`,((e,t)=>r(t))):e.handle(`${MODEL_PREFIX}${t}`,((e,t)=>(d(),r(t)))):e.handle(`${MODEL_PREFIX}${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(CHAT_DELTA_CHANNEL,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_PREFIX}readTextFile`,((e,t)=>{e.returnValue=readTextFileForPreview(t)})),e.handle(`${IPC_PREFIX}attachments:ingest`,(async(e,t)=>ingestAttachment(t)));for(const[t,r]of Object.entries(l))"status"!==t?e.handle(`${SYNC_PREFIX}${t}`,((e,t)=>r(t))):e.handle(`${SYNC_PREFIX}${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,QUEUE_MAX_WORKERS),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>QUEUE_MAX_TASK_CHARS)return{error:`task text is too long (${r.length} > ${QUEUE_MAX_TASK_CHARS} 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,QUEUE_MAX_WORKERS),maxRounds:clampInt(t.maxRounds,1,QUEUE_MAX_ROUNDS),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_CHANNEL,{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_CHANNEL,e))}});for(const[t,r]of Object.entries(d))e.handle(`${QUEUE_PREFIX}${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_PREFIX}${r}`,((e,t)=>n(t)));return t}const UPDATE_STATUS_CHANNEL=`${IPC_PREFIX}updateStatus`,ACCOUNT_STATUS_CHANNEL=`${IPC_PREFIX}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 h=0,g=0,y=null,E=null,S=null,_=null;function k(){y&&s(y),y=null}let A=null;async function b({announce:e=!1}={}){if(!f)return m({status:"disabled",error:"update checker unavailable"});if(E)return E;E=(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(h=0,g=0,k(),await async function(){if(null!==A)return A;if(!f||"function"!=typeof f.serverUpdateVerdict)return null;try{const e=await f.serverUpdateVerdict({current:d});return e&&e.ok&&(A=Boolean(e.decomposed)),A}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(_)return _;const e=f&&f.detectInstallMethod;if("function"!=typeof e)return _="npm",_;try{_=e({env:process.env,argv:process.argv,pkg:u,entry:__dirname,fileExists:e=>fs.existsSync(path.resolve(__dirname,"..",e))})}catch{_="npm"}return _}(),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})}h+=1;const c=i.error||describeRegistryFailure(i.reason,i.status,u);return l=i.reason,E=i.status,("function"==typeof f.isTransientReason?f.isTransientReason(l,E):"unknown"===l)?(function(){k();const e=UPDATE_RETRY_BACKOFF_MS[Math.min(Math.max(h-1,0),UPDATE_RETRY_BACKOFF_MS.length-1)];g=r()+e,y=o((()=>{y=null,b().catch((()=>{}))}),e),y&&y.unref&&y.unref(),m({retryInMs:e})}(),m(e?{status:"error",phase:"check",error:c,reason:i.reason,transient:!0,attempts:h}:{status:"available"===s?"available":"unavailable",version:a,error:c,reason:i.reason,transient:!0,attempts:h})):(k(),g=0,m({status:"error",phase:"check",error:c,reason:i.reason,transient:!1,attempts:h,retryInMs:0}));var l,E})();try{return await E}finally{E=null}}return{status:()=>p,check:b,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:()=>{b().catch((()=>{})),S=setInterval((()=>b().catch((()=>{}))),UPDATE_CHECK_INTERVAL_MS),S.unref&&S.unref()},stop:()=>{k(),S&&clearInterval(S),S=null},retryState:()=>({attempts:h,retryAt:g,inFlight:!!E,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(`${IPC_PREFIX}${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(DEEP_LINK_CHANNEL,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: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(),
|
|
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,MENU_NEW_CHAT_CHANNEL)},c={label:"Search",accelerator:"CmdOrCtrl+K",click:()=>sendToAppWindow(r,MENU_SEARCH_CHANNEL)},l={label:"Command palette…",accelerator:"CmdOrCtrl+P",click:()=>sendToAppWindow(r,MENU_PALETTE_CHANNEL)},u={label:"Toggle sidebar",accelerator:"CmdOrCtrl+B",click:()=>sendToAppWindow(r,MENU_TOGGLE_SIDEBAR_CHANNEL)},d={label:"Find in conversation",accelerator:"CmdOrCtrl+F",click:()=>sendToAppWindow(r,MENU_FIND_CHANNEL)},p={label:"Go Back",accelerator:s?"Cmd+[":"Alt+Left",enabled:navState.back,click:()=>sendToAppWindow(r,MENU_GO_BACK_CHANNEL)},m={label:"Go Forward",accelerator:s?"Cmd+]":"Alt+Right",enabled:navState.forward,click:()=>sendToAppWindow(r,MENU_GO_FORWARD_CHANNEL)},f={label:"Search memory",accelerator:"CmdOrCtrl+Shift+K",visible:!1,click:()=>sendToAppWindow(r,MENU_SEARCH_MEMORY_CHANNEL)},h={label:"Credits & Licence…",click:()=>sendToAppWindow(r,MENU_CREDITS_CHANNEL)},g={label:"Source Code",click:()=>{try{require("electron").shell.openExternal(creditsLib.SOURCE_URL)}catch{}}},y={label:"Save as…",accelerator:"CmdOrCtrl+S",click:()=>sendToAppWindow(r,MENU_EXPORT_MARKDOWN_CHANNEL)},E={label:"Export Session…",click:()=>sendToAppWindow(r,MENU_EXPORT_JSON_CHANNEL)},S={label:"Authorship Panel…",click:()=>sendToAppWindow(r,MENU_FINGERPRINT_CHANNEL)},_={label:"Google Drive Backup…",enabled:Boolean(o),click:()=>sendToAppWindow(r,MENU_GOOGLE_DRIVE_CHANNEL)},k=[...s?[{label:e.getName(),submenu:[{role:"about"},a,{type:"separator"},h,g,{type:"separator"},{role:"services"},{type:"separator"},{role:"hide"},{role:"hideOthers"},{role:"unhide"},{type:"separator"},{role:"quit"}]}]:[],{label:"File",submenu:[i,{type:"separator"},y,E,{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"},S,_,{type:"separator"},{role:"reload",accelerator:"CmdOrCtrl+R"},{role:"forceReload"},{type:"separator"},{role:"toggleDevTools",accelerator:"CmdOrCtrl+Shift+I"}]},{label:"Help",submenu:[h,g,{type:"separator"},...s?[]:[{role:"about"}]]}];return t.buildFromTemplate(k)}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 h=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):h=r}));const g=createClient(credentials.clientOptions()),y=resolveUserDataDir(s),{engine:E,sessionsDir:S,settingsDir:_,settings:k,avatar:A}=createEngine(g,{app:s,safeStorage:c,dir:y}),b=createAccountKey({aegis:g,credentials:credentials,persistKey:e=>k.setAegisKey(e),provision:(e,t)=>autoProvision.autoProvisionApiKey(e,t,{app:"desktop"}),describeFailure:autoProvision.provisionFailureText,onChange:e=>H(e)});let v=null;const P=createGoogleConnect({aegis:g,credentials:credentials,persistKey:e=>k.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(S,e),getAuthor:()=>{try{v||(v=createFingerprintService({dir:y,getVaultBackend:()=>k.vaultBackendConfig().backend}));const e=v.status();return e&&e.ok?e:null}catch{return null}},onAccountChange:()=>H(b.status()),machineFingerprint:()=>sharedFingerprint.machineFingerprint()}),I=Boolean(g.apiKey),C=autoProvision.autoProvisionApiKey(g,credentials,{app:"desktop"}).then((e=>{if(b.recordStartup(e),!e.key&&!g.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(k,envFile,{onWarn:t}),E&&E.settings&&E.settings!==k&&e(E.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not wire the shared env-file key mirror: ${e&&e.message}`)}let w=null;const R=(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),w&&"function"==typeof w.note){const e=t&&(t.model||t.modelId)||void 0;w.note({sessionId:t&&t.sessionId||null,model:e})}};registerIpc(i,g,y,(e=>{const t=k.setAegisKey(e);return e?credentials.saveApiKey(e):credentials.clearApiKey(),t}),(e=>l.openExternal(e)),R,(()=>providerRouteConfigured(E)),(()=>k.vaultBackendConfig().backend),A);const M=registerModelIpc(i,E,S,g,R,void 0,_,k);registerConfirmModeIpc(i,withAutoRoundsSwitch(createConfirmModeDispatch(k),M.modelDispatch)),registerConfirmModeIpc(i,createPermissionModeDispatch(k)),registerConfirmModeIpc(i,createFontScaleDispatch(k)),registerConfirmModeIpc(i,createAccentDispatch(k)),registerConfirmModeIpc(i,createDevModeDispatch(k)),registerConfirmModeIpc(i,createModelAutoSyncDispatch(k,E)),registerConfirmModeIpc(i,createVaultBackendDispatch(k)),registerConfirmModeIpc(i,createPermRulesDispatch(require("./lib/local/perm-store.js"))),registerConfirmModeIpc(i,createSandboxPolicyDispatch(k,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:_,enabled:telemetryEnabled(process.env,k),appVersion:(()=>{try{return"function"==typeof s.getVersion?s.getVersion():""}catch{return""}})()}))),registerCovenantIpc(i,createCovenantDispatch(covenantModule));const N=registerQueueIpc(i,{engine:createQueueEngine(g,k),aegis:g}),T=createAutoDrain({proceed:()=>N.proceed(),settings:k,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 D=null;w=createAutoMint({mint:e=>(D||(D=createFingerprintService({dir:y,getVaultBackend:()=>k.vaultBackendConfig().backend})),D.mint(e||{})),settings:k}),registerAutoIpc(i,createAutoDispatch({autoDrain:T,autoMint:w})),T.start(),w.start();let L=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 x(){const e=F();e.isVisible()?e.hide():function(){const e=F(),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!==U?e:a.getAllWindows().find((e=>e!==U))||null};const q=createQuickLauncherDispatch(k,{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,x)){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(QUICK_LAUNCHER_PUSH_CHANNEL,e||{}),n.isMinimized()&&n.restore(),n.isVisible()||n.show(),n.focus(),{ok:!0}):{ok:!1,reason:"no main window is open"}}});registerQuickLauncherIpc(i,q);let O=null;s.on("will-quit",(()=>{O&&"function"==typeof O.stop&&O.stop(),closeMemoryIndex(),f.unregisterAll(),X&&"function"==typeof X.stop&&X.stop(),W&&clearInterval(W),W=null}));let $=!1;s.on("before-quit",(e=>{!$&&E&&"function"==typeof E.unloadLocalModels&&(e.preventDefault(),Promise.resolve().then((()=>E.unloadLocalModels())).catch((()=>{})).finally((()=>{$=!0,s.quit()})))}));const j=new Set;function H(e){for(const t of j)t.isDestroyed()||t.webContents.send(ACCOUNT_STATUS_CHANNEL,e);B()}function B(){u.setApplicationMenu(buildAppMenu({app:s,Menu:u,BrowserWindow:a,updateManager:X,loggedIn:Boolean(g.apiKey)}))}const X=createUpdateManager({isPackaged:s.isPackaged,onStatus:function(e){for(const t of j)t.isDestroyed()||t.webContents.send(UPDATE_STATUS_CHANNEL,e)}});let W=null;registerUpdateIpc(i,X),i.handle(`${IPC_PREFIX}accountStatus`,(()=>b.status())),i.handle(`${IPC_PREFIX}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,B()),{ok:!0}})),i.handle(`${IPC_PREFIX}registerAccount`,(()=>b.registerAccount())),i.handle(`${IPC_PREFIX}driveSignIn`,(()=>P.signInWithGoogle())),i.handle(`${IPC_PREFIX}driveConnect`,(()=>P.connectDrive())),i.handle(`${IPC_PREFIX}driveStatus`,(()=>P.status())),i.handle(`${IPC_PREFIX}driveSyncMemory`,(()=>P.syncMemoryNow())),i.handle(`${IPC_PREFIX}driveBackupConversation`,((e,t)=>P.backupConversation({sessionId:t&&t.sessionId}))),i.handle(`${IPC_PREFIX}speechStatus`,(()=>{try{return speechHost.status({settings:readSpeechSettings(k)})}catch(e){return{enabled:!1,engine:"none",reason:e&&e.message||"dictation status failed"}}})),i.handle(`${IPC_PREFIX}speechSet`,((e,t)=>{try{const e=t&&"object"==typeof t?t:{},r={...readSpeechSettings(k)};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 k.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(`${IPC_PREFIX}speechTranscribe`,((e,t)=>{const r=t&&"object"==typeof t?t:{};return speechHost.transcribe(r.audio,{settings:readSpeechSettings(k),ext:r.ext}).catch((e=>({ok:!1,reason:e&&e.message||"transcription failed"})))})),i.handle(`${IPC_PREFIX}skillsList`,(()=>skillsHost.list())),i.handle(`${IPC_PREFIX}skillsRead`,((e,t)=>skillsHost.read(t||{}))),i.handle(`${IPC_PREFIX}skillsCreate`,((e,t)=>skillsHost.create(t||{}))),i.handle(`${IPC_PREFIX}skillsRemove`,((e,t)=>skillsHost.remove(t||{}))),i.handle(`${IPC_PREFIX}skillsImport`,((e,t)=>skillsHost.importFromUrl(t||{}))),registerExportIpc(i,sessionStore,S,(e=>m.showSaveDialog(a.getFocusedWindow(),e)),((e,t)=>fs.promises.writeFile(e,t,"utf8"))),i.handle(`${IPC_PREFIX}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)}}})),B();const K=pathToFileURL(path.join(__dirname,"renderer","index.html")).href;function Q(){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!==K&&(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")),j.add(n),L=n,n.on("closed",(()=>{j.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 C,t=startupKeyOverride({mintedKey:I?"":e.key,hostKey:credentials.normalizeApiKey(k.aegisRawKey())});if(t)credentials.saveApiKey(t),g.setApiKey(t);else{const e=credentials.preferNewest(k.aegisRawKey(),k.aegisKeySavedAt());e.key&&(g.setApiKey(e.key),"shared"===e.source&&k.setAegisKey(e.key))}}try{O&&"function"==typeof O.stop&&O.stop(),O=sharedPresence.createPresence({apiKey:g.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)}}),O.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(k,envFile,{onWarn:t});r.mirrored.length&&console.warn(`aegis: shared ${r.mirrored.join(", ")} key(s) with the other hosts (${envFile.envFileFor()})`),E&&E.settings&&E.settings!==k&&e(E.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not backfill the shared env-file key mirror: ${e&&e.message}`)}q.setConfig(k.quickLauncherConfig());const r=Q();X.start(),function(){if(W)return;const e=()=>{Promise.resolve(E.modelAutoSyncRun()).then((e=>{if(e&&e.ran){if(e.added>0&&"function"==typeof E.refreshByokModels)try{E.refreshByokModels()}catch{}for(const t of j)t.isDestroyed()||t.webContents.send(`${IPC_PREFIX}modelSyncReport`,e)}})).catch((()=>{}))},t=setTimeout(e,6e5);"function"==typeof t.unref&&t.unref(),W=setInterval(e,216e5),"function"==typeof W.unref&&W.unref()}(),h&&sendDeepLinkToWindow(r,h)})),s.on("window-all-closed",(()=>{"darwin"!==process.platform&&s.quit()})),s.on("activate",(()=>{const e=a.getAllWindows();if(0===e.length)return void Q();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)r.isMinimized()&&r.restore(),r.isVisible()||r.show(),r.focus(),n&&sendDeepLinkToWindow(r,n);else{const e=Q();n&&sendDeepLinkToWindow(e,n)}}))}electron&&electron.app&&bootstrap(),module.exports={memoryIndex:memoryIndex,closeMemoryIndex:closeMemoryIndex,createIpcDispatch:createIpcDispatch,registerIpc:registerIpc,providerRouteConfigured:providerRouteConfigured,IPC_PREFIX:IPC_PREFIX,MODEL_PREFIX:MODEL_PREFIX,SYNC_PREFIX:SYNC_PREFIX,watchTopupCredit:watchTopupCredit,bankAmount:bankAmount,TOPUP_POLL_MS:TOPUP_POLL_MS,TOPUP_POLL_TRIES:TOPUP_POLL_TRIES,CHAT_DELTA_CHANNEL:CHAT_DELTA_CHANNEL,PTY_EVENT_CHANNEL:PTY_EVENT_CHANNEL,createPtyIpc:createPtyIpc,MENU_NEW_CHAT_CHANNEL:MENU_NEW_CHAT_CHANNEL,MENU_SEARCH_CHANNEL:MENU_SEARCH_CHANNEL,MENU_SEARCH_MEMORY_CHANNEL:MENU_SEARCH_MEMORY_CHANNEL,MENU_CREDITS_CHANNEL:MENU_CREDITS_CHANNEL,MENU_PALETTE_CHANNEL:MENU_PALETTE_CHANNEL,MENU_TOGGLE_SIDEBAR_CHANNEL:MENU_TOGGLE_SIDEBAR_CHANNEL,MENU_EXPORT_MARKDOWN_CHANNEL:MENU_EXPORT_MARKDOWN_CHANNEL,MENU_EXPORT_JSON_CHANNEL:MENU_EXPORT_JSON_CHANNEL,MENU_FINGERPRINT_CHANNEL:MENU_FINGERPRINT_CHANNEL,MENU_GOOGLE_DRIVE_CHANNEL:MENU_GOOGLE_DRIVE_CHANNEL,DEEP_LINK_CHANNEL:DEEP_LINK_CHANNEL,UPDATE_STATUS_CHANNEL:UPDATE_STATUS_CHANNEL,UPDATE_CHECK_INTERVAL_MS:UPDATE_CHECK_INTERVAL_MS,taggedChunk:taggedChunk,maskKey:maskKey,createModelDispatch:createModelDispatch,DESKTOP_CLASSES:DESKTOP_CLASSES,readTextFileForPreview:readTextFileForPreview,PREVIEW_READ_MAX_BYTES:PREVIEW_READ_MAX_BYTES,ingestAttachment:ingestAttachment,nativeImageResizer:nativeImageResizer,createSyncDispatch:createSyncDispatch,registerModelIpc:registerModelIpc,createHeartbeatRetry:createHeartbeatRetry,describeSyncError:describeSyncError,HEARTBEAT_RETRY_BASE_MS:HEARTBEAT_RETRY_BASE_MS,HEARTBEAT_RETRY_MAX_MS:HEARTBEAT_RETRY_MAX_MS,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_PREFIX,QUICK_LAUNCHER_PUSH_CHANNEL:QUICK_LAUNCHER_PUSH_CHANNEL,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_PREFIX,QUEUE_PROGRESS_CHANNEL:QUEUE_PROGRESS_CHANNEL,QUEUE_CHANGED_CHANNEL:QUEUE_CHANGED_CHANNEL,QUEUE_MAX_TASK_CHARS:QUEUE_MAX_TASK_CHARS,QUEUE_MAX_ROUNDS:QUEUE_MAX_ROUNDS,createQueueEngine:createQueueEngine,queueEngineWithDeniedApprovals:queueEngineWithDeniedApprovals,createQueueDispatch:createQueueDispatch,registerQueueIpc:registerQueueIpc,AUTO_PREFIX:AUTO_PREFIX,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:()=>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};
|