aegisone 1.0.64 → 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
package/vendor/cli/src/theme.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const{caps:caps,detect:detect,onCapsChange:onCapsChange,rgb:rgb,bg:bg}=require("./caps.js"),{STAR:STAR,stencilGlyph:stencilGlyph}=require("./art.js"),RESET="[0m",BOLD="[1m",DIM="[2m",ITALIC="[3m",UNDER="[4m",BOLD_OFF="[22m",ITALIC_OFF="[23m",UNDER_OFF="[24m",RESET_FG="[39m",RESET_BG="[49m",RGB=(e,t,n)=>rgb(e,t,n),BG=(e,t,n)=>bg(e,t,n),C={},LIGHT={},CB_DARK={},CB_LIGHT={},ANSI_DARK={},ANSI_LIGHT={};function buildDark(){return{gold:RGB(255,193,7),coral:RGB(215,119,87),lavender:RGB(177,185,249),blue:RGB(120,160,250),green:RGB(78,186,101),red:RGB(220,90,90),gray:RGB(153,153,153),dim:RGB(80,80,80),white:RGB(255,255,255),black:RGB(30,30,30),darkBg:RGB(20,20,20)}}function buildLight(){return{gold:RGB(180,130,0),coral:RGB(190,100,70),lavender:RGB(120,130,220),blue:RGB(70,110,220),green:RGB(60,150,80),red:RGB(200,60,60),gray:RGB(110,110,110),dim:RGB(170,170,170),white:RGB(40,40,40),black:RGB(245,245,245),darkBg:RGB(255,255,255)}}function buildCbDark(){return{...buildDark(),green:RGB(86,182,194),red:RGB(255,146,43),gold:RGB(255,203,71)}}function buildCbLight(){return{...buildLight(),green:RGB(30,130,145),red:RGB(200,100,20),gold:RGB(150,110,0)}}const A=e=>caps().color?`[${e}m`:"";function buildAnsiDark(){return{gold:A(93),coral:A(91),lavender:A(94),blue:A(94),green:A(92),red:A(91),gray:A(90),dim:A(90),white:A(97),black:A(40),darkBg:caps().color?"[48;5;236m":""}}function buildAnsiLight(){return{gold:A(33),coral:A(31),lavender:A(34),blue:A(34),green:A(32),red:A(31),gray:A(90),dim:A(37),white:A(30),black:A(47),darkBg:caps().color?"[48;5;254m":""}}const DIFF={},DIFF_LIGHT={};function buildDiff(){return{delFg:RGB(220,90,90),delBg:BG(61,1,0),delHiFg:RGB(248,248,242),delHiBg:BG(92,2,0),addFg:RGB(80,200,80),addBg:BG(2,40,0),addHiFg:RGB(255,255,255),addHiBg:BG(4,71,0),codeFg:RGB(248,248,242),gutter:RGB(120,120,120),kw:RGB(102,217,239),fn:RGB(166,226,46),str:RGB(230,219,116),num:RGB(174,129,255),comment:RGB(117,113,94)}}function buildDiffLight(){return{delFg:RGB(160,40,40),delBg:BG(255,235,233),delHiFg:RGB(90,0,0),delHiBg:BG(255,205,200),addFg:RGB(30,130,40),addBg:BG(232,250,232),addHiFg:RGB(0,80,0),addHiBg:BG(195,240,195),codeFg:RGB(40,40,40),gutter:RGB(150,150,150),kw:RGB(0,120,160),fn:RGB(80,140,0),str:RGB(150,110,0),num:RGB(120,60,200),comment:RGB(140,140,130)}}const THEMES={dark:C,light:LIGHT},THEME_TABLE=[{name:"Auto",note:"(match terminal)",light:!1,palette:C},{name:"Dark mode",note:"",light:!1,palette:C},{name:"Light mode",note:"",light:!0,palette:LIGHT},{name:"Dark mode",note:"(colorblind-friendly)",light:!1,palette:CB_DARK},{name:"Light mode",note:"(colorblind-friendly)",light:!0,palette:CB_LIGHT},{name:"Dark mode",note:"(ANSI colors only)",light:!1,palette:ANSI_DARK},{name:"Light mode",note:"(ANSI colors only)",light:!0,palette:ANSI_LIGHT}],AUTO_THEME_INDEX=0;function terminalIsLight(e=caps()){return"light"===e.background}function themeIsLight(e,t=caps()){const n=THEME_TABLE[e];return!!n&&(e
|
|
3
|
+
"use strict";const{caps:caps,detect:detect,onCapsChange:onCapsChange,rgb:rgb,bg:bg}=require("./caps.js"),{STAR:STAR,stencilGlyph:stencilGlyph}=require("./art.js"),RESET="[0m",BOLD="[1m",DIM="[2m",ITALIC="[3m",UNDER="[4m",BOLD_OFF="[22m",ITALIC_OFF="[23m",UNDER_OFF="[24m",RESET_FG="[39m",RESET_BG="[49m",RGB=(e,t,n)=>rgb(e,t,n),BG=(e,t,n)=>bg(e,t,n),C={},LIGHT={},CB_DARK={},CB_LIGHT={},ANSI_DARK={},ANSI_LIGHT={};function buildDark(){return{gold:RGB(255,193,7),coral:RGB(215,119,87),lavender:RGB(177,185,249),blue:RGB(120,160,250),green:RGB(78,186,101),red:RGB(220,90,90),gray:RGB(153,153,153),dim:RGB(80,80,80),white:RGB(255,255,255),black:RGB(30,30,30),darkBg:RGB(20,20,20)}}function buildLight(){return{gold:RGB(180,130,0),coral:RGB(190,100,70),lavender:RGB(120,130,220),blue:RGB(70,110,220),green:RGB(60,150,80),red:RGB(200,60,60),gray:RGB(110,110,110),dim:RGB(170,170,170),white:RGB(40,40,40),black:RGB(245,245,245),darkBg:RGB(255,255,255)}}function buildCbDark(){return{...buildDark(),green:RGB(86,182,194),red:RGB(255,146,43),gold:RGB(255,203,71)}}function buildCbLight(){return{...buildLight(),green:RGB(30,130,145),red:RGB(200,100,20),gold:RGB(150,110,0)}}const A=e=>caps().color?`[${e}m`:"";function buildAnsiDark(){return{gold:A(93),coral:A(91),lavender:A(94),blue:A(94),green:A(92),red:A(91),gray:A(90),dim:A(90),white:A(97),black:A(40),darkBg:caps().color?"[48;5;236m":""}}function buildAnsiLight(){return{gold:A(33),coral:A(31),lavender:A(34),blue:A(34),green:A(32),red:A(31),gray:A(90),dim:A(37),white:A(30),black:A(47),darkBg:caps().color?"[48;5;254m":""}}const DIFF={},DIFF_LIGHT={};function buildDiff(){return{delFg:RGB(220,90,90),delBg:BG(61,1,0),delHiFg:RGB(248,248,242),delHiBg:BG(92,2,0),addFg:RGB(80,200,80),addBg:BG(2,40,0),addHiFg:RGB(255,255,255),addHiBg:BG(4,71,0),codeFg:RGB(248,248,242),gutter:RGB(120,120,120),kw:RGB(102,217,239),fn:RGB(166,226,46),str:RGB(230,219,116),num:RGB(174,129,255),comment:RGB(117,113,94)}}function buildDiffLight(){return{delFg:RGB(160,40,40),delBg:BG(255,235,233),delHiFg:RGB(90,0,0),delHiBg:BG(255,205,200),addFg:RGB(30,130,40),addBg:BG(232,250,232),addHiFg:RGB(0,80,0),addHiBg:BG(195,240,195),codeFg:RGB(40,40,40),gutter:RGB(150,150,150),kw:RGB(0,120,160),fn:RGB(80,140,0),str:RGB(150,110,0),num:RGB(120,60,200),comment:RGB(140,140,130)}}const THEMES={dark:C,light:LIGHT},THEME_TABLE=[{name:"Auto",note:"(match terminal)",light:!1,palette:C},{name:"Dark mode",note:"",light:!1,palette:C},{name:"Light mode",note:"",light:!0,palette:LIGHT},{name:"Dark mode",note:"(colorblind-friendly)",light:!1,palette:CB_DARK},{name:"Light mode",note:"(colorblind-friendly)",light:!0,palette:CB_LIGHT},{name:"Dark mode",note:"(ANSI colors only)",light:!1,palette:ANSI_DARK},{name:"Light mode",note:"(ANSI colors only)",light:!0,palette:ANSI_LIGHT}],AUTO_THEME_INDEX=0;function terminalIsLight(e=caps()){return"light"===e.background}function themeIsLight(e,t=caps()){const n=THEME_TABLE[e];return!!n&&(0===e?terminalIsLight(t):!!n.light)}const SIBLING_THEME_INDEX=[0,2,1,4,3,6,5];function themeContradicts(e,t=caps()){const n=THEME_TABLE[e];return!(!n||0===e||!t||!t.backgroundKnown||!!n.light==("light"===t.background))}function reconcileThemeIndex(e,t=caps()){const n=THEME_TABLE[e];if(!themeContradicts(e,t))return{index:e,changed:!1,reason:"",from:n||null};const i=SIBLING_THEME_INDEX[e],r=THEME_TABLE[i],l=e=>`${e.name}${e.note?" "+e.note:""}`;return{index:i,changed:!0,from:n,reason:`saved theme "${l(n)}" is unreadable on this ${t.background} terminal (${t.reasons.background}) — using "${l(r)}" instead`}}function themeForIndex(e){const t=THEME_TABLE[e];return t?t.palette:C}function themeOf(e){return e&&"number"==typeof e.themeIndex&&e.themeIndex>=3&&e.themeIndex<=6?themeForIndex(e.themeIndex):e&&0===e.themeIndex?terminalIsLight()?LIGHT:C:e&&e.light?LIGHT:C}function diffOf(e){return(e&&"number"==typeof e.themeIndex&&e.themeIndex>=3&&e.themeIndex<=6?THEME_TABLE[e.themeIndex].light:e&&0===e.themeIndex?terminalIsLight():e&&e.light)?DIFF_LIGHT:DIFF}function glyphsFor(e=null){const t=e?"string"==typeof e?detect(process.env,process.stdout,e):e:caps(),n="ascii"===t.glyphs,i=n||"edges"===t.face;if(n)return{cursor:">",check:"+",divider:"-",bullet:".",hint:">",pause:"||",star:stencilGlyph(STAR,t),rightarrow:"->",pointer:">",hook:"_|",block:"*",bloom:"*",spin:["|","/","-","\\","*","-"],ellipse:"...",err:"x",warn:"!",rule:"-",ruleHeavy:"="};const r={cursor:"❯",check:"✔",divider:"╌",bullet:"·",hint:"❯",pause:i?"❚❚":"⏸",star:stencilGlyph(STAR,t),rightarrow:"→",pointer:"▸",hook:i?"_|":"⎿",block:"●",bloom:"✻",spin:["✢","·","✻","*","✽","✶"],ellipse:"…",err:"✗",warn:"⚠",rule:"─",ruleHeavy:"━"};return i?{...r,bloom:"*",spin:["|","/","-","\\","*","-"]}:r}const GLYPH=glyphsFor(),VERBS=["Incubating","Tempering","Determining","Beboppin'","Julienning","Inferring","Simmering","Twisting","Fermenting","Fiddle-faddling","Orbiting","Prestidigitating"],DONE_VERBS=["Churned","Worked"];function rematerialize(){Object.assign(C,buildDark()),Object.assign(LIGHT,buildLight()),Object.assign(CB_DARK,buildCbDark()),Object.assign(CB_LIGHT,buildCbLight()),Object.assign(ANSI_DARK,buildAnsiDark()),Object.assign(ANSI_LIGHT,buildAnsiLight()),Object.assign(DIFF,buildDiff()),Object.assign(DIFF_LIGHT,buildDiffLight()),Object.assign(GLYPH,glyphsFor())}rematerialize(),onCapsChange(rematerialize),module.exports={RGB:RGB,BG:BG,RESET:RESET,BOLD:BOLD,DIM:DIM,ITALIC:"[3m",UNDER:UNDER,BOLD_OFF:"[22m",ITALIC_OFF:"[23m",UNDER_OFF:"[24m",RESET_FG:"[39m",RESET_BG:"[49m",C:C,LIGHT:LIGHT,DIFF:DIFF,DIFF_LIGHT:DIFF_LIGHT,diffOf:diffOf,CB_DARK:CB_DARK,CB_LIGHT:CB_LIGHT,ANSI_DARK:ANSI_DARK,ANSI_LIGHT:ANSI_LIGHT,THEMES:THEMES,THEME_TABLE:THEME_TABLE,AUTO_THEME_INDEX:0,themeIsLight:themeIsLight,terminalIsLight:terminalIsLight,themeForIndex:themeForIndex,themeContradicts:themeContradicts,reconcileThemeIndex:reconcileThemeIndex,SIBLING_THEME_INDEX:SIBLING_THEME_INDEX,GLYPH:GLYPH,glyphsFor:glyphsFor,VERBS:VERBS,DONE_VERBS:DONE_VERBS,themeOf:themeOf,rematerialize:rematerialize};
|
package/vendor/cli/src/title.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const DEFAULT_TITLE="AEGIS Code",TITLE_SPIN=["⠐","⠂","⠄","⠆","⠈","⠠","⠰","⠁"],TOPIC_MAX=48,TITLE_MAX=96,FILLER=/^(?:please|pls|plz|hey|hi|hello|ok(?:ay)?|so|now|just|also|and|then|maybe|well|um|uh|can you|could you|would you|will you|i want you to|i want to|i need you to|i need to|i'?d like you to|i would like you to|i'?d like to|help me|help|let'?s|lets|go ahead and|i'?m trying to|i am trying to|i'?m working on|i am working on)\b[\s,:;-]*/i,LEADING_NOISE=/^(?:[>#*•·\-–—]+|\d+[.)])\s*/,STOPWORDS=new Set(["the","and","for","with","that","this","these","those","you","your","yours","can","could","would","should","will","please","pls","hey","now","then","from","into","onto","over","under","about","also","just","like","want","need","make","made","use","using","get","got","let","lets","its","it","are","was","were","been","has","have","had","but","not","all","any","how","what","when","where","which","who","why","there","here","some","one","two","add","new","fix","fixing","help","doing","does","did","me","my","our","we","i","a","an","to","of","in","on","at","is","be","do"]);function sanitize(t,e=
|
|
3
|
+
"use strict";const DEFAULT_TITLE="AEGIS Code",TITLE_SPIN=["⠐","⠂","⠄","⠆","⠈","⠠","⠰","⠁"],TOPIC_MAX=48,TITLE_MAX=96,FILLER=/^(?:please|pls|plz|hey|hi|hello|ok(?:ay)?|so|now|just|also|and|then|maybe|well|um|uh|can you|could you|would you|will you|i want you to|i want to|i need you to|i need to|i'?d like you to|i would like you to|i'?d like to|help me|help|let'?s|lets|go ahead and|i'?m trying to|i am trying to|i'?m working on|i am working on)\b[\s,:;-]*/i,LEADING_NOISE=/^(?:[>#*•·\-–—]+|\d+[.)])\s*/,STOPWORDS=new Set(["the","and","for","with","that","this","these","those","you","your","yours","can","could","would","should","will","please","pls","hey","now","then","from","into","onto","over","under","about","also","just","like","want","need","make","made","use","using","get","got","let","lets","its","it","are","was","were","been","has","have","had","but","not","all","any","how","what","when","where","which","who","why","there","here","some","one","two","add","new","fix","fixing","help","doing","does","did","me","my","our","we","i","a","an","to","of","in","on","at","is","be","do"]);function sanitize(t,e=96){const n=String(null==t?"":t).replace(/[\u0000-\u001f\u007f]/g," ").replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,Math.max(0,e-1)).trimEnd()}…`}function topicFrom(t,{max:e=48}={}){if(null==t)return"";const n=String(t).split(/[\r\n]+/);let i="";for(const t of n){const e=sanitize(t,4e3).replace(LEADING_NOISE,"").trim();if(e&&!/^```/.test(e)){i=e;break}}if(!i)return"";let o=i;for(let t=0;t<6;t++){const t=o.replace(FILLER,"");if(t===o)break;o=t.replace(LEADING_NOISE,"").trim()}return o=o.replace(/[.!?]+$/,"").trim(),o||(o=i),/^[a-z]/.test(o)&&(o=o[0].toUpperCase()+o.slice(1)),sanitize(o,e)}function keywords(t){const e=new Set;for(const n of String(t||"").toLowerCase().match(/[\p{L}\p{N}_]+/gu)||[])n.length<3||STOPWORDS.has(n)||e.add(n);return[...e]}function titleShift(t,e,{threshold:n=.34}={}){if(!e)return!1;if(!t)return!0;const i=keywords(t),o=keywords(e);if(!i.length||!o.length)return!0;const r=new Set(i);let l=0;for(const t of o)r.has(t)&&l++;return l/Math.min(i.length,o.length)<n}function adoptTopic(t,e,n){const i=topicFrom(e);return i&&titleShift(t,i,n)?i:t||""}function titleText({topic:t="",frame:e=null,app:n="AEGIS Code"}={}){const i=sanitize(t,48);return i?sanitize(e?`${e?`${e} `:""}${i}`:`${i} · ${n}`,96):sanitize(n,96)||"AEGIS Code"}function flagOn(t){return!0===t||null!=t&&!1!==t&&/^(?:1|true|yes|on)$/i.test(String(t).trim())}function titleEnabled(t={},e={}){const n=t||{};if(flagOn(n.AEGIS_TERMINAL_TITLE))return!0;if(flagOn(n.AEGIS_DISABLE_TERMINAL_TITLE))return!1;if(flagOn(n.CLAUDE_CODE_DISABLE_TERMINAL_TITLE))return!1;const i=e||{};return!1!==i.terminalTitle&&!1!==i.terminalTitleBar}function writeTitle(t,e){const n=e||process.stdout;if(!n||"function"!=typeof n.write)return!1;try{return n.write(`]0;${sanitize(t,96)}`),!0}catch{return!1}}module.exports={DEFAULT_TITLE:"AEGIS Code",TITLE_SPIN:TITLE_SPIN,TOPIC_MAX:48,TITLE_MAX:96,sanitize:sanitize,topicFrom:topicFrom,keywords:keywords,titleShift:titleShift,adoptTopic:adoptTopic,titleText:titleText,titleEnabled:titleEnabled,writeTitle:writeTitle};
|
package/vendor/cli/src/todos.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{writePrivateFile:writePrivateFile}=require("./securefs.js");function todosFile(){return path.join(aegisDir(),"todos.json")}function readTodos(){try{const t=JSON.parse(fs.readFileSync(todosFile(),"utf8"));return Array.isArray(t)?t.filter(
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{writePrivateFile:writePrivateFile}=require("./securefs.js");function todosFile(){return path.join(aegisDir(),"todos.json")}function readTodos(){try{const t=JSON.parse(fs.readFileSync(todosFile(),"utf8"));return Array.isArray(t)?t.filter(t=>t&&"string"==typeof t.text).map(t=>({text:t.text,done:!0===t.done,at:t.at||null})):[]}catch{return[]}}function writeTodos(t){const e=(Array.isArray(t)?t:[]).filter(t=>t&&"string"==typeof t.text&&t.text.trim()).map(t=>({text:t.text.trim(),done:!0===t.done,at:t.at||(new Date).toISOString()}));try{writePrivateFile(todosFile(),`${JSON.stringify(e,null,2)}\n`)}catch{}return e}function addTodo(t){const e=String(t||"").trim();if(!e)return{error:"usage: /todos add <text>"};const o=readTodos();return o.push({text:e,done:!1,at:(new Date).toISOString()}),{list:writeTodos(o),added:e}}function completeTodo(t){const e=readTodos(),o=String(t||"").trim();if(!o)return{error:"usage: /todos done <n|text>"};let r=-1;const i=Number.parseInt(o,10);if(Number.isFinite(i)&&String(i)===o)r=i-1;else{const t=e.map((t,e)=>t.text.startsWith(o)?e:-1).filter(t=>t>=0);if(1===t.length)r=t[0];else if(t.length>1)return{error:`"${o}" matches ${t.length} todos — use the number from /todos`}}return r<0||r>=e.length?{error:`no todo #${o} — run /todos to list them`}:(e[r].done=!e[r].done,{list:writeTodos(e),item:e[r]})}function clearTodos(){return writeTodos([]),{list:[]}}function formatTodos(t=readTodos()){return t.length?t.map((t,e)=>` ${String(e+1).padStart(2)}. ${t.done?"✔":"○"} ${t.text}`):[" No todos yet — /todos add <text>"]}module.exports={todosFile:todosFile,readTodos:readTodos,writeTodos:writeTodos,addTodo:addTodo,completeTodo:completeTodo,clearTodos:clearTodos,formatTodos:formatTodos};
|
package/vendor/cli/src/tokens.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const path=require("node:path"),{resolveShared:resolveShared}=require("./sharedpaths.js"),shared=require(resolveShared(path.join("desktop","renderer","usage.js"))),{RATES:RATES,RATE_BASIS:RATE_BASIS,UNPRICED_BY_DESIGN:UNPRICED_BY_DESIGN,isPeak:isPeak,ratesFor:ratesFor,costBreakdown:costBreakdown,cacheHitRate:cacheHitRate,usageBuckets:usageBuckets}=shared,SYSTEM_TOKENS=18e3,TOOL_TOKENS=12e3,CONTEXT_WINDOW=2e5,CONTEXT_WINDOWS={deepseek:1048576,openrouter:256e3,together:256e3,xai:256e3,groq:128e3,ollama:128e3,openai:2e5,anthropic:2e5,google:1e6,gemini:1e6};function contextWindowFor(e){const t=String(e||"").toLowerCase();if(!t)return
|
|
3
|
+
"use strict";const path=require("node:path"),{resolveShared:resolveShared}=require("./sharedpaths.js"),shared=require(resolveShared(path.join("desktop","renderer","usage.js"))),{RATES:RATES,RATE_BASIS:RATE_BASIS,UNPRICED_BY_DESIGN:UNPRICED_BY_DESIGN,isPeak:isPeak,ratesFor:ratesFor,costBreakdown:costBreakdown,cacheHitRate:cacheHitRate,usageBuckets:usageBuckets}=shared,SYSTEM_TOKENS=18e3,TOOL_TOKENS=12e3,CONTEXT_WINDOW=2e5,CONTEXT_WINDOWS={deepseek:1048576,openrouter:256e3,together:256e3,xai:256e3,groq:128e3,ollama:128e3,openai:2e5,anthropic:2e5,google:1e6,gemini:1e6};function contextWindowFor(e){const t=String(e||"").toLowerCase();if(!t)return 2e5;const s=[t],o=t.slice(t.lastIndexOf(":")+1);o&&o!==t&&s.push(o);for(const e of s){if(CONTEXT_WINDOWS[e])return CONTEXT_WINDOWS[e];for(const[t,s]of Object.entries(CONTEXT_WINDOWS))if(e.startsWith(t))return s}return 2e5}function estimateTokens(e){return e?Math.max(1,Math.ceil([...String(e)].length/4)):0}function estimateTokensFromCells(e){const t=Number(e);return t>0?Math.ceil(t/4):0}function transcriptUsage(e,t="sonnet"){const s=e.filter(e=>"user"===e.role),o=e.filter(e=>"assistant"===e.role),n=s.reduce((e,t)=>e+estimateTokens(t.text||""),0);return{input:n,output:o.reduce((e,t)=>e+estimateTokens(t.text||""),0),cacheRead:Math.max(0,n-(s.length?estimateTokens(s[s.length-1].text||""):0)),cacheWrite:s.length?estimateTokens(s[s.length-1].text||""):0}}function usageCost(e,t,s={}){return shared.usageCost(e,t,s)}function sessionAccounting(e,t="sonnet"){const s=transcriptUsage(e,t),o=s.input+s.output,n=3e4+o,r=contextWindowFor(t),a=costBreakdown(s,t);return{usage:s,system:18e3,tools:12e3,history:o,used:n,contextWindow:r,pct:Math.min(100,Math.round(n/r*100)),cost:a.cost,costBasis:a.basis,costPriced:a.priced}}function accountingFromUsage(e,t="sonnet",{exchanges:s=0,real:o=!1,costUsd:n,at:r}={}){const a=costBreakdown(e,t,{at:r}),c="number"==typeof n?n:a.cost,i=o?e.input+e.output+e.cacheRead+e.cacheWrite:3e4+e.input+e.output,u=contextWindowFor(t);return{usage:e,system:18e3,tools:12e3,history:e.input+e.output,used:i,contextWindow:u,pct:Math.min(100,Math.round(i/u*100)),cost:c,costBasis:"number"==typeof n?"settled":a.basis,costPriced:"number"==typeof n||a.priced,exchanges:s,real:o}}function fmtTokens(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function fmtCost(e){return`$${e.toFixed(4)}`}module.exports={RATES:RATES,RATE_BASIS:RATE_BASIS,UNPRICED_BY_DESIGN:UNPRICED_BY_DESIGN,isPeak:isPeak,SYSTEM_TOKENS:18e3,TOOL_TOKENS:12e3,CONTEXT_WINDOW:2e5,CONTEXT_WINDOWS:CONTEXT_WINDOWS,contextWindowFor:contextWindowFor,ratesFor:ratesFor,costBreakdown:costBreakdown,cacheHitRate:cacheHitRate,usageBuckets:usageBuckets,estimateTokens:estimateTokens,estimateTokensFromCells:estimateTokensFromCells,transcriptUsage:transcriptUsage,usageCost:usageCost,sessionAccounting:sessionAccounting,accountingFromUsage:accountingFromUsage,fmtTokens:fmtTokens,fmtCost:fmtCost};
|
package/vendor/cli/src/topup.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const{resolveShared:resolveShared}=require("./sharedpaths.js"),{openUrl:defaultOpenUrl}=require("./system.js"),credentials=require("./credentials.js");function loadShared(e){return require(resolveShared(e))}function createCliClient(){const{createClient:e}=loadShared("client/aegis.js");return e(credentials.clientOptions({channel:"cli"}))}async function ensureKey(e,t){if(e.apiKey)return!0;try{const n=loadShared("client/auto-provision.js"),o=n.autoProvisionApiKey||n.default;if("function"==typeof o){const n=await o(e,t,{app:"cli"});n&&n.key&&"function"==typeof e.setApiKey&&e.setApiKey(n.key)}}catch{}return Boolean(e.apiKey)}async function runTopupCommand(e,t){const n=t||{},o=n.stdout||process.stdout,r=n.stderr||process.stderr,i=n.json?()=>{}:e=>o.write(e);let a=null;const s=(e,t)=>(n.json&&o.write(JSON.stringify(t)+"\n"),e);let c;try{c=loadShared("client/topup.js")}catch(e){return r.write(`aegiscode: the shared top-up module is missing — ${e&&e.message||e}\n`),2}const{parseTopupAmount:u,startTopup:l,createCreditWatch:d,TOPUP_POLL_MS:p,TOPUP_POLL_TRIES:h,TOPUP_MIN_EUR:m,TOPUP_MAX_EUR:g}=c,f=u(e);if(!f.ok)return r.write(`aegiscode: ${f.message}\n usage: aegiscode topup [${m}..${g}] (default 10)\n`),s(2,{ok:!1,credited:!1,amount_eur:null,url:null,balance_eur:null,error:f.message});a={ok:!1,credited:!1,amount_eur:f.amount,url:null,balance_eur:null},r.write(`aegiscode: requesting a ${f.amount} EUR top-up from the account service…\n`);const y=n.client||createCliClient();if(!y.apiKey&&!await ensureKey(y,credentials))return r.write("aegiscode: no AEGIS key on this machine and none could be provisioned —\n `aegiscode login <api_key>` (from https://aegiscloud.org/dashboard) first\n"),a.error="no usable AEGIS key",s(2,a);const w=await l(y,f.amount);if(!w.ok)return r.write(`aegiscode: the top-up could not be started — ${w.message}\n`),w.hint&&r.write(`aegiscode: ${w.hint}\n`),a.error=w.message,a.status=w.status,s(2,a);a.url=w.url;const b=n.openUrl||defaultOpenUrl,k=n.sleep||(e=>new Promise(
|
|
3
|
+
"use strict";const{resolveShared:resolveShared}=require("./sharedpaths.js"),{openUrl:defaultOpenUrl}=require("./system.js"),credentials=require("./credentials.js");function loadShared(e){return require(resolveShared(e))}function createCliClient(){const{createClient:e}=loadShared("client/aegis.js");return e(credentials.clientOptions({channel:"cli"}))}async function ensureKey(e,t){if(e.apiKey)return!0;try{const n=loadShared("client/auto-provision.js"),o=n.autoProvisionApiKey||n.default;if("function"==typeof o){const n=await o(e,t,{app:"cli"});n&&n.key&&"function"==typeof e.setApiKey&&e.setApiKey(n.key)}}catch{}return Boolean(e.apiKey)}async function runTopupCommand(e,t){const n=t||{},o=n.stdout||process.stdout,r=n.stderr||process.stderr,i=n.json?()=>{}:e=>o.write(e);let a=null;const s=(e,t)=>(n.json&&o.write(JSON.stringify(t)+"\n"),e);let c;try{c=loadShared("client/topup.js")}catch(e){return r.write(`aegiscode: the shared top-up module is missing — ${e&&e.message||e}\n`),2}const{parseTopupAmount:u,startTopup:l,createCreditWatch:d,TOPUP_POLL_MS:p,TOPUP_POLL_TRIES:h,TOPUP_MIN_EUR:m,TOPUP_MAX_EUR:g}=c,f=u(e);if(!f.ok)return r.write(`aegiscode: ${f.message}\n usage: aegiscode topup [${m}..${g}] (default 10)\n`),s(2,{ok:!1,credited:!1,amount_eur:null,url:null,balance_eur:null,error:f.message});a={ok:!1,credited:!1,amount_eur:f.amount,url:null,balance_eur:null},r.write(`aegiscode: requesting a ${f.amount} EUR top-up from the account service…\n`);const y=n.client||createCliClient();if(!y.apiKey&&!await ensureKey(y,credentials))return r.write("aegiscode: no AEGIS key on this machine and none could be provisioned —\n `aegiscode login <api_key>` (from https://aegiscloud.org/dashboard) first\n"),a.error="no usable AEGIS key",s(2,a);const w=await l(y,f.amount);if(!w.ok)return r.write(`aegiscode: the top-up could not be started — ${w.message}\n`),w.hint&&r.write(`aegiscode: ${w.hint}\n`),a.error=w.message,a.status=w.status,s(2,a);a.url=w.url;const b=n.openUrl||defaultOpenUrl,k=n.sleep||(e=>new Promise(t=>setTimeout(t,e))),U=null==n.intervalMs?p:n.intervalMs,S=null==n.maxTries?h:n.maxTries,T=Math.max(1,Math.round(U*S/1e3));b(w.url)?i(`aegiscode: opening the payment page in your browser — ${w.amount} EUR\n`):i(`aegiscode: open this to pay ${w.amount} EUR:\n ${w.url}\n`),i(`aegiscode: watching this account's bank for up to ${T}s to confirm the credit\n`);const $=d(y,{maxTries:S});let _=!1;for(;;){const e=await $.tick();if("function"==typeof n.onStep&&n.onStep(e),"credited"===e.state)return a.ok=!0,a.credited=!0,a.balance_eur=e.amount,i(`aegiscode: credit confirmed — the bank is now ${e.amount.toFixed(2)} EUR\naegiscode: (this account was created by this machine, so the browser there has no\n session for it — the confirmation comes from the API, not the page)\n`),s(0,a);if("expired"===e.state)return i(`aegiscode: no credit observed within ${T}s — if you completed the payment it\naegiscode: may still land; re-run \`aegiscode topup\` or check \`/billing\` in a session\n`),a.error="no credit observed within the watch window",s(1,a);null==e.baseline||_||n.json||(_=!0,i(`aegiscode: bank before the payment: ${e.baseline.toFixed(2)} EUR\n`)),await k(U)}}module.exports={runTopupCommand:runTopupCommand,ensureKey:ensureKey,createCliClient:createCliClient};
|
package/vendor/cli/src/update.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const path=require("node:path"),fs=require("node:fs"),{execFileSync:execFileSync}=require("node:child_process"),{resolveShared:resolveShared}=require("./deps.js"),shared=require(resolveShared("client/update.js")),VERSION=require("../package.json").version,PKG=shared.PKG||"aegiscode",DECOMPOSED_VERSIONS=Object.freeze(["1.0.47"]);function decomposedVersion(e=VERSION){return DECOMPOSED_VERSIONS.includes(String(e||"").trim())}function decomposedUpdateLine(e=VERSION){return decomposedVersion(e)?`This version (${e}) is DECOMPOSED — update to the latest release.`:null}let methodCache=null;function installMethod(){if(methodCache)return methodCache;const e=shared.detectInstallMethod;if("function"!=typeof e)return methodCache="npm",methodCache;try{methodCache=e({env:process.env,argv:process.argv,pkg:PKG,entry:path.resolve(__dirname,".."),fileExists:e=>fs.existsSync(path.resolve(__dirname,"..","..",e))})}catch{methodCache="npm"}return methodCache}function compareVersions(e,n){const t=String(e||"0").split("-")[0].split(".").map(
|
|
3
|
+
"use strict";const path=require("node:path"),fs=require("node:fs"),{execFileSync:execFileSync}=require("node:child_process"),{resolveShared:resolveShared}=require("./deps.js"),shared=require(resolveShared("client/update.js")),VERSION=require("../package.json").version,PKG=shared.PKG||"aegiscode",DECOMPOSED_VERSIONS=Object.freeze(["1.0.47"]);function decomposedVersion(e=VERSION){return DECOMPOSED_VERSIONS.includes(String(e||"").trim())}function decomposedUpdateLine(e=VERSION){return decomposedVersion(e)?`This version (${e}) is DECOMPOSED — update to the latest release.`:null}let methodCache=null;function installMethod(){if(methodCache)return methodCache;const e=shared.detectInstallMethod;if("function"!=typeof e)return methodCache="npm",methodCache;try{methodCache=e({env:process.env,argv:process.argv,pkg:PKG,entry:path.resolve(__dirname,".."),fileExists:e=>fs.existsSync(path.resolve(__dirname,"..","..",e))})}catch{methodCache="npm"}return methodCache}function compareVersions(e,n){const t=String(e||"0").split("-")[0].split(".").map(e=>Number.parseInt(e,10)||0),r=String(n||"0").split("-")[0].split(".").map(e=>Number.parseInt(e,10)||0);for(let e=0;e<Math.max(t.length,r.length);e++){const n=(t[e]||0)-(r[e]||0);if(n)return n>0?1:-1}return 0}function upgradeAdvice({current:e=VERSION,latest:n=null,packageName:t=PKG,method:r="npm"}={}){if(!n)return{upToDate:null,lines:[` Could not read the npm registry — local version is ${e}.`]};if(compareVersions(n,e)>0){const s="function"==typeof shared.updatePlan?shared.updatePlan({current:e,latest:n,behind:!0,channel:"npm",pkg:t,method:r}):null,a=[` Installed: ${e}`,` Published: ${n}`,` Channel: ${r}`,` Upgrade: ${s&&s.instruction||`npm i -g ${t}@latest`}`];return s&&s.apply&&a.push(" (or run `/upgrade apply` to do it here)"),{upToDate:!1,lines:a,plan:s}}return{upToDate:!0,lines:[` Installed ${e} is the published ${n} — nothing to upgrade.`]}}function applyUpgrade({current:e=VERSION,packageName:n=PKG,method:t="npm",latest:r=null}={}){const s="function"==typeof shared.updatePlan&&r?shared.updatePlan({current:e,latest:r,behind:!0,channel:"npm",pkg:n,method:t}):null,a=s&&s.apply?s.apply:null;if(!a)return{ok:!0,skipped:!0,channel:t,command:null,instruction:s&&s.instruction||("npm"===t?`npm i -g ${n}@latest`:"restart to pick up the new version")};try{const e=("function"==typeof shared.installSpawn?shared.installSpawn(a,{env:process.env}):{command:a.command,args:a.args,shell:!1})||{command:a.command,args:a.args,shell:!1},n=execFileSync(e.command,e.args,{encoding:"utf8",timeout:18e4,stdio:["ignore","pipe","pipe"],shell:!0===e.shell,windowsHide:!0});return{ok:!0,channel:t,command:`${a.command} ${a.args.join(" ")}`,output:String(n||"").trim()}}catch(e){return{ok:!1,channel:t,command:`${a.command} ${a.args.join(" ")}`,error:String(e&&(e.stderr||e.message)||e).trim()}}}function latestPublishedVersion({packageName:e=PKG,timeoutMs:n=5e3}={}){try{const t=execFileSync("npm",["view",e,"version"],{encoding:"utf8",timeout:n,stdio:["ignore","pipe","ignore"]}),r=String(t).trim();return/^\d+\.\d+\.\d+/.test(r)?r:null}catch{return null}}module.exports={...shared,VERSION:VERSION,compareVersions:compareVersions,upgradeAdvice:upgradeAdvice,applyUpgrade:applyUpgrade,installMethod:installMethod,latestPublishedVersion:latestPublishedVersion,DECOMPOSED_VERSIONS:DECOMPOSED_VERSIONS,decomposedVersion:decomposedVersion,decomposedUpdateLine:decomposedUpdateLine};
|
|
@@ -1,4 +1,4 @@
|
|
|
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";function envVar(e){if("undefined"==typeof process||!process.env)return"";const t=process.env[e];return t&&!/^\$\{[A-Z_]+\}$/.test(t)?t:""}function envIdleMs(e){const t=envVar(e);if(!t)return 0;const n=Number(t);return Number.isFinite(n)&&n>0?n:0}const DSML_RE_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*>/g,DSML_RE_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/g,DSML_RE_LEADER=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:(?:tool|function)[_▁ ]*calls?|reasoning)[_▁ ]*(?:begin|end)?\s*>/gi,DSML_RE_ANY_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_SKELETON=/<\s*\/?\s*(?:tool_calls|function_calls|invoke|parameter|param|reasoning)\b[^>]{0,120}>/gi,DSML_RE_JSON_CALLS=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|([\s\S]*?)|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_JSON_CALLS_OPEN=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|/gi,DSML_RE_JSON_CALLS_CLOSE=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_ENVELOPE_TOKEN=/|[ \t]?[A-Za-z0-9_▁]*[ \t]?|/g,DSML_RE_DRIFT_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>/gi,DSML_RE_DRIFT_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>/gi,DSML_RE_PARAM_CLOSE=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/gi,DSML_RE_ATTR=/([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,DSML_RE_STRUCT_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_STRUCT_CLOSER=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_WRAPPER_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?!(?:invoke|call|tool_call|parameter|param|arg)\b)[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_TRAILING_LT=/<\s*\/?\s*$/,DSML_RE_OPEN_TOKEN=/^|[ \t]?[A-Za-z0-9_▁]*[ \t]?$/,DSML_HOLD_MAX=4194304;function dsmlAttrs(e){const t={};if(!e)return t;let n;for(DSML_RE_ATTR.lastIndex=0;n=DSML_RE_ATTR.exec(e);)t[n[1].toLowerCase()]=null!=n[2]?n[2]:n[3];return t}function dsmlJson(e){const t=String(null==e?"":e).trim();try{const e=JSON.parse(t);return void 0===e?t:e}catch{return t}}function dsmlArgs(e){const t={};let n;for(DSML_RE_PARAM.lastIndex=0;n=DSML_RE_PARAM.exec(e);){const e=dsmlAttrs(n[1]),r=e.name||e.key||`arg${Object.keys(t).length}`,o="false"===String(e.string||"").toLowerCase()||"true"===String(e.json||"").toLowerCase();t[r]=o?dsmlJson(n[2]):n[2]}return t}function decodeDeepSeekDSML(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n=e;DSML_RE_INVOKE.lastIndex=0;const r=[];let o;for(;o=DSML_RE_INVOKE.exec(n);){const e=dsmlAttrs(o[1]),n=e.name||e.function||e.tool||"";n&&t.push({name:n,args:dsmlArgs(o[2])}),r.push([o.index,o.index+o[0].length])}for(let e=r.length-1;e>=0;e--)n=n.slice(0,r[e][0])+n.slice(r[e][1]);return n=n.replace(DSML_RE_JSON_CALLS,((e,n)=>{const r=dsmlJson(n),o=Array.isArray(r)?r:r&&Array.isArray(r.tool_calls)?r.tool_calls:[];for(const e of o){const n=e&&e.function||e||{},r=n.name||e&&e.name||"";if(!r)continue;let o=null!=n.arguments?n.arguments:e&&e.arguments;"string"==typeof o&&(o=dsmlJson(o)),t.push({name:r,args:o&&"object"==typeof o?o:{}})}return""})),n=n.replace(DSML_RE_LEADER,""),{text:n,calls:t}}function decodeDeepSeekDSMLDrift(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n;for(DSML_RE_DRIFT_INVOKE.lastIndex=0;n=DSML_RE_DRIFT_INVOKE.exec(e);)t.push({at:n.index,attrs:n[1],body:DSML_RE_DRIFT_INVOKE.lastIndex});if(!t.length)return{text:e,calls:[]};const r=[];let o="",s=0;for(let n=0;n<t.length;n++){const a=n+1<t.length?t[n+1].at:e.length,i=e.slice(t[n].body,a),c=dsmlAttrs(t[n].attrs),l=c.name||c.function||c.tool||"",u={},d=[];let m;for(DSML_RE_DRIFT_PARAM.lastIndex=0;m=DSML_RE_DRIFT_PARAM.exec(i);)d.push({at:m.index,attrs:m[1],from:DSML_RE_DRIFT_PARAM.lastIndex});for(let e=0;e<d.length;e++){const t=e+1<d.length?d[e+1].at:i.length,n=i.slice(d[e].from,t).replace(DSML_RE_PARAM_CLOSE,""),r=dsmlAttrs(d[e].attrs),o=r.name||r.key||`arg${Object.keys(u).length}`,s="false"===String(r.string||"").toLowerCase();u[o]=s?dsmlJson(n):n}o+=e.slice(s,t[n].at),s=a,l&&r.push({name:l,args:u})}return o+=e.slice(s),{text:o,calls:r}}function dsmlResidue(e){return e?-1===e.indexOf("|")?e.replace(DSML_RE_SKELETON,""):e.replace(DSML_RE_ANY_TAG,"").replace(DSML_RE_SKELETON,"").replace(DSML_RE_ENVELOPE_TOKEN,""):e}function dsmlUnterminated(e){return!!DSML_RE_OPEN_TOKEN.test(e)||(e.match(DSML_RE_STRUCT_TAG)||[]).length>(e.match(DSML_RE_STRUCT_CLOSER)||[]).length}function dsmlHoldFrom(e){const t=e.search(/<\s*\/?\s*|/);if(-1!==t)return t;const n=e.search(DSML_RE_JSON_CALLS_OPEN);if(-1!==n&&-1===e.slice(n).search(DSML_RE_JSON_CALLS_CLOSE))return n;const r=DSML_RE_TRAILING_LT.exec(e);if(r)return r.index;const o=e.indexOf("|");return-1!==o&&dsmlUnterminated(e.slice(o))?o:-1}function makeDeepSeekEnvelopeStripper(){let e="";const t=[],n=n=>{e+="string"==typeof n?n:"";const r=decodeDeepSeekDSML(e);e=r.text;for(const e of r.calls)t.push(e);e=e.replace(DSML_RE_WRAPPER_TAG,"");const o=dsmlHoldFrom(e);let s;return-1!==o&&e.length-o<=DSML_HOLD_MAX?(s=e.slice(0,o),e=e.slice(o)):(s=e,e=""),dsmlResidue(s)};return n.flush=()=>{const n=decodeDeepSeekDSML(e);e="";for(const e of n.calls)t.push(e);const r=decodeDeepSeekDSMLDrift(n.text);for(const e of r.calls)t.push(e);return dsmlResidue(r.text)},n.calls=()=>t.slice(),n}function randomUUID(){const e="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||null,t=e&&e.crypto;if(t&&"function"==typeof t.randomUUID)try{return t.randomUUID()}catch(e){}if(t&&"function"==typeof t.getRandomValues)try{const e=new Uint8Array(16);t.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128;const n=Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}catch(e){}if("function"==typeof require)try{const e=require("crypto");if(e&&"function"==typeof e.randomUUID)return e.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}const DEFAULT_API_BASE="https://aegiscloud.org",CLIENT_VERSION="3.2.0",DEFAULT_TIMEOUT_MS=6e4,MAX_BODY_BYTES=8388608,RATE_LIMIT_RETRIES=4,RATE_LIMIT_MAX_WAIT_MS=3e4,RATE_LIMIT_BASE_WAIT_MS=1e3,TRANSIENT_STREAM_ERROR_PATTERN=/connection reset by peer|broken pipe|connection aborted|errno 104|errno 32|errno 54|econnreset|epipe/i,TRANSIENT_STREAM_RETRIES=2,TRANSIENT_STREAM_BASE_WAIT_MS=500,TRANSIENT_SOCKET_CODE_PATTERN=/^(ECONNRESET|EPIPE|ECONNABORTED|UND_ERR_SOCKET|UND_ERR_CLOSED)$/,TRANSIENT_SOCKET_RETRIES=2,SSE_UPSTREAM_TIMEOUT_PATTERN=/request timed out|timed out waiting|upstream timeout/i;function upstreamTimeoutMessage(e,t){const n=Number(t);return`${e} — the upstream provider gave up before answering${null!=t&&Number.isFinite(n)?n>=1e3?` after ${(n/1e3).toFixed(1)}s`:` after ${Math.max(0,Math.round(n))}ms`:""}. That is the provider's own deadline, not this client's stream budget, so raising AEGIS_SSE_IDLE_TIMEOUT_MS cannot help`}function createClient(e={}){const t=(e.apiBase||envVar("AEGIS_API_BASE")||DEFAULT_API_BASE).replace(/\/+$/,"");let n=void 0!==e.apiKey?e.apiKey:envVar("AEGIS_API_KEY");const r=void 0!==e.memoryToken?e.memoryToken:envVar("AEGIS_MEMORY_TOKEN"),o=e.clientVersion||"3.2.0",s="cli"===e.channel?"cli":"desktop";function a(e){return n&&"string"==typeof e?e.split(n).join("[redacted]"):e}const i={ECONNRESET:"connection reset by the backend",ECONNREFUSED:"connection refused — is the backend running?",EPIPE:"connection closed while sending the request",ETIMEDOUT:"connection timed out",ENOTFOUND:"host not found — check the endpoint URL",EAI_AGAIN:"DNS lookup failed temporarily",EHOSTUNREACH:"host unreachable",ENETUNREACH:"network unreachable",CERT_HAS_EXPIRED:"TLS certificate has expired",DEPTH_ZERO_SELF_SIGNED_CERT:"TLS certificate is self-signed",UND_ERR_SOCKET:"the socket closed before the response finished",UND_ERR_CLOSED:"the connection was closed",UND_ERR_CONNECT_TIMEOUT:"timed out connecting to the backend",UND_ERR_HEADERS_TIMEOUT:"the backend accepted the connection but never sent a response",UND_ERR_BODY_TIMEOUT:"the backend stalled mid-response",UND_ERR_ABORTED:"the request was aborted"};function c(e,t){const n=e instanceof Error?e:new Error(String(e)),r=n&&n.name;if("AbortError"===r||"TimeoutError"===r)return e;const o=l(n),s=t||"the backend",a=new Error(o?`Could not reach ${s} (${o}).`:`Could not reach ${s}: ${n.message||"network failure"}.`);return a.status=0,a.code="network",a.networkCode=o||null,a.data=null,a.cause=n,a}function l(e,t=0){if(!e||t>4)return null;const n=e.code||e.cause&&e.cause.code,r=e.cause,o=r?l(r,t+1):null;return i[n]?i[n]:o||(r&&r.message&&r.message!==e.message?r.message:n||null)}async function u(e,n){const r=n&&n.signal,o="function"==typeof AbortController?new AbortController:null;let s=null;o&&(s=setTimeout((()=>o.abort()),S),s&&"function"==typeof s.unref&&s.unref(),r&&(r.aborted?o.abort():"function"==typeof r.addEventListener&&r.addEventListener("abort",(()=>{o&&o.abort()}),{once:!0})));try{return await fetch(e,{...n||{},signal:o?o.signal:r})}catch(e){if(o&&o.signal.aborted&&(!r||!r.aborted)){const e=new Error(`Timed out after ${S/1e3}s waiting for ${t}.`);throw e.status=0,e.code="timeout",e.data=null,e}throw c(e,t)}finally{s&&clearTimeout(s)}}function d(e,t){const n=e&&e.headers&&"function"==typeof e.headers.get?e.headers.get("retry-after"):null;let r=0;if(n){const e=Number(n);if(Number.isFinite(e)&&e>=0)r=1e3*e;else{const e=Date.parse(n);Number.isFinite(e)&&(r=e-Date.now())}}return r||(r=R*Math.pow(2,t)),Math.min(r,A)}function m(e,t){return new Promise((n=>{const r=setTimeout(n,e);if(r&&"function"==typeof r.unref&&r.unref(),t&&"function"==typeof t.addEventListener)return t.aborted?(clearTimeout(r),void n()):void t.addEventListener("abort",(()=>{clearTimeout(r),n()}),{once:!0})}))}function _(e,t=0){if(!e||t>4)return null;const n=e.code;return"string"==typeof n&&"network"!==n?n:_(e.cause,t+1)}async function f(e,t){let n=0;for(;;)try{return await u(e,t)}catch(e){const r=e&&"network"===e.code?String(_(e)||""):"";if(n>=2||!TRANSIENT_SOCKET_CODE_PATTERN.test(r))throw e;if(t&&t.signal&&t.signal.aborted)throw e;if(await m(500*Math.pow(2,n),t&&t.signal),t&&t.signal&&t.signal.aborted)throw e;n++}}async function E(e,t){let n=await f(e,t);for(let r=0;n&&429===n.status&&r<T;r++){const o=d(n,r);try{n.body&&await n.body.cancel()}catch{}await m(o,t&&t.signal),n=await f(e,t)}for(let r=0;n&&n.status>=500&&n.status<600&&r<2;r++){let o="";try{o=await g(n.clone())}catch{break}if(!TRANSIENT_STREAM_ERROR_PATTERN.test(o))break;await m(500*Math.pow(2,r),t&&t.signal),n=await f(e,t)}return n}function p(e){if(!e)return e;if("AbortError"===e.name||"TimeoutError"===e.name)return e;if("network"===e.code||"timeout"===e.code||"ABORT_ERR"===e.code)return e;if(/^stream stalled - /.test(String(e.message||"")))return e;if(!_(e))return e;const n=c(e,t);return n.bodyPhase=!0,n}async function g(e){if(!e||!e.body||"function"!=typeof e.body.getReader){let t;try{t=await e.text()}catch(e){const t=p(e);throw t&&"network"===t.code&&(t.bytesRead=0),t||e}return t.length>h?t.slice(0,h):t}const n=e.body.getReader(),r=new TextDecoder;let o="",s=0;try{for(;;){let a;try{a=await n.read()}catch(e){const t=p(e);throw t&&"network"===t.code&&(t.bytesRead=s),t||e}const{done:i,value:c}=a;if(i)break;if(s+=c?c.byteLength:0,s>h){const n=new Error(`Response from ${t} exceeded the ${h/1048576}MB cap.`);throw n.status=e.status,n.code="body_too_large",n.data=null,n}o+=r.decode(c,{stream:!0})}return o+=r.decode(),o}finally{try{await n.cancel()}catch{}}}let y=null;const S=Number(e.timeoutMs)>0?Number(e.timeoutMs):Number(envVar("AEGIS_HTTP_TIMEOUT_MS"))>0?Number(envVar("AEGIS_HTTP_TIMEOUT_MS")):6e4,h=Number(e.maxBodyBytes)>0?Number(e.maxBodyBytes):8388608,T=Number(e.rateLimitRetries)>=0?Number(e.rateLimitRetries):4,R=Number(e.rateLimitBaseWaitMs)>=0?Number(e.rateLimitBaseWaitMs):1e3,A=Number(e.rateLimitMaxWaitMs)>0?Number(e.rateLimitMaxWaitMs):3e4;function M(e,n){try{const r=new URL(`/go/${String(e||"upgrade").replace(/^\/+|\/+$/g,"")}`,t);r.searchParams.set("s",s);const o=String(n||"").trim().toLowerCase();return/^[a-z0-9][a-z0-9_-]{0,63}$/.test(o)&&r.searchParams.set("c",o),r.toString()}catch(e){return""}}function D(e){const t={"Content-Type":"application/json","X-AEGIS-Version":o,...e};return n&&(t["X-API-Key"]=n,t.Authorization=`Bearer ${n}`),t}async function L(e,n){return O(await E(`${t}${e}`,n))}async function I(e,t){let n=0;for(;;)try{return await L(e,t)}catch(e){if(!e||"network"!==e.code||!0!==e.bodyPhase||0!==e.bytesRead||n>=2)throw e;if(t&&t.signal&&t.signal.aborted)throw e;if(await m(500*Math.pow(2,n),t&&t.signal),t&&t.signal&&t.signal.aborted)throw e;n++}}async function w(e,t,n,r){return I(e,{method:"POST",headers:n||D(),body:JSON.stringify(t||{}),signal:r&&r.signal})}async function b(e,t,n){return I(e,{method:"GET",headers:t||D(),signal:n&&n.signal})}function N(e,t){const n=e||{},r=n.latest_cli||"",s=n.latest_desktop||"",a=r||s||n.required||"",i=new Error(a?`This client (v${o}) is out of date — upgrade to v${a}.`:`This client (v${o}) is out of date.`);return i.status=t,i.code="version_mismatch",i.data=n,i.upgrade={required:n.required||"",latestCli:r,latestDesktop:s,url:M("upgrade","version_gate")||n.update_url||""},i}async function O(e){const t=await g(e);let n;try{n=t?JSON.parse(t):{}}catch{n={raw:a(t)}}if(!e.ok){if(function(e,t){return 426===e||t&&"version_mismatch"===t.code}(e.status,n))throw N(n,e.status);const t=n&&(n.error?.message||n.error||n.message)||`HTTP ${e.status}`,r=new Error(a("string"==typeof t?t:JSON.stringify(t)));throw e.status>=500&&e.status<600&&SSE_UPSTREAM_TIMEOUT_PATTERN.test(r.message)?(r.serverStatus=e.status,r.status=0,r.code="timeout",r.message=upstreamTimeoutMessage(r.message)):r.status=e.status,r.data=n,r}if(n&&"version_mismatch"===n.code)throw N(n,e.status);return n}function v(e){if(!e)return"";const t=e.error;return"string"==typeof t?t:t&&"string"==typeof t.message?t.message:t&&"string"==typeof t.error?t.error:"string"==typeof e.message?e.message:"string"==typeof e.error_message?e.error_message:""}async function k(){if(r)return r;if(y)return y;const e=await w("/api/verify-api-key",{api_key:n});if(!e||!e.memory_token){const e=M("upgrade","memory_quota");throw new Error("This AEGIS account has no memory token. "+(e?`Enable cloud memory at ${e}`:"Enable cloud memory in your AEGIS account settings."))}return y=e.memory_token,y}function x(e){return{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`}}function U(e){if(null==e)return"";if("string"==typeof e)return e;if(!Array.isArray(e))return String(e);let t="";for(let n=0;n<e.length;n+=1){const r=e[n];r&&"object"==typeof r&&("string"==typeof r.text?t+=(t?"\n":"")+r.text:"image_url"===r.type&&(t+=(t?"\n":"")+"[image]"))}return t}function C(e,t,n){const r=Array.isArray(e)?e.filter(Boolean):[],o=[];if(t&&!r.some((e=>e&&"system"===e.role))&&o.push({role:"system",content:t}),o.push(...r),null!=n&&("string"==typeof n?""!==n:Array.isArray(n)&&n.length>0)){const e=o[o.length-1];(Array.isArray(n)&&e&&"user"===e.role?U(e.content)===U(n):e&&"user"===e.role&&e.content===n)||o.push({role:"user",content:n})}return o}function P(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;return"string"==typeof n?n:""}function $(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;if("string"!=typeof n||-1===n.indexOf("|"))return e;const r=decodeDeepSeekDSML(n),o=decodeDeepSeekDSMLDrift(r.text);t.message.content=dsmlResidue(o.text);const s=[...r.calls,...o.calls];return s.length&&(e.toolCalls=[...Array.isArray(e.toolCalls)?e.toolCalls:[],...s.map((e=>({id:"",name:e.name,args:e.args||{}})))]),e}async function B(e,n,r,o,s,i){const{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:u,_transientStreamAttempt:d=0}=i||{},_=n=>E(`${t}${e}`,{method:"POST",headers:r,body:JSON.stringify({...n,stream:!0}),signal:s});let f;try{f=await _(n)}catch(e){throw e}if(!f.ok&&426===f.status){let e={};try{const t=await g(f);e=t?JSON.parse(t):{}}catch{e={}}throw N(e,f.status)}if(!f.ok&&u&&n.stream_options){try{f.body&&await f.body.cancel()}catch{}const t={...n};delete t.stream_options,n=t;try{f=await _(n)}catch(e){throw e}}if(!f.ok){const t={...n};delete t.stream_options;const a=$(await w(e,{...t,stream:!1},r,{signal:s})),i=P(a);return i&&o({delta:i}),a}if(!(f.headers.get("content-type")||"").includes("text/event-stream")){const e=$(await O(f)),t=P(e);return t?o({delta:t}):function(e,t){if(e&&"version_mismatch"===e.code)throw N(e,t||426);const n=a(v(e));if(!n)return;const r=new Error(n);throw r.status=t||500,r.data=e,r}(e,f.status),e}const y=f.body.getReader(),S=new TextDecoder;let h="",T="",R="",A=n.model,M=null,D="";const L=new Map;let I=null,b="";const k=makeDeepSeekEnvelopeStripper(),x=idleBudgetFor(f,l);let U=Date.now();const C=U;let K=0;async function G(){let e,t=null;const n=Math.max(0,x-(Date.now()-U)),r=new Promise(((t,r)=>{e=setTimeout((()=>{r(new Error(K>0?`stream stalled - only keep-alives for ${x/1e3}s`:`stream stalled - no data for ${x/1e3}s`))}),n)})),o=s&&"function"==typeof s.addEventListener?new Promise(((e,n)=>{t=()=>{const e=new Error("The turn was stopped.");e.name="AbortError",e.code="ABORT_ERR",n(e)},s.aborted?t():s.addEventListener("abort",t,{once:!0})})):null;try{return await(o?Promise.race([y.read(),r,o]):Promise.race([y.read(),r]))}finally{clearTimeout(e),s&&t&&"function"==typeof s.removeEventListener&&s.removeEventListener("abort",t)}}for(;;){let t,l;try{({done:t,value:l}=await G())}catch(t){y.cancel().catch((()=>{}));const a=p(t);if(a&&"network"===a.code&&(a.bytesRead=b?1:0,0===a.bytesRead&&d<2&&(!s||!s.aborted))){if(await m(500*Math.pow(2,d),s),s&&s.aborted)throw a;return B(e,n,r,o,s,{...i,_transientStreamAttempt:d+1})}throw a||t}if(t)break;h+=S.decode(l,{stream:!0});const u=h.split("\n");h=u.pop();for(const e of u){const t=e.trim();if(!t.startsWith("data:")){t.startsWith(":")&&K++;continue}U=Date.now();const n=t.slice(5).trim();if(!n||"[DONE]"===n)continue;let r;try{r=JSON.parse(n)}catch{continue}if(r.error){if(!D){const e=r.error;D="string"==typeof e?e:v({error:e})||"stream error",D=a(D)}continue}r.model&&(A=r.model),r.usage&&(M=r.usage);const s=r.choices&&r.choices[0];s&&s.finish_reason&&(I=s.finish_reason);const i=(e,t,n,r)=>{if("string"==typeof e&&e)return r(e),n+e;if("string"==typeof t&&t){if(!n)return r(t),t;if(t.startsWith(n)){const e=t.slice(n.length);return e&&r(e),t}return n}return n};R=i(s&&s.delta&&s.delta.reasoning_content,s&&s.message&&s.message.reasoning_content,R,(e=>{"function"==typeof c?c(e):o({reasoning:e})})),T=i(s&&s.delta&&s.delta.content,s&&s.message&&s.message.content,T,(e=>{const t=k(e);t&&(b+=t,o({delta:t}))}));const l=s&&s.delta&&s.delta.tool_calls||s&&s.message&&s.message.tool_calls;if(Array.isArray(l))for(const e of l){const t=null==e.index?0:e.index,n=L.get(t)||{id:"",type:"function",function:{name:"",arguments:""}};e.id&&(n.id=e.id),e.type&&(n.type=e.type);const r=e.function||{};r.name&&(n.function.name=r.name),"string"==typeof r.arguments&&(n.function.arguments+=r.arguments),L.set(t,n)}}}if(!T&&D){if(d<2&&TRANSIENT_STREAM_ERROR_PATTERN.test(D))return await m(500*Math.pow(2,d),s),B(e,n,r,o,s,{...i,_transientStreamAttempt:d+1});const t=SSE_UPSTREAM_TIMEOUT_PATTERN.test(D),a=new Error(t?upstreamTimeoutMessage(D,Date.now()-C):D);throw a.status=t?0:f.status,t&&(a.code="timeout"),a}const V=k.flush();V&&(b+=V,o({delta:V}));const F=[...L.entries()].sort(((e,t)=>e[0]-t[0])).map((([e,t])=>({...t,id:t.id||`call_${e}`}))),J={content:b};R&&(J.reasoning_content=R),F.length&&(J.tool_calls=F);const W={model:A,choices:[{message:J,...I?{finish_reason:I}:{}}]};M&&(W.usage=M);const X=k.calls();return(F.length||X.length)&&(W.toolCalls=[...F.map((e=>({id:e.id,name:e.function.name,args:e.function.arguments}))),...X.map((e=>({id:"",name:e.name,args:e.args||{}})))]),W}return{apiBase:t,get apiKey(){return n},setApiKey:function(e){return n="string"==typeof e?e.trim():"",y=null,n},get clientVersion(){return o},get channel(){return s},promptUrl:M,verifyApiKey:async function(){return w("/api/verify-api-key",{api_key:n})},registerDevice:async function(e,t){return w("/api/v1/auth/register-device",{fingerprint:e,app:t&&t.app},void 0,t)},chatCompletion:async function({prompt:e,system:t,messages:n,model:r,mode:o,maxTokens:s,stream:a=!1,onStream:i,onReasoning:c,idleTimeoutMs:l,includeUsage:u,signal:d,extra:m,agentKey:_}={}){const f={messages:C(n,t,e),...s?{max_tokens:s}:{},...m||{}};r?f.model=r:o&&(f.mode=o);const E=D(_?{"X-AEGIS-Agent-Key":_}:void 0);return a&&"function"==typeof i?(u&&(f.stream_options={include_usage:!0}),B("/api/v1/chat/completions",f,E,i,d,{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:Boolean(u)})):$(await w("/api/v1/chat/completions",{...f,stream:!1},E,{signal:d}))},byokChatCompletion:async function({provider:t="openai",model:r,messages:s,prompt:a,system:i,maxTokens:c,effort:l,reasoningEffort:u,tools:d,toolChoice:m,stream:_=!1,onStream:f,signal:E,providerKey:p,baseURL:g}={}){const y=void 0!==p?p:e.providerKey;if("custom"===t&&!g){const e=new Error('the "custom" provider dials the endpoint you name, and this call names none — save the address first: /model-add custom <https-base-url> <api-key> <model-id>, or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const S={provider:t,messages:C(s,i,a),...c?{max_tokens:c}:{},...l?{effort:l}:{},...u?{reasoning_effort:u}:{},...Array.isArray(d)&&d.length?{tools:d}:{},...m?{tool_choice:m}:{},...g?{base_url:g}:{}};r&&(S.model=r);const h={"Content-Type":"application/json","X-AEGIS-Version":o,"X-Provider-Key":y};return n&&(h["X-AEGIS-Key"]=n),_&&"function"==typeof f?B("/api/v1/byok/chat/completions",S,h,f,E):$(await w("/api/v1/byok/chat/completions",{...S,stream:!1},h))},listModels:async function(e){return b("/api/v1/models",null,e)},tokenBankBalance:async function(e){return b("/api/token-bank/balance",null,e)},tokenBankTopup:async function(e){return w("/api/token-bank/topup",{amount_eur:e})},billingCheckout:async function(){return w("/api/billing/checkout",{})},byokStatus:async function(e){return b("/api/user/api-keys",null,e)},byokProviders:async function(e){return b("/api/v1/byok/providers",null,e)},catalog:async function(e,t,n){const r=(e||"models").replace(/^\/+/,""),o=new URLSearchParams;for(const[e,n]of Object.entries(t||{}))null!=n&&""!==n&&o.set(e,String(n));const s=o.toString();return b(`/api/v1/catalog/${r}${s?`?${s}`:""}`,n&&n.etag?{...D(),"If-None-Match":n.etag}:D(),n)},byokSet:async function(e,t){return w("/api/user/api-keys",{provider:e,api_key:t||""})},getMemoryToken:k,memorySearch:async function(e,t){return w("/api/memory/search",{query:e||"",limit:t||5},x(await k()))},memorySave:async function(e){return w("/api/memory/save",{entry:e},x(await k()))},memoryList:async function(e){return w("/api/memory/search",{query:"",limit:e||10},x(await k()))},verifyToken:async function(e){return w("/api/verify-token",{token:e||""},{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`})},memoryActivate:async function(e){return w("/api/memory/activate",{},x(e||await k()))},memoryPull:async function(e){return w("/api/memory/pull",{since:e||0},x(await k()))},memorySaveBatch:async function(e){return w("/api/memory/save",{entries:e||[]},x(await k()))},conversationSyncPush:async function(e){const t=await k();return w("/api/conversations/sync",{session_id:e&&e.session_id,title:e&&e.title||"",messages:e&&e.messages||[],source:e&&e.source||"aegis-desktop"},x(t))},conversationSyncPull:async function(){return w("/api/conversations/sync",{},x(await k()))},importConversation:async function({messages:e,url:t,title:n,source:r}={}){return w("/api/import",{messages:e||[],url:t||"",title:n||"",source:r||"aegiscode-plugin"})},driveToken:async function(){try{return await b("/api/drive/token")}catch(e){if(e&&404===e.status)return{connected:!1,access_token:null,email:null};throw e}},randomUUID:randomUUID}}const SSE_IDLE_TIMEOUT_MS=6e4,BRAIN_IDLE_TIMEOUT_MS=9e5;function idleBudgetFor(e,t){const n=Number(t),r=envIdleMs("AEGIS_SSE_IDLE_TIMEOUT_MS"),o=n>0?n:r>0?r:SSE_IDLE_TIMEOUT_MS;let s="";try{const t=e&&e.headers&&"function"==typeof e.headers.get?e.headers.get.bind(e.headers):null;s=t&&t("X-AEGIS-Brain")||""}catch{s=""}const a=envIdleMs("AEGIS_BRAIN_IDLE_TIMEOUT_MS")||BRAIN_IDLE_TIMEOUT_MS;return s&&String(s).trim()?Math.max(o,a):o}function isVersionGateError(e){return!(!e||"version_mismatch"!==e.code)}const api={createClient:createClient,envVar:envVar,randomUUID:randomUUID,DEFAULT_API_BASE:DEFAULT_API_BASE,CLIENT_VERSION:"3.2.0",isVersionGateError:isVersionGateError,idleBudgetFor:idleBudgetFor,SSE_IDLE_TIMEOUT_MS:SSE_IDLE_TIMEOUT_MS,BRAIN_IDLE_TIMEOUT_MS:BRAIN_IDLE_TIMEOUT_MS};"undefined"!=typeof module&&module.exports&&(module.exports=api),"undefined"!=typeof window&&(window.AegisClient=api);
|
|
4
|
+
"use strict";function envVar(e){if("undefined"==typeof process||!process.env)return"";const t=process.env[e];return t&&!/^\$\{[A-Z_]+\}$/.test(t)?t:""}function envIdleMs(e){const t=envVar(e);if(!t)return 0;const n=Number(t);return Number.isFinite(n)&&n>0?n:0}const DSML_RE_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*>/g,DSML_RE_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/g,DSML_RE_LEADER=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:(?:tool|function)[_▁ ]*calls?|reasoning)[_▁ ]*(?:begin|end)?\s*>/gi,DSML_RE_ANY_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_SKELETON=/<\s*\/?\s*(?:tool_calls|function_calls|invoke|parameter|param|reasoning)\b[^>]{0,120}>/gi,DSML_RE_JSON_CALLS=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|([\s\S]*?)|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_JSON_CALLS_OPEN=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|/gi,DSML_RE_JSON_CALLS_CLOSE=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_ENVELOPE_TOKEN=/|[ \t]?[A-Za-z0-9_▁]*[ \t]?|/g,DSML_RE_DRIFT_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>/gi,DSML_RE_DRIFT_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>/gi,DSML_RE_PARAM_CLOSE=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/gi,DSML_RE_ATTR=/([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,DSML_RE_STRUCT_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_STRUCT_CLOSER=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_WRAPPER_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?!(?:invoke|call|tool_call|parameter|param|arg)\b)[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_TRAILING_LT=/<\s*\/?\s*$/,DSML_RE_OPEN_TOKEN=/^|[ \t]?[A-Za-z0-9_▁]*[ \t]?$/,DSML_HOLD_MAX=4194304;function dsmlAttrs(e){const t={};if(!e)return t;let n;for(DSML_RE_ATTR.lastIndex=0;n=DSML_RE_ATTR.exec(e);)t[n[1].toLowerCase()]=null!=n[2]?n[2]:n[3];return t}function dsmlJson(e){const t=String(null==e?"":e).trim();try{const e=JSON.parse(t);return void 0===e?t:e}catch{return t}}function dsmlArgs(e){const t={};let n;for(DSML_RE_PARAM.lastIndex=0;n=DSML_RE_PARAM.exec(e);){const e=dsmlAttrs(n[1]),r=e.name||e.key||`arg${Object.keys(t).length}`,o="false"===String(e.string||"").toLowerCase()||"true"===String(e.json||"").toLowerCase();t[r]=o?dsmlJson(n[2]):n[2]}return t}function decodeDeepSeekDSML(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n=e;DSML_RE_INVOKE.lastIndex=0;const r=[];let o;for(;o=DSML_RE_INVOKE.exec(n);){const e=dsmlAttrs(o[1]),n=e.name||e.function||e.tool||"";n&&t.push({name:n,args:dsmlArgs(o[2])}),r.push([o.index,o.index+o[0].length])}for(let e=r.length-1;e>=0;e--)n=n.slice(0,r[e][0])+n.slice(r[e][1]);return n=n.replace(DSML_RE_JSON_CALLS,(e,n)=>{const r=dsmlJson(n),o=Array.isArray(r)?r:r&&Array.isArray(r.tool_calls)?r.tool_calls:[];for(const e of o){const n=e&&e.function||e||{},r=n.name||e&&e.name||"";if(!r)continue;let o=null!=n.arguments?n.arguments:e&&e.arguments;"string"==typeof o&&(o=dsmlJson(o)),t.push({name:r,args:o&&"object"==typeof o?o:{}})}return""}),n=n.replace(DSML_RE_LEADER,""),{text:n,calls:t}}function decodeDeepSeekDSMLDrift(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n;for(DSML_RE_DRIFT_INVOKE.lastIndex=0;n=DSML_RE_DRIFT_INVOKE.exec(e);)t.push({at:n.index,attrs:n[1],body:DSML_RE_DRIFT_INVOKE.lastIndex});if(!t.length)return{text:e,calls:[]};const r=[];let o="",s=0;for(let n=0;n<t.length;n++){const a=n+1<t.length?t[n+1].at:e.length,i=e.slice(t[n].body,a),c=dsmlAttrs(t[n].attrs),l=c.name||c.function||c.tool||"",u={},d=[];let m;for(DSML_RE_DRIFT_PARAM.lastIndex=0;m=DSML_RE_DRIFT_PARAM.exec(i);)d.push({at:m.index,attrs:m[1],from:DSML_RE_DRIFT_PARAM.lastIndex});for(let e=0;e<d.length;e++){const t=e+1<d.length?d[e+1].at:i.length,n=i.slice(d[e].from,t).replace(DSML_RE_PARAM_CLOSE,""),r=dsmlAttrs(d[e].attrs),o=r.name||r.key||`arg${Object.keys(u).length}`,s="false"===String(r.string||"").toLowerCase();u[o]=s?dsmlJson(n):n}o+=e.slice(s,t[n].at),s=a,l&&r.push({name:l,args:u})}return o+=e.slice(s),{text:o,calls:r}}function dsmlResidue(e){return e?-1===e.indexOf("|")?e.replace(DSML_RE_SKELETON,""):e.replace(DSML_RE_ANY_TAG,"").replace(DSML_RE_SKELETON,"").replace(DSML_RE_ENVELOPE_TOKEN,""):e}function dsmlUnterminated(e){return!!DSML_RE_OPEN_TOKEN.test(e)||(e.match(DSML_RE_STRUCT_TAG)||[]).length>(e.match(DSML_RE_STRUCT_CLOSER)||[]).length}function dsmlHoldFrom(e){const t=e.search(/<\s*\/?\s*|/);if(-1!==t)return t;const n=e.search(DSML_RE_JSON_CALLS_OPEN);if(-1!==n&&-1===e.slice(n).search(DSML_RE_JSON_CALLS_CLOSE))return n;const r=DSML_RE_TRAILING_LT.exec(e);if(r)return r.index;const o=e.indexOf("|");return-1!==o&&dsmlUnterminated(e.slice(o))?o:-1}function makeDeepSeekEnvelopeStripper(){let e="";const t=[],n=n=>{e+="string"==typeof n?n:"";const r=decodeDeepSeekDSML(e);e=r.text;for(const e of r.calls)t.push(e);e=e.replace(DSML_RE_WRAPPER_TAG,"");const o=dsmlHoldFrom(e);let s;return-1!==o&&e.length-o<=4194304?(s=e.slice(0,o),e=e.slice(o)):(s=e,e=""),dsmlResidue(s)};return n.flush=()=>{const n=decodeDeepSeekDSML(e);e="";for(const e of n.calls)t.push(e);const r=decodeDeepSeekDSMLDrift(n.text);for(const e of r.calls)t.push(e);return dsmlResidue(r.text)},n.calls=()=>t.slice(),n}function randomUUID(){const e="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||null,t=e&&e.crypto;if(t&&"function"==typeof t.randomUUID)try{return t.randomUUID()}catch(e){}if(t&&"function"==typeof t.getRandomValues)try{const e=new Uint8Array(16);t.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128;const n=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}catch(e){}if("function"==typeof require)try{const e=require("crypto");if(e&&"function"==typeof e.randomUUID)return e.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const DEFAULT_API_BASE="https://aegiscloud.org",CLIENT_VERSION="3.2.0",DEFAULT_TIMEOUT_MS=6e4,MAX_BODY_BYTES=8388608,RATE_LIMIT_RETRIES=4,RATE_LIMIT_MAX_WAIT_MS=3e4,RATE_LIMIT_BASE_WAIT_MS=1e3,TRANSIENT_STREAM_ERROR_PATTERN=/connection reset by peer|broken pipe|connection aborted|errno 104|errno 32|errno 54|econnreset|epipe/i,TRANSIENT_STREAM_RETRIES=2,TRANSIENT_STREAM_BASE_WAIT_MS=500,TRANSIENT_SOCKET_CODE_PATTERN=/^(ECONNRESET|EPIPE|ECONNABORTED|UND_ERR_SOCKET|UND_ERR_CLOSED)$/,TRANSIENT_SOCKET_RETRIES=2,SSE_UPSTREAM_TIMEOUT_PATTERN=/request timed out|timed out waiting|upstream timeout/i;function upstreamTimeoutMessage(e,t){const n=Number(t);return`${e} — the upstream provider gave up before answering${null!=t&&Number.isFinite(n)?n>=1e3?` after ${(n/1e3).toFixed(1)}s`:` after ${Math.max(0,Math.round(n))}ms`:""}. That is the provider's own deadline, not this client's stream budget, so raising AEGIS_SSE_IDLE_TIMEOUT_MS cannot help`}function createClient(e={}){const t=(e.apiBase||envVar("AEGIS_API_BASE")||DEFAULT_API_BASE).replace(/\/+$/,"");let n=void 0!==e.apiKey?e.apiKey:envVar("AEGIS_API_KEY");const r=void 0!==e.memoryToken?e.memoryToken:envVar("AEGIS_MEMORY_TOKEN"),o=e.clientVersion||"3.2.0",s="cli"===e.channel?"cli":"desktop";function a(e){return n&&"string"==typeof e?e.split(n).join("[redacted]"):e}const i={ECONNRESET:"connection reset by the backend",ECONNREFUSED:"connection refused — is the backend running?",EPIPE:"connection closed while sending the request",ETIMEDOUT:"connection timed out",ENOTFOUND:"host not found — check the endpoint URL",EAI_AGAIN:"DNS lookup failed temporarily",EHOSTUNREACH:"host unreachable",ENETUNREACH:"network unreachable",CERT_HAS_EXPIRED:"TLS certificate has expired",DEPTH_ZERO_SELF_SIGNED_CERT:"TLS certificate is self-signed",UND_ERR_SOCKET:"the socket closed before the response finished",UND_ERR_CLOSED:"the connection was closed",UND_ERR_CONNECT_TIMEOUT:"timed out connecting to the backend",UND_ERR_HEADERS_TIMEOUT:"the backend accepted the connection but never sent a response",UND_ERR_BODY_TIMEOUT:"the backend stalled mid-response",UND_ERR_ABORTED:"the request was aborted"};function c(e,t){const n=e instanceof Error?e:new Error(String(e)),r=n&&n.name;if("AbortError"===r||"TimeoutError"===r)return e;const o=l(n),s=t||"the backend",a=new Error(o?`Could not reach ${s} (${o}).`:`Could not reach ${s}: ${n.message||"network failure"}.`);return a.status=0,a.code="network",a.networkCode=o||null,a.data=null,a.cause=n,a}function l(e,t=0){if(!e||t>4)return null;const n=e.code||e.cause&&e.cause.code,r=e.cause,o=r?l(r,t+1):null;return i[n]?i[n]:o||(r&&r.message&&r.message!==e.message?r.message:n||null)}async function u(e,n){const r=n&&n.signal,o="function"==typeof AbortController?new AbortController:null;let s=null;o&&(s=setTimeout(()=>o.abort(),S),s&&"function"==typeof s.unref&&s.unref(),r&&(r.aborted?o.abort():"function"==typeof r.addEventListener&&r.addEventListener("abort",()=>{o&&o.abort()},{once:!0})));try{return await fetch(e,{...n||{},signal:o?o.signal:r})}catch(e){if(o&&o.signal.aborted&&(!r||!r.aborted)){const e=new Error(`Timed out after ${S/1e3}s waiting for ${t}.`);throw e.status=0,e.code="timeout",e.data=null,e}throw c(e,t)}finally{s&&clearTimeout(s)}}function d(e,t){const n=e&&e.headers&&"function"==typeof e.headers.get?e.headers.get("retry-after"):null;let r=0;if(n){const e=Number(n);if(Number.isFinite(e)&&e>=0)r=1e3*e;else{const e=Date.parse(n);Number.isFinite(e)&&(r=e-Date.now())}}return r||(r=R*Math.pow(2,t)),Math.min(r,A)}function m(e,t){return new Promise(n=>{const r=setTimeout(n,e);if(r&&"function"==typeof r.unref&&r.unref(),t&&"function"==typeof t.addEventListener)return t.aborted?(clearTimeout(r),void n()):void t.addEventListener("abort",()=>{clearTimeout(r),n()},{once:!0})})}function _(e,t=0){if(!e||t>4)return null;const n=e.code;return"string"==typeof n&&"network"!==n?n:_(e.cause,t+1)}async function f(e,t){let n=0;for(;;)try{return await u(e,t)}catch(e){const r=e&&"network"===e.code?String(_(e)||""):"";if(n>=2||!TRANSIENT_SOCKET_CODE_PATTERN.test(r))throw e;if(t&&t.signal&&t.signal.aborted)throw e;if(await m(500*Math.pow(2,n),t&&t.signal),t&&t.signal&&t.signal.aborted)throw e;n++}}async function E(e,t){let n=await f(e,t);for(let r=0;n&&429===n.status&&r<T;r++){const o=d(n,r);try{n.body&&await n.body.cancel()}catch{}await m(o,t&&t.signal),n=await f(e,t)}for(let r=0;n&&n.status>=500&&n.status<600&&r<2;r++){let o="";try{o=await g(n.clone())}catch{break}if(!TRANSIENT_STREAM_ERROR_PATTERN.test(o))break;await m(500*Math.pow(2,r),t&&t.signal),n=await f(e,t)}return n}function p(e){if(!e)return e;if("AbortError"===e.name||"TimeoutError"===e.name)return e;if("network"===e.code||"timeout"===e.code||"ABORT_ERR"===e.code)return e;if(/^stream stalled - /.test(String(e.message||"")))return e;if(!_(e))return e;const n=c(e,t);return n.bodyPhase=!0,n}async function g(e){if(!e||!e.body||"function"!=typeof e.body.getReader){let t;try{t=await e.text()}catch(e){const t=p(e);throw t&&"network"===t.code&&(t.bytesRead=0),t||e}return t.length>h?t.slice(0,h):t}const n=e.body.getReader(),r=new TextDecoder;let o="",s=0;try{for(;;){let a;try{a=await n.read()}catch(e){const t=p(e);throw t&&"network"===t.code&&(t.bytesRead=s),t||e}const{done:i,value:c}=a;if(i)break;if(s+=c?c.byteLength:0,s>h){const n=new Error(`Response from ${t} exceeded the ${h/1048576}MB cap.`);throw n.status=e.status,n.code="body_too_large",n.data=null,n}o+=r.decode(c,{stream:!0})}return o+=r.decode(),o}finally{try{await n.cancel()}catch{}}}let y=null;const S=Number(e.timeoutMs)>0?Number(e.timeoutMs):Number(envVar("AEGIS_HTTP_TIMEOUT_MS"))>0?Number(envVar("AEGIS_HTTP_TIMEOUT_MS")):6e4,h=Number(e.maxBodyBytes)>0?Number(e.maxBodyBytes):8388608,T=Number(e.rateLimitRetries)>=0?Number(e.rateLimitRetries):4,R=Number(e.rateLimitBaseWaitMs)>=0?Number(e.rateLimitBaseWaitMs):1e3,A=Number(e.rateLimitMaxWaitMs)>0?Number(e.rateLimitMaxWaitMs):3e4;function M(e,n){try{const r=new URL(`/go/${String(e||"upgrade").replace(/^\/+|\/+$/g,"")}`,t);r.searchParams.set("s",s);const o=String(n||"").trim().toLowerCase();return/^[a-z0-9][a-z0-9_-]{0,63}$/.test(o)&&r.searchParams.set("c",o),r.toString()}catch(e){return""}}function D(e){const t={"Content-Type":"application/json","X-AEGIS-Version":o,...e};return n&&(t["X-API-Key"]=n,t.Authorization=`Bearer ${n}`),t}async function L(e,n){return O(await E(`${t}${e}`,n))}async function I(e,t){let n=0;for(;;)try{return await L(e,t)}catch(e){if(!e||"network"!==e.code||!0!==e.bodyPhase||0!==e.bytesRead||n>=2)throw e;if(t&&t.signal&&t.signal.aborted)throw e;if(await m(500*Math.pow(2,n),t&&t.signal),t&&t.signal&&t.signal.aborted)throw e;n++}}async function w(e,t,n,r){return I(e,{method:"POST",headers:n||D(),body:JSON.stringify(t||{}),signal:r&&r.signal})}async function b(e,t,n){return I(e,{method:"GET",headers:t||D(),signal:n&&n.signal})}function N(e,t){const n=e||{},r=n.latest_cli||"",s=n.latest_desktop||"",a=r||s||n.required||"",i=new Error(a?`This client (v${o}) is out of date — upgrade to v${a}.`:`This client (v${o}) is out of date.`);return i.status=t,i.code="version_mismatch",i.data=n,i.upgrade={required:n.required||"",latestCli:r,latestDesktop:s,url:M("upgrade","version_gate")||n.update_url||""},i}async function O(e){const t=await g(e);let n;try{n=t?JSON.parse(t):{}}catch{n={raw:a(t)}}if(!e.ok){if(function(e,t){return 426===e||t&&"version_mismatch"===t.code}(e.status,n))throw N(n,e.status);const t=n&&(n.error?.message||n.error||n.message)||`HTTP ${e.status}`,r=new Error(a("string"==typeof t?t:JSON.stringify(t)));throw e.status>=500&&e.status<600&&SSE_UPSTREAM_TIMEOUT_PATTERN.test(r.message)?(r.serverStatus=e.status,r.status=0,r.code="timeout",r.message=upstreamTimeoutMessage(r.message)):r.status=e.status,r.data=n,r}if(n&&"version_mismatch"===n.code)throw N(n,e.status);return n}function v(e){if(!e)return"";const t=e.error;return"string"==typeof t?t:t&&"string"==typeof t.message?t.message:t&&"string"==typeof t.error?t.error:"string"==typeof e.message?e.message:"string"==typeof e.error_message?e.error_message:""}async function k(){if(r)return r;if(y)return y;const e=await w("/api/verify-api-key",{api_key:n});if(!e||!e.memory_token){const e=M("upgrade","memory_quota");throw new Error("This AEGIS account has no memory token. "+(e?`Enable cloud memory at ${e}`:"Enable cloud memory in your AEGIS account settings."))}return y=e.memory_token,y}function x(e){return{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`}}function U(e){if(null==e)return"";if("string"==typeof e)return e;if(!Array.isArray(e))return String(e);let t="";for(let n=0;n<e.length;n+=1){const r=e[n];r&&"object"==typeof r&&("string"==typeof r.text?t+=(t?"\n":"")+r.text:"image_url"===r.type&&(t+=(t?"\n":"")+"[image]"))}return t}function C(e,t,n){const r=Array.isArray(e)?e.filter(Boolean):[],o=[];if(t&&!r.some(e=>e&&"system"===e.role)&&o.push({role:"system",content:t}),o.push(...r),null!=n&&("string"==typeof n?""!==n:Array.isArray(n)&&n.length>0)){const e=o[o.length-1];(Array.isArray(n)&&e&&"user"===e.role?U(e.content)===U(n):e&&"user"===e.role&&e.content===n)||o.push({role:"user",content:n})}return o}function P(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;return"string"==typeof n?n:""}function $(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;if("string"!=typeof n||-1===n.indexOf("|"))return e;const r=decodeDeepSeekDSML(n),o=decodeDeepSeekDSMLDrift(r.text);t.message.content=dsmlResidue(o.text);const s=[...r.calls,...o.calls];return s.length&&(e.toolCalls=[...Array.isArray(e.toolCalls)?e.toolCalls:[],...s.map(e=>({id:"",name:e.name,args:e.args||{}}))]),e}async function B(e,n,r,o,s,i){const{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:u,_transientStreamAttempt:d=0}=i||{},_=n=>E(`${t}${e}`,{method:"POST",headers:r,body:JSON.stringify({...n,stream:!0}),signal:s});let f;try{f=await _(n)}catch(e){throw e}if(!f.ok&&426===f.status){let e={};try{const t=await g(f);e=t?JSON.parse(t):{}}catch{e={}}throw N(e,f.status)}if(!f.ok&&u&&n.stream_options){try{f.body&&await f.body.cancel()}catch{}const t={...n};delete t.stream_options,n=t;try{f=await _(n)}catch(e){throw e}}if(!f.ok){const t={...n};delete t.stream_options;const a=$(await w(e,{...t,stream:!1},r,{signal:s})),i=P(a);return i&&o({delta:i}),a}if(!(f.headers.get("content-type")||"").includes("text/event-stream")){const e=$(await O(f)),t=P(e);return t?o({delta:t}):function(e,t){if(e&&"version_mismatch"===e.code)throw N(e,t||426);const n=a(v(e));if(!n)return;const r=new Error(n);throw r.status=t||500,r.data=e,r}(e,f.status),e}const y=f.body.getReader(),S=new TextDecoder;let h="",T="",R="",A=n.model,M=null,D="";const L=new Map;let I=null,b="";const k=makeDeepSeekEnvelopeStripper(),x=idleBudgetFor(f,l);let U=Date.now();const C=U;let K=0;async function G(){let e,t=null;const n=Math.max(0,x-(Date.now()-U)),r=new Promise((t,r)=>{e=setTimeout(()=>{r(new Error(K>0?`stream stalled - only keep-alives for ${x/1e3}s`:`stream stalled - no data for ${x/1e3}s`))},n)}),o=s&&"function"==typeof s.addEventListener?new Promise((e,n)=>{t=()=>{const e=new Error("The turn was stopped.");e.name="AbortError",e.code="ABORT_ERR",n(e)},s.aborted?t():s.addEventListener("abort",t,{once:!0})}):null;try{return await(o?Promise.race([y.read(),r,o]):Promise.race([y.read(),r]))}finally{clearTimeout(e),s&&t&&"function"==typeof s.removeEventListener&&s.removeEventListener("abort",t)}}for(;;){let t,l;try{({done:t,value:l}=await G())}catch(t){y.cancel().catch(()=>{});const a=p(t);if(a&&"network"===a.code&&(a.bytesRead=b?1:0,0===a.bytesRead&&d<2&&(!s||!s.aborted))){if(await m(500*Math.pow(2,d),s),s&&s.aborted)throw a;return B(e,n,r,o,s,{...i,_transientStreamAttempt:d+1})}throw a||t}if(t)break;h+=S.decode(l,{stream:!0});const u=h.split("\n");h=u.pop();for(const e of u){const t=e.trim();if(!t.startsWith("data:")){t.startsWith(":")&&K++;continue}U=Date.now();const n=t.slice(5).trim();if(!n||"[DONE]"===n)continue;let r;try{r=JSON.parse(n)}catch{continue}if(r.error){if(!D){const e=r.error;D="string"==typeof e?e:v({error:e})||"stream error",D=a(D)}continue}r.model&&(A=r.model),r.usage&&(M=r.usage);const s=r.choices&&r.choices[0];s&&s.finish_reason&&(I=s.finish_reason);const i=(e,t,n,r)=>{if("string"==typeof e&&e)return r(e),n+e;if("string"==typeof t&&t){if(!n)return r(t),t;if(t.startsWith(n)){const e=t.slice(n.length);return e&&r(e),t}return n}return n};R=i(s&&s.delta&&s.delta.reasoning_content,s&&s.message&&s.message.reasoning_content,R,e=>{"function"==typeof c?c(e):o({reasoning:e})}),T=i(s&&s.delta&&s.delta.content,s&&s.message&&s.message.content,T,e=>{const t=k(e);t&&(b+=t,o({delta:t}))});const l=s&&s.delta&&s.delta.tool_calls||s&&s.message&&s.message.tool_calls;if(Array.isArray(l))for(const e of l){const t=null==e.index?0:e.index,n=L.get(t)||{id:"",type:"function",function:{name:"",arguments:""}};e.id&&(n.id=e.id),e.type&&(n.type=e.type);const r=e.function||{};r.name&&(n.function.name=r.name),"string"==typeof r.arguments&&(n.function.arguments+=r.arguments),L.set(t,n)}}}if(!T&&D){if(d<2&&TRANSIENT_STREAM_ERROR_PATTERN.test(D))return await m(500*Math.pow(2,d),s),B(e,n,r,o,s,{...i,_transientStreamAttempt:d+1});const t=SSE_UPSTREAM_TIMEOUT_PATTERN.test(D),a=new Error(t?upstreamTimeoutMessage(D,Date.now()-C):D);throw a.status=t?0:f.status,t&&(a.code="timeout"),a}const V=k.flush();V&&(b+=V,o({delta:V}));const F=[...L.entries()].sort((e,t)=>e[0]-t[0]).map(([e,t])=>({...t,id:t.id||`call_${e}`})),J={content:b};R&&(J.reasoning_content=R),F.length&&(J.tool_calls=F);const W={model:A,choices:[{message:J,...I?{finish_reason:I}:{}}]};M&&(W.usage=M);const z=k.calls();return(F.length||z.length)&&(W.toolCalls=[...F.map(e=>({id:e.id,name:e.function.name,args:e.function.arguments})),...z.map(e=>({id:"",name:e.name,args:e.args||{}}))]),W}return{apiBase:t,get apiKey(){return n},setApiKey:function(e){return n="string"==typeof e?e.trim():"",y=null,n},get clientVersion(){return o},get channel(){return s},promptUrl:M,verifyApiKey:async function(){return w("/api/verify-api-key",{api_key:n})},registerDevice:async function(e,t){return w("/api/v1/auth/register-device",{fingerprint:e,app:t&&t.app},void 0,t)},chatCompletion:async function({prompt:e,system:t,messages:n,model:r,mode:o,maxTokens:s,stream:a=!1,onStream:i,onReasoning:c,idleTimeoutMs:l,includeUsage:u,signal:d,extra:m,agentKey:_}={}){const f={messages:C(n,t,e),...s?{max_tokens:s}:{},...m||{}};r?f.model=r:o&&(f.mode=o);const E=D(_?{"X-AEGIS-Agent-Key":_}:void 0);return a&&"function"==typeof i?(u&&(f.stream_options={include_usage:!0}),B("/api/v1/chat/completions",f,E,i,d,{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:Boolean(u)})):$(await w("/api/v1/chat/completions",{...f,stream:!1},E,{signal:d}))},byokChatCompletion:async function({provider:t="openai",model:r,messages:s,prompt:a,system:i,maxTokens:c,effort:l,reasoningEffort:u,tools:d,toolChoice:m,stream:_=!1,onStream:f,signal:E,providerKey:p,baseURL:g}={}){const y=void 0!==p?p:e.providerKey;if("custom"===t&&!g){const e=new Error('the "custom" provider dials the endpoint you name, and this call names none — save the address first: /model-add custom <https-base-url> <api-key> <model-id>, or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const S={provider:t,messages:C(s,i,a),...c?{max_tokens:c}:{},...l?{effort:l}:{},...u?{reasoning_effort:u}:{},...Array.isArray(d)&&d.length?{tools:d}:{},...m?{tool_choice:m}:{},...g?{base_url:g}:{}};r&&(S.model=r);const h={"Content-Type":"application/json","X-AEGIS-Version":o,"X-Provider-Key":y};return n&&(h["X-AEGIS-Key"]=n),_&&"function"==typeof f?B("/api/v1/byok/chat/completions",S,h,f,E):$(await w("/api/v1/byok/chat/completions",{...S,stream:!1},h))},listModels:async function(e){return b("/api/v1/models",null,e)},tokenBankBalance:async function(e){return b("/api/token-bank/balance",null,e)},tokenBankTopup:async function(e){return w("/api/token-bank/topup",{amount_eur:e})},billingCheckout:async function(){return w("/api/billing/checkout",{})},byokStatus:async function(e){return b("/api/user/api-keys",null,e)},byokProviders:async function(e){return b("/api/v1/byok/providers",null,e)},catalog:async function(e,t,n){const r=(e||"models").replace(/^\/+/,""),o=new URLSearchParams;for(const[e,n]of Object.entries(t||{}))null!=n&&""!==n&&o.set(e,String(n));const s=o.toString();return b(`/api/v1/catalog/${r}${s?`?${s}`:""}`,n&&n.etag?{...D(),"If-None-Match":n.etag}:D(),n)},byokSet:async function(e,t){return w("/api/user/api-keys",{provider:e,api_key:t||""})},getMemoryToken:k,memorySearch:async function(e,t){return w("/api/memory/search",{query:e||"",limit:t||5},x(await k()))},memorySave:async function(e){return w("/api/memory/save",{entry:e},x(await k()))},memoryList:async function(e){return w("/api/memory/search",{query:"",limit:e||10},x(await k()))},verifyToken:async function(e){return w("/api/verify-token",{token:e||""},{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`})},memoryActivate:async function(e){return w("/api/memory/activate",{},x(e||await k()))},memoryPull:async function(e){return w("/api/memory/pull",{since:e||0},x(await k()))},memorySaveBatch:async function(e){return w("/api/memory/save",{entries:e||[]},x(await k()))},conversationSyncPush:async function(e){const t=await k();return w("/api/conversations/sync",{session_id:e&&e.session_id,title:e&&e.title||"",messages:e&&e.messages||[],source:e&&e.source||"aegis-desktop"},x(t))},conversationSyncPull:async function(){return w("/api/conversations/sync",{},x(await k()))},importConversation:async function({messages:e,url:t,title:n,source:r}={}){return w("/api/import",{messages:e||[],url:t||"",title:n||"",source:r||"aegiscode-plugin"})},driveToken:async function(){try{return await b("/api/drive/token")}catch(e){if(e&&404===e.status)return{connected:!1,access_token:null,email:null};throw e}},randomUUID:randomUUID}}const SSE_IDLE_TIMEOUT_MS=6e4,BRAIN_IDLE_TIMEOUT_MS=9e5;function idleBudgetFor(e,t){const n=Number(t),r=envIdleMs("AEGIS_SSE_IDLE_TIMEOUT_MS"),o=n>0?n:r>0?r:SSE_IDLE_TIMEOUT_MS;let s="";try{const t=e&&e.headers&&"function"==typeof e.headers.get?e.headers.get.bind(e.headers):null;s=t&&t("X-AEGIS-Brain")||""}catch{s=""}const a=envIdleMs("AEGIS_BRAIN_IDLE_TIMEOUT_MS")||BRAIN_IDLE_TIMEOUT_MS;return s&&String(s).trim()?Math.max(o,a):o}function isVersionGateError(e){return!(!e||"version_mismatch"!==e.code)}const api={createClient:createClient,envVar:envVar,randomUUID:randomUUID,DEFAULT_API_BASE:DEFAULT_API_BASE,CLIENT_VERSION:"3.2.0",isVersionGateError:isVersionGateError,idleBudgetFor:idleBudgetFor,SSE_IDLE_TIMEOUT_MS:SSE_IDLE_TIMEOUT_MS,BRAIN_IDLE_TIMEOUT_MS:BRAIN_IDLE_TIMEOUT_MS};"undefined"!=typeof module&&module.exports&&(module.exports=api),"undefined"!=typeof window&&(window.AegisClient=api);
|
|
@@ -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 crypto=require("node:crypto"),fs=require("node:fs"),path=require("node:path"),fp=require("./fingerprint.js"),authorship=require("./authorship-key.js"),envFile=require("./env-file.js"),DEFAULT_HISTORY=()=>path.join(authorship.dataDir(),"history.jsonl"),DIR_KEYS=["cwd","dir","workspace","root"],DEMAND_KEYS=["demand","prompt","task","text","content"],OUTCOME_KEYS=["outcome","status","result"],SESSION_KEYS=["session","sessionId","session_id"],TIME_KEYS=["at","ts","time","createdAt"],REPLY_KEYS=["reply","answer","response"],MODEL_KEYS=["model","aiModel","modelId"],sha256hex=e=>crypto.createHash("sha256").update(String(e||""),"utf8").digest("hex"),AI_SECRET_ENV="AEGIS_AI_SECRET";function firstKey(e,t){for(const r of t){const t=e[r];if(null==t)continue;const o="string"==typeof t?t:String(t);if(""!==o.trim())return o}return null}function readHistory(e){if(!fs.existsSync(e))throw new Error(`attest: no session log at ${e}`);const t=[];let r=0;for(const o of fs.readFileSync(e,"utf8").split("\n")){const e=o.trim();if(e)try{const o=JSON.parse(e);o&&"object"==typeof o?t.push(o):r+=1}catch{r+=1}}return{entries:t,skipped:r}}function lastSessionId(e){for(let t=e.length-1;t>=0;t-=1){const r=firstKey(e[t],SESSION_KEYS);if(r)return r}return null}function selectTurns(e,{session:t=null,turns:r=null}={}){let o=e;if(t){const r=String(t);o=e.filter(
|
|
3
|
+
"use strict";const crypto=require("node:crypto"),fs=require("node:fs"),path=require("node:path"),fp=require("./fingerprint.js"),authorship=require("./authorship-key.js"),envFile=require("./env-file.js"),DEFAULT_HISTORY=()=>path.join(authorship.dataDir(),"history.jsonl"),DIR_KEYS=["cwd","dir","workspace","root"],DEMAND_KEYS=["demand","prompt","task","text","content"],OUTCOME_KEYS=["outcome","status","result"],SESSION_KEYS=["session","sessionId","session_id"],TIME_KEYS=["at","ts","time","createdAt"],REPLY_KEYS=["reply","answer","response"],MODEL_KEYS=["model","aiModel","modelId"],sha256hex=e=>crypto.createHash("sha256").update(String(e||""),"utf8").digest("hex"),AI_SECRET_ENV="AEGIS_AI_SECRET";function firstKey(e,t){for(const r of t){const t=e[r];if(null==t)continue;const o="string"==typeof t?t:String(t);if(""!==o.trim())return o}return null}function readHistory(e){if(!fs.existsSync(e))throw new Error(`attest: no session log at ${e}`);const t=[];let r=0;for(const o of fs.readFileSync(e,"utf8").split("\n")){const e=o.trim();if(e)try{const o=JSON.parse(e);o&&"object"==typeof o?t.push(o):r+=1}catch{r+=1}}return{entries:t,skipped:r}}function lastSessionId(e){for(let t=e.length-1;t>=0;t-=1){const r=firstKey(e[t],SESSION_KEYS);if(r)return r}return null}function selectTurns(e,{session:t=null,turns:r=null}={}){let o=e;if(t){const r=String(t);o=e.filter(e=>firstKey(e,SESSION_KEYS)===r)}return r&&Number.isFinite(Number(r))&&Number(r)>0&&(o=o.slice(-Math.floor(Number(r)))),o}function observationsFromTurns(e){const t=[];for(const r of Array.isArray(e)?e:[]){if(!r||"object"!=typeof r)continue;const e=firstKey(r,DIR_KEYS),o=firstKey(r,DEMAND_KEYS);t.push({tool:o||e?"turn":null,target:`${e?path.basename(e):"?"}#${sha256hex(o||"").slice(0,8)}`,outcome:firstKey(r,OUTCOME_KEYS)})}return t}function aiObservationsFromTurns(e){const t=[];for(const r of Array.isArray(e)?e:[]){if(!r||"object"!=typeof r)continue;const e=firstKey(r,REPLY_KEYS),o=firstKey(r,OUTCOME_KEYS),s=firstKey(r,MODEL_KEYS),n=Boolean(e||o||s);t.push({tool:n?"reply":null,target:n?`reply#${sha256hex(e||"").slice(0,8)}`:null,outcome:o||null,model:s})}return t}function resolveAiSecret(e={}){const t=e.argv||[],r=e.env||{},o=firstFlag(t,["--ai-secret","--ai-secret-file"]);if(o){const e=fs.readFileSync(o,"utf8").trim();if(!e)throw new Error(`attest: ${o} is empty — an empty AI credential is not one`);return{secret:e,source:o}}const s=r[AI_SECRET_ENV]&&String(r[AI_SECRET_ENV]).trim();if(s)return{secret:s,source:AI_SECRET_ENV};const n=String(e.aiModel||e.model||"").trim();if(n&&"function"==typeof envFile.providerForModelId){const t=envFile.providerForModelId(n,e.cls);if(t){const e=envFile.providerKeyFromEnv(t,r);if(e&&e.key)return{secret:e.key,source:e.env};const o=providerKeyFromFile(t,r);if(o)return o}}return{secret:null,source:"none"}}function providerKeyFromFile(e,t){const r="function"==typeof envFile.envVarFor?envFile.envVarFor(e):"";if(!r)return null;const o=t&&(t.AEGIS_HOME||t.AEGISCODE_HOME)?String(t.AEGIS_HOME||t.AEGISCODE_HOME):void 0;let s;try{s=envFile.parseEnvText(fs.readFileSync(envFile.envFileFor(o),"utf8"))}catch{return null}const n=s&&"string"==typeof s[r]?s[r].trim():"";return n&&("function"!=typeof envFile.credentialLooksUsable||envFile.credentialLooksUsable(n))?{secret:n,source:r}:null}function firstFlag(e,t){for(const r of t){const t=e.indexOf(r);if(-1!==t&&void 0!==e[t+1]&&!String(e[t+1]).startsWith("--"))return e[t+1]}return null}const SKIP_DIRS=new Set([".git","node_modules","dist","build","out","vendor",".venv","venv","__pycache__",".next",".cache","release","coverage"]),MAX_FILE_BYTES=2097152,MAX_FILES=4096;function collectCode({roots:e=[],files:t=[],skip:r=[]}={}){const o=new Set(r),s=[],n=(e,t)=>{const r=fs.statSync(t);if(!r.isFile())return;if(r.size>2097152)throw new Error(`attest: ${t} is ${r.size} bytes — too large to attest (max 2097152)`);if(s.length>=4096)throw new Error("attest: more than 4096 files — refusing to attest a partial walk");const o=fp.normaliseCodePath(e);o&&s.push({path:o,content:fs.readFileSync(t,"utf8")})};for(const t of e){const e=path.resolve(t),r=(e,t)=>{for(const s of fs.readdirSync(e).sort()){const i=path.join(e,s),c=t?`${t}/${s}`:s,l=fs.lstatSync(i);if(!l.isSymbolicLink())if(l.isDirectory()){if(SKIP_DIRS.has(s)||o.has(s))continue;r(i,c)}else n(c,i)}};r(e,"")}for(const e of t){const t=path.resolve(e);n(path.basename(t),t)}return s}function mintSession(e={}){const t=e.key||authorship.resolveKey(e);if(!t.secret)throw new Error(`attest: no authorship key — run \`aegiscode fingerprint keygen\`, set ${authorship.SECRET_ENV}, or pass --secret <file>`);const r=e.history||DEFAULT_HISTORY(),{entries:o,skipped:s}=readHistory(r),n=selectTurns(o,{session:e.session||lastSessionId(o),turns:e.turns}),i=observationsFromTurns(n),c=e.code||[],l=e.aiObservations||aiObservationsFromTurns(n),a=void 0!==e.aiModel&&null!==e.aiModel?e.aiModel:l.map(e=>e.model).filter(Boolean).pop()||"",u=void 0===e.aiSecret?resolveAiSecret({...e,aiModel:a}):{secret:e.aiSecret,source:e.aiSecret?"caller":"none"},S=fp.mint({secret:t.secret,label:e.label,account:e.account,model:e.model,tools:e.tools,observations:i,code:c,codeDirty:void 0===e.codeDirty?null:e.codeDirty,aiSecret:u.secret,aiModel:a,aiObservations:l,createdAt:e.createdAt||void 0});return{record:S,keySource:t.source,public:t.public,samples:S.behaviourSamples,observations:i.length,aiKeySource:u.source,aiSamples:S.aiSamples,skippedLines:s}}module.exports={DEFAULT_HISTORY:DEFAULT_HISTORY,DIR_KEYS:DIR_KEYS,DEMAND_KEYS:DEMAND_KEYS,OUTCOME_KEYS:OUTCOME_KEYS,SESSION_KEYS:SESSION_KEYS,REPLY_KEYS:REPLY_KEYS,MODEL_KEYS:MODEL_KEYS,AI_SECRET_ENV:AI_SECRET_ENV,TIME_KEYS:TIME_KEYS,SKIP_DIRS:SKIP_DIRS,MAX_FILE_BYTES:2097152,MAX_FILES:4096,firstKey:firstKey,readHistory:readHistory,lastSessionId:lastSessionId,selectTurns:selectTurns,observationsFromTurns:observationsFromTurns,aiObservationsFromTurns:aiObservationsFromTurns,resolveAiSecret:resolveAiSecret,collectCode:collectCode,mintSession:mintSession};
|
|
@@ -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 crypto=require("node:crypto"),fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),fp=require("./fingerprint.js"),KEY_FILE_MODE=384,DIR_MODE=448,GROUP_OTHER_BITS=63,KEY_BYTES=32,SECRET_ENV="AEGIS_FINGERPRINT_SECRET",HOME_ENV="AEGIS_HOME",KEY_FILENAME="authorship.key",isWin="win32"===process.platform;function dataDir(e=process.env){const r=e[HOME_ENV];return r&&String(r).trim()?path.resolve(String(r).trim()):path.join(os.homedir(),".aegiscode")}function defaultKeyPath(e=process.env){return path.join(dataDir(e),"keys",KEY_FILENAME)}function modeOf(e){return 511&fs.statSync(e).mode}function modeString(e){return e.toString(8).padStart(3,"0")}function assertPrivate(e){if(isWin)return;const r=modeOf(e);if(r
|
|
3
|
+
"use strict";const crypto=require("node:crypto"),fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),fp=require("./fingerprint.js"),KEY_FILE_MODE=384,DIR_MODE=448,GROUP_OTHER_BITS=63,KEY_BYTES=32,SECRET_ENV="AEGIS_FINGERPRINT_SECRET",HOME_ENV="AEGIS_HOME",KEY_FILENAME="authorship.key",isWin="win32"===process.platform;function dataDir(e=process.env){const r=e[HOME_ENV];return r&&String(r).trim()?path.resolve(String(r).trim()):path.join(os.homedir(),".aegiscode")}function defaultKeyPath(e=process.env){return path.join(dataDir(e),"keys",KEY_FILENAME)}function modeOf(e){return 511&fs.statSync(e).mode}function modeString(e){return e.toString(8).padStart(3,"0")}function assertPrivate(e){if(isWin)return;const r=modeOf(e);if(63&r)throw new Error(`authorship-key: ${e} is mode ${modeString(r)} — a secret file must not be group/other readable. chmod 600 ${e}`)}function readSecretFile(e){const r=fs.readFileSync(e,"utf8").replace(/\r?\n$/,"");if(!r.trim())throw new Error(`authorship-key: ${e} is empty`);if(/\s/.test(r.trim()))throw new Error(`authorship-key: ${e} holds more than one line — not a key file`);return r.trim()}function flag(e,r,t=null){const i="--secret"===r?["--secret","--secret-file"]:[r];for(const r of i){const t=e.indexOf(r);if(-1!==t&&void 0!==e[t+1]&&!e[t+1].startsWith("--"))return e[t+1]}return t}function hasFlag(e,r){return("--secret"===r?["--secret","--secret-file"]:[r]).some(r=>e.includes(r))}function resolveKey(e={}){const r=e.argv||[],t=e.env||process.env,i=flag(r,"--secret");if(i){if(!fs.existsSync(i))throw new Error(`authorship-key: no such secret file: ${i}`);return assertPrivate(i),{secret:readSecretFile(i),source:i,public:!1,path:i}}if(hasFlag(r,"--public")){const e=flag(r,"--covenant");if(!e)throw new Error("authorship-key: --public requires --covenant <file> — the public key IS the covenant document's hash, so it cannot be assumed");if(!fs.existsSync(e))throw new Error(`authorship-key: no such covenant file: ${e}`);return{secret:crypto.createHash("sha256").update(fs.readFileSync(e)).digest("hex"),source:`covenant (public): ${e}`,public:!0,path:null}}const o=t[SECRET_ENV];if(o&&String(o).trim())return{secret:String(o).trim(),source:SECRET_ENV,public:!1,path:null};const n=defaultKeyPath(t);return fs.existsSync(n)?(assertPrivate(n),{secret:readSecretFile(n),source:n,public:!1,path:n}):{secret:null,source:null,public:!1,path:null}}function writeSecret(e,r){try{fs.mkdirSync(path.dirname(e),{recursive:!0,mode:448}),fs.writeFileSync(e,r+"\n",{mode:384})}catch(r){const t=r&&r.code,i=path.dirname(e);if("EACCES"===t||"EPERM"===t)throw new Error(`authorship-key: cannot write ${e} — ${i} is not writable by this user (${t}). Fix it with: chmod u+rwx ${i}`);if("EROFS"===t)throw new Error(`authorship-key: cannot write ${e} — ${i} is on a read-only filesystem (EROFS). Point --out (or $AEGIS_HOME) at a writable location.`);if("ENOSPC"===t)throw new Error(`authorship-key: cannot write ${e} — the disk is full (ENOSPC).`);throw r}}function keygen(e={}){const r=e.argv||[],t=e.env||process.env,i=path.resolve(flag(r,"--out")||defaultKeyPath(t)),o=hasFlag(r,"--force")||!0===e.force,n=fs.existsSync(i);if(n&&!o)throw new Error(`authorship-key: ${i} already exists — pass --force to replace it`);n&&!isWin&&assertPrivate(i);const s=crypto.randomBytes(32).toString("base64url");if(writeSecret(i,s),fs.chmodSync(i,384),!isWin){const e=modeOf(i);if(384!==e)throw new Error(`authorship-key: ${i} landed mode ${modeString(e)}, expected 600 — refusing to report success for a key another user may be able to read`)}if(readSecretFile(i)!==s)throw new Error(`authorship-key: ${i} does not read back as written`);return{out:i,created:!n,replaced:n,keyFingerprint:fp.keyFingerprint(s),bytes:32,secretPrinted:!1,mode:isWin?"n/a":modeString(modeOf(i))}}function git(e,r){try{return execFileSync("git",e,{cwd:r,encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return null}}function insideGitTree(e){return"true\n"===git(["rev-parse","--is-inside-work-tree"],e)}function backup(e={}){const r=e.argv||[],t=e.env||process.env,i=flag(r,"--to");if(!i)throw new Error("authorship-key: backup requires --to DIR");const o=flag(r,"--secret")||defaultKeyPath(t);if(!fs.existsSync(o))throw new Error(`authorship-key: no key at ${o} — run keygen first`);assertPrivate(o);const n=path.resolve(i),s=flag(r,"--name")||path.basename(o),a=path.join(n,s);if(insideGitTree(n)&&!hasFlag(r,"--allow-git")&&!e.allowGit&&null===git(["check-ignore","-q",a],n))throw new Error(`authorship-key: ${a} is inside a git working tree and is not gitignored — a committed key cannot be un-published. Add it to .gitignore, choose another --to, or pass --allow-git if you know the destination is protected`);const c=readSecretFile(o);if(writeSecret(a,c),fs.chmodSync(a,384),!isWin&&384!==modeOf(a))throw new Error(`authorship-key: ${a} landed mode ${modeString(modeOf(a))}, expected 600`);if(readSecretFile(a)!==c)throw new Error(`authorship-key: ${a} does not read back as the same key`);return{from:o,to:a,keyFingerprint:fp.keyFingerprint(c),matchesSource:!0,secretPrinted:!1}}module.exports={KEY_FILE_MODE:384,DIR_MODE:448,GROUP_OTHER_BITS:63,KEY_BYTES:32,SECRET_ENV:SECRET_ENV,HOME_ENV:HOME_ENV,KEY_FILENAME:KEY_FILENAME,dataDir:dataDir,defaultKeyPath:defaultKeyPath,assertPrivate:assertPrivate,readSecretFile:readSecretFile,flag:flag,hasFlag:hasFlag,resolveKey:resolveKey,keygen:keygen,backup:backup,modeString:modeString};
|
|
@@ -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{machineFingerprint:machineFingerprint}=require("./device-fingerprint.js"),DEVICE_REGISTER_TIMEOUT_MS=8e3,DEVICE_REGISTER_RETRY_DELAYS_MS=[1e3,3e3];function isTransientRegisterError(e){const r=e&&e.status;return!r||408===r||r>=500}function provisionFailureText(e){const r=e&&e.error;return r?429===r.status?"too many sign-ups from this network — try again later":r.status>=500?`aegiscloud.org failed to register this device: ${r.message}`:isTransientRegisterError(r)?"could not reach aegiscloud.org":`the server refused the request (HTTP ${r.status})`:"the server returned no account key"}function trialOutcomeNote(e){return e&&e.reusedAccount?". This machine was already registered, so it got its existing account back — the welcome trial is granted once per machine, ever, and was not granted again. A fresh trial needs a new sign-up, not a new key.":e&&!1===e.trialGranted?". The welcome trial was withheld this hour (too many new devices from this network)":""}async function autoProvisionApiKey(e,r,t={}){if(Array.isArray(t))throw new TypeError("autoProvisionApiKey takes { app, retryDelaysMs }; a bare retry array is no longer accepted");if(e.apiKey)return{ok:!0,key:e.apiKey};const{app:i,retryDelaysMs:n=DEVICE_REGISTER_RETRY_DELAYS_MS}=t;let o=null;for(let t=0;t<=n.length;t++){t>0&&await new Promise(
|
|
3
|
+
"use strict";const{machineFingerprint:machineFingerprint}=require("./device-fingerprint.js"),DEVICE_REGISTER_TIMEOUT_MS=8e3,DEVICE_REGISTER_RETRY_DELAYS_MS=[1e3,3e3];function isTransientRegisterError(e){const r=e&&e.status;return!r||408===r||r>=500}function provisionFailureText(e){const r=e&&e.error;return r?429===r.status?"too many sign-ups from this network — try again later":r.status>=500?`aegiscloud.org failed to register this device: ${r.message}`:isTransientRegisterError(r)?"could not reach aegiscloud.org":`the server refused the request (HTTP ${r.status})`:"the server returned no account key"}function trialOutcomeNote(e){return e&&e.reusedAccount?". This machine was already registered, so it got its existing account back — the welcome trial is granted once per machine, ever, and was not granted again. A fresh trial needs a new sign-up, not a new key.":e&&!1===e.trialGranted?". The welcome trial was withheld this hour (too many new devices from this network)":""}async function autoProvisionApiKey(e,r,t={}){if(Array.isArray(t))throw new TypeError("autoProvisionApiKey takes { app, retryDelaysMs }; a bare retry array is no longer accepted");if(e.apiKey)return{ok:!0,key:e.apiKey};const{app:i,retryDelaysMs:n=DEVICE_REGISTER_RETRY_DELAYS_MS}=t;let o=null;for(let t=0;t<=n.length;t++){t>0&&await new Promise(e=>setTimeout(e,n[t-1]));const a=new AbortController,s=setTimeout(()=>a.abort(),8e3);try{const t=await e.registerDevice(machineFingerprint(),{app:i,signal:a.signal}),n=t&&"string"==typeof t.api_key?t.api_key.trim():"";if(!n)return{ok:!1,key:""};const o=r.saveApiKey(n);return e.setApiKey(n),{ok:!!o.ok,key:n,trialGranted:t.trial_granted,reusedAccount:!0===t.reused_account}}catch(e){if(o=e,!isTransientRegisterError(e))break}finally{clearTimeout(s)}}return{ok:!1,key:"",error:o}}module.exports={autoProvisionApiKey:autoProvisionApiKey,provisionFailureText:provisionFailureText,trialOutcomeNote:trialOutcomeNote,DEVICE_REGISTER_TIMEOUT_MS:8e3,DEVICE_REGISTER_RETRY_DELAYS_MS:DEVICE_REGISTER_RETRY_DELAYS_MS};
|
|
@@ -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 NEXUS_BRAIN_IDS=Object.freeze(["nexus-brain","aegis-brain"]),AEGIS_CLOUD_MODEL_IDS=Object.freeze(["nexus-brain","aegis-brain","nexus-brain-smart","aegis-brain-smart","nexus-brain-neo","aegis-brain-neo"]),AEGIS_CLOUD_MODEL_RE=/^(?:nexus|aegis)-brain(?:-(?:smart|neo))?$/,NEXUS_LABEL="Nexus",AUTO_MODEL_ID="nexus";function isAutoModelId(e){return"nexus"===String(null==e?"":e).trim().toLowerCase()}const AUTO_LABEL="Nexus — auto-route",AUTO_NOTE="server picks fast/smart/neo from the ask";function aliasOfEntry(e){if(!e||"object"!=typeof e)return null;for(const i of[e.alias_of,e.aliasOf])if("string"==typeof i&&i.trim())return i.trim();return null}function isHiddenEntry(e){return Boolean(e)&&!0===e.hidden}function selectBrainEntry(e){const i=Array.isArray(e)?e.filter(Boolean):[];return i.find(
|
|
3
|
+
"use strict";const NEXUS_BRAIN_IDS=Object.freeze(["nexus-brain","aegis-brain"]),AEGIS_CLOUD_MODEL_IDS=Object.freeze(["nexus-brain","aegis-brain","nexus-brain-smart","aegis-brain-smart","nexus-brain-neo","aegis-brain-neo"]),AEGIS_CLOUD_MODEL_RE=/^(?:nexus|aegis)-brain(?:-(?:smart|neo))?$/,NEXUS_LABEL="Nexus",AUTO_MODEL_ID="nexus";function isAutoModelId(e){return"nexus"===String(null==e?"":e).trim().toLowerCase()}const AUTO_LABEL="Nexus — auto-route",AUTO_NOTE="server picks fast/smart/neo from the ask";function aliasOfEntry(e){if(!e||"object"!=typeof e)return null;for(const i of[e.alias_of,e.aliasOf])if("string"==typeof i&&i.trim())return i.trim();return null}function isHiddenEntry(e){return Boolean(e)&&!0===e.hidden}function selectBrainEntry(e){const i=Array.isArray(e)?e.filter(Boolean):[];return i.find(e=>NEXUS_BRAIN_IDS.includes(e.id)&&!isHiddenEntry(e)&&null===aliasOfEntry(e))||i.find(e=>NEXUS_BRAIN_IDS.includes(e.id))||i.find(e=>NEXUS_BRAIN_IDS.includes(aliasOfEntry(e)))||null}function filterAegisCatalog(e){const i=selectBrainEntry(e);if(!i)return[];const{hidden:t,alias_of:n,aliasOf:r,...s}=i;return[{...s,label:"Nexus"}]}function isAegisCloudModel(e){const i="string"==typeof e?e.trim():e&&"object"==typeof e&&"string"==typeof e.id?e.id.trim():"";return!!AEGIS_CLOUD_MODEL_IDS.includes(i)||!!AEGIS_CLOUD_MODEL_RE.test(i)||NEXUS_BRAIN_IDS.includes(aliasOfEntry(e))}function omitAegisCloudModels(e){return(Array.isArray(e)?e:[]).filter(e=>{if(!e)return!1;if("string"==typeof e)return!isAegisCloudModel(e);const i="string"==typeof e.id?e.id.trim():"";return Boolean(i)&&!isAegisCloudModel(e)})}function offerableCatalog(e){const i=Array.isArray(e)?e.filter(Boolean):[];if(!i.length)return[];const t=selectBrainEntry(i),n=[],r=new Set;if(t){const{hidden:e,alias_of:i,aliasOf:s,...o}=t;n.push({...o,label:"Nexus"});for(const e of NEXUS_BRAIN_IDS)r.add(e);"string"==typeof t.id&&r.add(t.id)}const s=new Set(i.map(e=>"string"==typeof e.id?e.id.trim():"").filter(Boolean)),o=new Set(i.map(e=>aliasOfEntry(e)).filter(e=>e&&s.has(e)));for(const e of i){const i="string"==typeof e.id?e.id.trim():"";i&&!r.has(i)&&(aliasOfEntry(e)&&o.has(aliasOfEntry(e))||(r.add(i),n.push(e)))}return n}module.exports={NEXUS_BRAIN_IDS:NEXUS_BRAIN_IDS,NEXUS_LABEL:"Nexus",AUTO_MODEL_ID:"nexus",AUTO_LABEL:AUTO_LABEL,AUTO_NOTE:AUTO_NOTE,isAutoModelId:isAutoModelId,AEGIS_CLOUD_MODEL_IDS:AEGIS_CLOUD_MODEL_IDS,isAegisCloudModel:isAegisCloudModel,omitAegisCloudModels:omitAegisCloudModels,selectBrainEntry:selectBrainEntry,filterAegisCatalog:filterAegisCatalog,offerableCatalog:offerableCatalog};
|
|
@@ -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 BYOK_MODEL_ADDITIONS=Object.freeze({}),WIRE_MODEL_ALIASES=Object.freeze({deepseek:Object.freeze({"deepseek-v4.1-flash":"deepseek-flash","deepseek-flash-41":"deepseek-flash","deepseek-flash-0731":"deepseek-flash","deepseek-v4-flash-0731":"deepseek-flash","deepseek-pro":"deepseek-v4-pro","deepseek-v4-pro-latest":"deepseek-v4-pro","deepseek-v4.1-flash-1017":"deepseek-flash","deepseek-v4-pro-0813":"deepseek-v4-pro"})}),SNAPSHOT_SUFFIX_RE=/-(?:\d{4}|\d{8})$/;function knownWireId(e,r){return Object.prototype.hasOwnProperty.call(e,r)?e[r]:Object.values(e).includes(r)?r:""}function canonicalModelId(e,r){const o="string"==typeof r?r.trim():"";if(!o)return o;const s="string"==typeof e?e.trim():"",n=s?WIRE_MODEL_ALIASES[s]:null;if(!n)return o;const t=knownWireId(n,o);if(t)return t;const i=o.replace(SNAPSHOT_SUFFIX_RE,"");if(i!==o){const e=knownWireId(n,i);if(e)return e}return o}function addedModelsFor(e){const r="string"==typeof e?e.trim():"",o=r?BYOK_MODEL_ADDITIONS[r]:null;return Array.isArray(o)?o.slice():[]}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map(
|
|
3
|
+
"use strict";const BYOK_MODEL_ADDITIONS=Object.freeze({}),WIRE_MODEL_ALIASES=Object.freeze({deepseek:Object.freeze({"deepseek-v4.1-flash":"deepseek-flash","deepseek-flash-41":"deepseek-flash","deepseek-flash-0731":"deepseek-flash","deepseek-v4-flash-0731":"deepseek-flash","deepseek-pro":"deepseek-v4-pro","deepseek-v4-pro-latest":"deepseek-v4-pro","deepseek-v4.1-flash-1017":"deepseek-flash","deepseek-v4-pro-0813":"deepseek-v4-pro"})}),SNAPSHOT_SUFFIX_RE=/-(?:\d{4}|\d{8})$/;function knownWireId(e,r){return Object.prototype.hasOwnProperty.call(e,r)?e[r]:Object.values(e).includes(r)?r:""}function canonicalModelId(e,r){const o="string"==typeof r?r.trim():"";if(!o)return o;const s="string"==typeof e?e.trim():"",n=s?WIRE_MODEL_ALIASES[s]:null;if(!n)return o;const t=knownWireId(n,o);if(t)return t;const i=o.replace(SNAPSHOT_SUFFIX_RE,"");if(i!==o){const e=knownWireId(n,i);if(e)return e}return o}function addedModelsFor(e){const r="string"==typeof e?e.trim():"",o=r?BYOK_MODEL_ADDITIONS[r]:null;return Array.isArray(o)?o.slice():[]}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map(e=>"string"==typeof e?e:e&&e.id).map(e=>"string"==typeof e?e.trim():"").filter(Boolean)}function withByokAdditions(e){const r=Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null;if(!r)return[];const o=[];for(const e of r){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.id?e.id.trim():"",s=r?BYOK_MODEL_ADDITIONS[r]:null;if(!Array.isArray(s)||!s.length){o.push(e);continue}const n=new Set(modelIdsOf(e)),t=s.filter(e=>!n.has(e));if(!t.length){o.push(e);continue}const i=Array.isArray(e.models)?e.models:[];o.push({...e,models:[...i,...t]})}return o}const NEXUS_ELIGIBLE_PROVIDERS=Object.freeze(["deepseek","openai","groq","gemini","openrouter","together","grok","xai","mistral","cerebras","fireworks"]),NEXUS_POOLED_PROVIDER_ID=Object.freeze({xai:"grok"});function nexusFallbackProvider(e){const r="string"==typeof e?e.trim().toLowerCase():"";return r&&NEXUS_ELIGIBLE_PROVIDERS.includes(r)?NEXUS_POOLED_PROVIDER_ID[r]||r:""}function nexusFallbackModel({provider:e,providerKey:r,aegisKey:o,providerKeyRefused:s}={}){return r||s?"":o?nexusFallbackProvider(e):""}function nexusFallbackNotice(e){const r=e&&e.pooled_from;return r?`no ${r} key — answered through your AEGIS account${e.pooled_model?` (${e.pooled_model})`:""}`:""}module.exports={BYOK_MODEL_ADDITIONS:BYOK_MODEL_ADDITIONS,WIRE_MODEL_ALIASES:WIRE_MODEL_ALIASES,NEXUS_ELIGIBLE_PROVIDERS:NEXUS_ELIGIBLE_PROVIDERS,NEXUS_POOLED_PROVIDER_ID:NEXUS_POOLED_PROVIDER_ID,addedModelsFor:addedModelsFor,canonicalModelId:canonicalModelId,nexusFallbackModel:nexusFallbackModel,nexusFallbackNotice:nexusFallbackNotice,nexusFallbackProvider:nexusFallbackProvider,withByokAdditions:withByokAdditions};
|
|
@@ -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("fs"),path=require("path"),credentials=require("./credentials.js"),CATALOG_FILE="catalog.json",STALE_AFTER_MS=864e5;function catalogDir(e){return e&&e.dir||credentials.aegisHome(e&&e.env)}function catalogPath(e){return path.join(catalogDir(e),CATALOG_FILE)}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map(
|
|
3
|
+
"use strict";const fs=require("fs"),path=require("path"),credentials=require("./credentials.js"),CATALOG_FILE="catalog.json",STALE_AFTER_MS=864e5;function catalogDir(e){return e&&e.dir||credentials.aegisHome(e&&e.env)}function catalogPath(e){return path.join(catalogDir(e),CATALOG_FILE)}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map(e=>"string"==typeof e?e:e&&e.id).map(e=>"string"==typeof e?e.trim():"").filter(Boolean)}function providerArray(e){return Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null}function indexCatalog(e){const t=Object.create(null),r=Array.isArray(e&&e.models)?e.models:[];for(const e of r){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.provider_id?e.provider_id.trim():"",o="string"==typeof e.model_id?e.model_id.trim():"";r&&o&&"active"===("string"==typeof e.status?e.status.toLowerCase():"active")&&(t[r]||(t[r]=[])).push(o)}return t}function read(e){const t=catalogPath(e);let r,o;try{r=fs.readFileSync(t,"utf8")}catch(e){return null}try{o=JSON.parse(r)}catch(e){return null}if(!o||"object"!=typeof o||!Array.isArray(o.providers))return null;let n=null;const a=o.snapshot&&(o.snapshot.fetched_at||o.snapshot.fetchedAt);if("string"==typeof a&&a){const e=Date.parse(a);Number.isNaN(e)||(n=e)}if(null===n)try{n=fs.statSync(t).mtimeMs}catch(e){n=null}const s=null===n?null:Math.max(0,Date.now()-n);let i=null;const l=o.snapshot&&o.snapshot.revalidated_at;if("string"==typeof l&&l){const e=Date.parse(l);Number.isNaN(e)||(i=e)}const d=null!==i&&(null===n||i>n)?i:n;return{data:o,fetchedAt:n,revalidatedAt:i,ageMs:s,stale:null===d||Date.now()-d>864e5,path:t}}function write(e,t){const r=catalogPath(t);fs.mkdirSync(path.dirname(r),{recursive:!0});const o=`${r}.${process.pid}.tmp`;return fs.writeFileSync(o,JSON.stringify(e),"utf8"),fs.renameSync(o,r),r}function withCatalog(e,t,r){const o=providerArray(e);if(!o)return[];let n=t;if(void 0===n){const e=read(r);n=e?e.data:null}const a=indexCatalog(n);if(!Object.keys(a).length)return o.slice();const s=[];for(const e of o){if(!e||"object"!=typeof e)continue;const t="string"==typeof e.id?e.id.trim():"",r=t?a[t]:null;if(!r||!r.length){s.push(e);continue}const o=new Set(modelIdsOf(e)),n=r.filter(e=>!o.has(e));if(!n.length){s.push(e);continue}const i=Array.isArray(e.models)?e.models:[];s.push({...e,models:[...i,...n]})}return s}function addedModelsFor(e,t,r,o){const n="string"==typeof e?e.trim():"";if(!n)return[];let a=r;if(void 0===a){const e=read(o);a=e?e.data:null}const s=indexCatalog(a)[n]||[],i=(providerArray(t)||[]).find(e=>e&&"string"==typeof e.id&&e.id.trim()===n),l=new Set(modelIdsOf(i));return s.filter(e=>!l.has(e))}const MAX_PAGES=200;async function refresh(e,t){const r=t||{},o=r.limit||500,n=r.maxPages||200,a=read(r),s=a&&a.data||null,i=[];let l=null,d=0,c=r.etag||null,u=null,f=!1;try{for(;;){const t=await e({cursor:l,limit:o,etag:c});if(!t||t.notModified){f=!0;break}0===d&&t.etag&&(u=t.etag);const r=Array.isArray(t.models)?t.models:[];for(const e of r)e&&"object"==typeof e&&i.push(e);if(d+=1,!t.has_more||!t.next_cursor)break;if(d>=n)return _refreshResult({ok:!1,changed:!1,pages:d,models:i.length,providers:0,staleKept:Boolean(s),reason:`stopped after ${d} pages; cache left untouched`});l=t.next_cursor,c=null}}catch(e){return _refreshResult({ok:!1,changed:!1,pages:d,models:0,providers:0,staleKept:Boolean(s),reason:e&&e.message||String(e)})}if(f){let e=null;if(s)try{const t="function"==typeof r.now?r.now():Date.now();e=write({...s,snapshot:{...s.snapshot||{},revalidated_at:new Date(t).toISOString(),...u?{etag:u}:{}}},r)}catch{e=null}return _refreshResult({ok:!0,changed:!1,pages:0,models:0,providers:0,staleKept:!e,written:e,reason:"not-modified"})}if(!i.length)return _refreshResult({ok:!1,changed:!1,pages:d,models:0,providers:0,staleKept:Boolean(s),reason:"empty catalog; cache left untouched"});const p=s&&Array.isArray(s.providers)?s.providers:[],h="function"==typeof r.now?r.now():Date.now(),g={schema_version:s&&s.schema_version||1,providers:p,models:i,snapshot:{fetched_at:new Date(h).toISOString(),models_seen:i.length,providers_seen:p.length,source:"catalog-api",...u?{etag:u}:{}}};let m=null;try{m=write(g,r)}catch(e){return _refreshResult({ok:!1,changed:!1,pages:d,models:i.length,providers:p.length,staleKept:Boolean(s),reason:e&&e.message||String(e)})}return _refreshResult({ok:!0,changed:!0,pages:d,models:i.length,providers:p.length,staleKept:!1,written:m})}function _refreshResult(e){return{ok:Boolean(e.ok),changed:Boolean(e.changed),written:e.written||null,pages:e.pages||0,models:e.models||0,providers:e.providers||0,staleKept:Boolean(e.staleKept),...e.reason?{reason:e.reason}:{}}}module.exports={CATALOG_FILE:CATALOG_FILE,STALE_AFTER_MS:864e5,MAX_PAGES:200,catalogDir:catalogDir,catalogPath:catalogPath,indexCatalog:indexCatalog,read:read,write:write,refresh:refresh,withCatalog:withCatalog,addedModelsFor:addedModelsFor};
|
|
@@ -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 SCOPE_CONVERSATION="conversation",SCOPE_MEMORY="memory",SCOPE_TEXT={
|
|
3
|
+
"use strict";const SCOPE_CONVERSATION="conversation",SCOPE_MEMORY="memory",SCOPE_TEXT={[SCOPE_CONVERSATION]:"one conversation",[SCOPE_MEMORY]:"the whole memory base"};function keyTag(e){const n="string"==typeof e?e.trim():"";return n?`φ_${n}`:null}function authorLine(e){return keyTag(e)||"no key — this copy is unsigned"}function safeFileName(e,n){return String(e||n||"aegis-export").normalize("NFKD").replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"aegis-export"}function stamp({scope:e,keyFingerprint:n=null,email:t=null,exportedAt:o=null,subject:r=null,count:i=null}={}){const a=keyTag(n),s=[];return r&&s.push(`**What this is:** ${r}`),s.push(`**Scope:** ${SCOPE_TEXT[e]||String(e||"unknown")} (${e||"unknown"})`),s.push(`**Author:** ${authorLine(n)}`),s.push(`**Account:** ${t||"not reported by the server"}`),null!=i&&s.push(`**Entries:** ${i}`),s.push(`**Exported:** ${o||"timestamp not recorded"}`),s.push(a?`**Sealed by:** ${a} — this is a key tag, not the key. It proves the same machine wrote it.`:"**Sealed by:** nothing — no authorship key is set on this machine, so this copy cannot prove it came from you."),`${s.join("\n")}\n\n`}function conversationMarkdown(e,n={}){return`# ${e&&(e.title||e.id)||"Untitled conversation"}\n\n${stamp({scope:"conversation",subject:null,keyFingerprint:n.keyFingerprint,email:n.email,exportedAt:n.exportedAt,count:void 0===n.count?null:n.count})}---\n\n${n.transcript||""}`}function memoryMarkdown(e,n={}){return`${stamp({scope:"memory",subject:null,keyFingerprint:n.keyFingerprint,email:n.email,exportedAt:n.exportedAt,count:void 0===n.count?null:n.count})}---\n\n${e||""}`}function conversationFileName(e,n){const t=String(n||"").replace(/[:.]/g,"-").replace(/[^\w-]+/g,""),o=safeFileName(e&&(e.title||e.id),"conversation");return t?`${o}-${t}.md`:`${o}.md`}module.exports={SCOPE_CONVERSATION:"conversation",SCOPE_MEMORY:"memory",SCOPE_TEXT:SCOPE_TEXT,keyTag:keyTag,authorLine:authorLine,safeFileName:safeFileName,stamp:stamp,conversationMarkdown:conversationMarkdown,memoryMarkdown:memoryMarkdown,conversationFileName:conversationFileName};
|
|
@@ -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"),os=require("node:os"),path=require("node:path"),KEY_ENV="AEGIS_API_KEY",MEMORY_ENV="AEGIS_MEMORY_TOKEN",HOME_ENV="AEGISCODE_HOME",CREDENTIALS_FILE="credentials.json",CONFIG_FILE="config.json",FILE_MODE=384,DIR_MODE=448;function aegisHome(e){const r=e||process.env,n=r&&r[HOME_ENV];return n&&String(n).trim()?path.resolve(String(n).trim()):path.join(os.homedir(),".aegiscode")}function credentialsPath(e){return path.join(e||aegisHome(),CREDENTIALS_FILE)}function configPath(e){return path.join(e||aegisHome(),CONFIG_FILE)}function normalizeApiKey(e){let r=String(null==e?"":e).trim();if(!r)return"";r=r.replace(/^export\s+/i,"").trim();const n=/^[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.+)$/s.exec(r);return n&&(r=n[1].trim()),r=r.replace(/^["']|["']$/g,"").trim(),r=r.replace(/^Bearer\s+/i,"").trim(),r}function validateApiKey(e,r={}){const n=String(r.label||"AEGIS"),t=normalizeApiKey(e);return t?/\s/.test(t)?{ok:!1,key:t,reason:"whitespace",message:"that looks like more than one word — paste just the key"}:t.length<16?{ok:!1,key:t,reason:"too short",message:`that key is ${t.length} characters — ${n} keys are longer than that`}:{ok:!0,key:t,reason:null,message:null}:{ok:!1,key:t,reason:"empty",message:"no key given"}}function readCredentials(e){try{const r=JSON.parse(fs.readFileSync(credentialsPath(e),"utf8"));if(r&&"object"==typeof r)return r}catch{}return{}}function writeCredentials(e,r){const n=credentialsPath(r),t={...readCredentials(r),...e,version:1};try{fs.mkdirSync(path.dirname(n),{recursive:!0,mode:
|
|
3
|
+
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),KEY_ENV="AEGIS_API_KEY",MEMORY_ENV="AEGIS_MEMORY_TOKEN",HOME_ENV="AEGISCODE_HOME",CREDENTIALS_FILE="credentials.json",CONFIG_FILE="config.json",FILE_MODE=384,DIR_MODE=448;function aegisHome(e){const r=e||process.env,n=r&&r[HOME_ENV];return n&&String(n).trim()?path.resolve(String(n).trim()):path.join(os.homedir(),".aegiscode")}function credentialsPath(e){return path.join(e||aegisHome(),CREDENTIALS_FILE)}function configPath(e){return path.join(e||aegisHome(),CONFIG_FILE)}function normalizeApiKey(e){let r=String(null==e?"":e).trim();if(!r)return"";r=r.replace(/^export\s+/i,"").trim();const n=/^[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.+)$/s.exec(r);return n&&(r=n[1].trim()),r=r.replace(/^["']|["']$/g,"").trim(),r=r.replace(/^Bearer\s+/i,"").trim(),r}function validateApiKey(e,r={}){const n=String(r.label||"AEGIS"),t=normalizeApiKey(e);return t?/\s/.test(t)?{ok:!1,key:t,reason:"whitespace",message:"that looks like more than one word — paste just the key"}:t.length<16?{ok:!1,key:t,reason:"too short",message:`that key is ${t.length} characters — ${n} keys are longer than that`}:{ok:!0,key:t,reason:null,message:null}:{ok:!1,key:t,reason:"empty",message:"no key given"}}function readCredentials(e){try{const r=JSON.parse(fs.readFileSync(credentialsPath(e),"utf8"));if(r&&"object"==typeof r)return r}catch{}return{}}function writeCredentials(e,r){const n=credentialsPath(r),t={...readCredentials(r),...e,version:1};try{fs.mkdirSync(path.dirname(n),{recursive:!0,mode:448});const e=n+".tmp";fs.writeFileSync(e,JSON.stringify(t,null,2)+"\n",{mode:384}),fs.renameSync(e,n);try{fs.chmodSync(n,384)}catch{}}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[credentials] write failed:",e),{ok:!1,error:e,credentials:t}}return{ok:!0,credentials:t}}function readLegacyConfig(e){try{const r=JSON.parse(fs.readFileSync(configPath(e),"utf8"));if(!r||"object"!=typeof r)return{};const n=r.aegiscloud&&"object"==typeof r.aegiscloud?r.aegiscloud:{},t=r.memory&&"object"==typeof r.memory?r.memory:{};return{apiKey:normalizeApiKey(n.api_key),memoryToken:String(t.token||"").trim(),syncConversations:!0===n.syncConversations||void 0,lastVerified:n.lastVerified||null,memorySubscribed:!0===t.subscribed||void 0}}catch{return{}}}function legacyKeyOnDisk(e){return!!readLegacyConfig(e).apiKey}function adoptLegacy(e){const r=readLegacyConfig(e),n=readCredentials(e),t={};return r.apiKey&&!n.aegisApiKey&&(t.aegisApiKey=r.apiKey),r.memoryToken&&!n.memoryToken&&(t.memoryToken=r.memoryToken),Object.keys(t).length&&writeCredentials({...t,adoptedFrom:configPath(e)},e).ok?{adopted:Object.keys(t)}:{adopted:[]}}function fromEnvFile(e,r,n){try{const t=require("./env-file.js");return"function"==typeof t.isFromEnvFile&&t.isFromEnvFile(e,r,n?{env:n}:void 0)}catch{return!1}}function resolveApiKey(e={}){const r=e.env||process.env,n=e.dir,t=normalizeApiKey(r&&r[KEY_ENV]);if(t&&!fromEnvFile(KEY_ENV,r&&r[KEY_ENV],r))return{key:t,source:"env",from:KEY_ENV};const o=normalizeApiKey(readCredentials(n).aegisApiKey);if(o)return{key:o,source:"credentials",from:credentialsPath(n)};if(t)return{key:t,source:"envfile",from:envFileLabel(r,n)};const i=readLegacyConfig(n).apiKey;return i?{key:i,source:"config",from:configPath(n)}:{key:"",source:"none",from:""}}function hasApiKey(e={}){return!!resolveApiKey(e).key}function saveApiKey(e,r){const n=validateApiKey(e);if(!n.ok)return{ok:!1,key:n.key,path:credentialsPath(r),message:n.message};const t=writeCredentials({aegisApiKey:n.key,savedAt:(new Date).toISOString()},r);return t.ok?{ok:!0,key:n.key,path:credentialsPath(r)}:{ok:!1,key:n.key,path:credentialsPath(r),error:t.error,message:`could not write ${credentialsPath(r)}`}}function clearApiKey(e){return{cleared:!!normalizeApiKey(readCredentials(e).aegisApiKey),ok:writeCredentials({aegisApiKey:"",adoptedFrom:""},e).ok,path:credentialsPath(e)}}function resolveMemoryToken(e={}){const r=e.env||process.env,n=e.dir,t=String(r&&r[MEMORY_ENV]||"").trim();if(t)return{token:t,source:"env"};const o=readCredentials(n),i=String(o.memoryToken||"").trim();if(i)return{token:i,source:"credentials"};const a=readLegacyConfig(n).memoryToken;return a?{token:a,source:"config"}:{token:"",source:"none"}}function saveMemoryToken(e,r={},n){return writeCredentials({memoryToken:String(e||"").trim(),...r},n)}function clearMemoryToken(e){return writeCredentials({memoryToken:"",memorySubscribed:!1},e)}function keyStatus(e={}){const r=e.dir,{key:n,source:t,from:o}=resolveApiKey(e),i=readCredentials(r);let a=null;try{a=511&fs.statSync(credentialsPath(r)).mode}catch{}return{configured:!!n,key:n,source:t,from:o,path:credentialsPath(r),fileMode:null==a?null:"0"+a.toString(8),stored:!!normalizeApiKey(i.aegisApiKey),legacyPlaintext:legacyKeyOnDisk(r),verifiedAt:i.verifiedAt||null,account:i.account||null,memoryToken:!!resolveMemoryToken(e).token,memorySource:resolveMemoryToken(e).source}}function clientOptions(e={}){const{key:r}=resolveApiKey(e),{token:n}=resolveMemoryToken(e),t={};return t.apiKey=r,t.memoryToken=n,e.channel&&(t.channel=e.channel),t}const SOURCE_LABEL={env:`${KEY_ENV}`,credentials:"saved key file",envfile:`~/.aegiscode/.env (${KEY_ENV})`,config:"config.json (aegis CLI)",none:"not set"};function envFileLabel(e,r){try{const e=require("./env-file.js");if("function"==typeof e.envFileFor)return e.envFileFor(r)}catch{}return envFileForFallback(r)}function envFileForFallback(e){return path.join(e||aegisHome(),".env")}function sourceLabel(e){return SOURCE_LABEL[e]||SOURCE_LABEL.none}function preferNewest(e,r,n={}){const t=normalizeApiKey(e),o=Date.parse(r||"")||0,i=readCredentials(n.dir),a=normalizeApiKey(i.aegisApiKey),s=Date.parse(i.savedAt||"")||0;return a?t?t===a?{key:t,source:"host",sharedAt:s,hostAt:o}:s>o?{key:a,source:"shared",sharedAt:s,hostAt:o}:{key:t,source:"host",sharedAt:s,hostAt:o}:{key:a,source:"shared",sharedAt:s,hostAt:o}:{key:t,source:t?"host":"none",sharedAt:s,hostAt:o}}const HOW_TO_SET="run `aegiscode login` (or /key inside a session) to save one";module.exports={KEY_ENV:KEY_ENV,MEMORY_ENV:MEMORY_ENV,HOME_ENV:HOME_ENV,CREDENTIALS_FILE:CREDENTIALS_FILE,CONFIG_FILE:CONFIG_FILE,aegisHome:aegisHome,credentialsPath:credentialsPath,configPath:configPath,normalizeApiKey:normalizeApiKey,validateApiKey:validateApiKey,readCredentials:readCredentials,writeCredentials:writeCredentials,readLegacyConfig:readLegacyConfig,legacyKeyOnDisk:legacyKeyOnDisk,adoptLegacy:adoptLegacy,resolveApiKey:resolveApiKey,hasApiKey:hasApiKey,fromEnvFile:fromEnvFile,envFileForFallback:envFileForFallback,saveApiKey:saveApiKey,clearApiKey:clearApiKey,resolveMemoryToken:resolveMemoryToken,saveMemoryToken:saveMemoryToken,clearMemoryToken:clearMemoryToken,keyStatus:keyStatus,clientOptions:clientOptions,preferNewest:preferNewest,sourceLabel:sourceLabel,HOW_TO_SET:HOW_TO_SET};
|
|
@@ -42,4 +42,4 @@
|
|
|
42
42
|
* fonts: [{ name, copyright, url, licence }],
|
|
43
43
|
* missing: [id…]
|
|
44
44
|
* }
|
|
45
|
-
*/function buildCredits(t){const e={};for(const n of Array.isArray(t)?t:[])n&&n.id&&(e[n.id]=n);const n=e.vendor||null,r=e.fonts||null,i=e.licensing||null,s=i?extractNotice(i.text):"Copyright (C) 2026 Niklas Borneklint";return{program:{licence:LICENCE_ID,name:LICENCE_NAME,url:LICENCE_URL,source:SOURCE_URL,copyright:COPYRIGHT,notice:s},documents:DOCUMENTS.map(
|
|
45
|
+
*/function buildCredits(t){const e={};for(const n of Array.isArray(t)?t:[])n&&n.id&&(e[n.id]=n);const n=e.vendor||null,r=e.fonts||null,i=e.licensing||null,s=i?extractNotice(i.text):"Copyright (C) 2026 Niklas Borneklint";return{program:{licence:LICENCE_ID,name:LICENCE_NAME,url:LICENCE_URL,source:SOURCE_URL,copyright:COPYRIGHT,notice:s},documents:DOCUMENTS.map(t=>({id:t.id,title:t.title,applies:t.applies,found:Boolean(e[t.id]),path:e[t.id]?e[t.id].path:null})),code:n?parseAttributions(n.text):[],fonts:r?parseFonts(r.text):[],missing:DOCUMENTS.filter(t=>!e[t.id]).map(t=>t.id)}}function extractNotice(t){const e=String(t||""),n=e.indexOf("## Notice to apply to the program");if(-1===n)return"Copyright (C) 2026 Niklas Borneklint";const r=/```([\s\S]*?)```/.exec(e.slice(n));return r&&r[1].trim()||"Copyright (C) 2026 Niklas Borneklint"}function creditsFromDisk(t){const e=[];for(const n of DOCUMENTS){const r=t&&"function"==typeof t.readText?t.readText(n.file):readDocument(n);r&&e.push(r)}return buildCredits(e)}module.exports={LICENCE_ID:LICENCE_ID,LICENCE_NAME:LICENCE_NAME,LICENCE_URL:LICENCE_URL,SOURCE_URL:SOURCE_URL,COPYRIGHT:COPYRIGHT,DOCUMENTS:DOCUMENTS,buildCredits:buildCredits,creditsFromDisk:creditsFromDisk,parseAttributions:parseAttributions,parseFonts:parseFonts,unwrapBullets:unwrapBullets,readDocument:readDocument,extractNotice:extractNotice};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";function driveConnectUrl(e){return`${String(e||"").replace(/\/+$/,"")}/connect/drive`}async function driveStatus(e){const n=await e.driveToken(),o=Boolean(n&&n.connected),t=n&&n.google_linked;return{connected:o,googleLinked:o||!0===t,googleLinkedKnown:"boolean"==typeof t||o,email:n&&n.email||null}}async function waitForDriveConnected(e,n={}){const o=Number(n.timeoutMs)>0?Number(n.timeoutMs):18e4,t=Number(n.pollMs)>0?Number(n.pollMs):2e3,r=n.signal||null,i=Date.now()+o;for(;;){const n=await driveStatus(e);if(n.connected)return n;if(r&&r.aborted){const e=new Error("cancelled");throw e.name="AbortError",e}if(Date.now()>=i)throw new Error(`timed out after ${Math.round(o/1e3)}s waiting for Google Drive to connect`);await new Promise(
|
|
3
|
+
"use strict";function driveConnectUrl(e){return`${String(e||"").replace(/\/+$/,"")}/connect/drive`}async function driveStatus(e){const n=await e.driveToken(),o=Boolean(n&&n.connected),t=n&&n.google_linked;return{connected:o,googleLinked:o||!0===t,googleLinkedKnown:"boolean"==typeof t||o,email:n&&n.email||null}}async function waitForDriveConnected(e,n={}){const o=Number(n.timeoutMs)>0?Number(n.timeoutMs):18e4,t=Number(n.pollMs)>0?Number(n.pollMs):2e3,r=n.signal||null,i=Date.now()+o;for(;;){const n=await driveStatus(e);if(n.connected)return n;if(r&&r.aborted){const e=new Error("cancelled");throw e.name="AbortError",e}if(Date.now()>=i)throw new Error(`timed out after ${Math.round(o/1e3)}s waiting for Google Drive to connect`);await new Promise(e=>setTimeout(e,t))}}module.exports={driveConnectUrl:driveConnectUrl,driveStatus:driveStatus,waitForDriveConnected:waitForDriveConnected};
|