aegisone 1.0.64 → 1.0.66
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/bin/aegiscode.js +47 -5
- 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/autonomous.js +574 -10
- 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-cmd.js +3 -0
- 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/limits.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/provenance.lock.json +3 -3
- 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/main.js +82 -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/main.js +82 -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/pty-window.html +72 -0
- package/vendor/desktop/renderer/pty-window.js +3 -0
- 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 +77 -3
- 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-cmd.js +3 -0
- 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/provenance.lock.json +3 -3
- package/vendor/desktop/vendor/faces/cli/src/render.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/screen.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/screens.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/secret.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/securefs.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/settings.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/signup.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/summarize.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/sysdiag.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/theme.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/title.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/todos.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/tokens.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/topup.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/update.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/aegis.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/attest.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/authorship-key.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/auto-provision.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/brain-catalog.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/catalog-client.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/conversation-export.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/credentials.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/credits.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/drive-connect.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/env-file.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/fingerprint.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-memory.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-sessions.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/google-signin.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/hooks.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/model-discovery.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/model-sync.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/platform.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/presence.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/record-vault.js +2 -2
- package/vendor/desktop/vendor/faces/cli/vendor/client/session-search.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/session-store.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/skills.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/topup.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/touch.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/update.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/user-models.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/attachments.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/autonomous.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/context.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/entitlement.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/exec-plan.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/local.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-rules.js +2 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-store.js +3 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-write.js +2 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/pro-sessions.js +3 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/queue.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/repeat-guard.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/session-rounds.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/shell.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/spill.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/turn-guard.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/verify-stop.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/worktree-lock.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +3 -3
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/hosts/install.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/hosts/openai-shim.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/hosts/spec.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/hosts/targets.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/admission.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/server.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/tools.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/child.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/protocol.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/selfhost.js +1 -1
- package/vendor/desktop/vendor/fingerprint.js +1 -1
- package/vendor/desktop/vendor/foreign-memory.js +1 -1
- package/vendor/desktop/vendor/foreign-sessions.js +1 -1
- package/vendor/desktop/vendor/google-signin.js +1 -1
- package/vendor/desktop/vendor/hooks.js +1 -1
- package/vendor/desktop/vendor/model-discovery.js +1 -1
- package/vendor/desktop/vendor/model-sync.js +1 -1
- package/vendor/desktop/vendor/naming.js +1 -1
- package/vendor/desktop/vendor/platform.js +1 -1
- package/vendor/desktop/vendor/prefs.js +1 -1
- package/vendor/desktop/vendor/presence.js +1 -1
- package/vendor/desktop/vendor/protocol.js +1 -1
- package/vendor/desktop/vendor/record-vault.js +2 -2
- package/vendor/desktop/vendor/selfhost.js +1 -1
- package/vendor/desktop/vendor/session-search.js +1 -1
- package/vendor/desktop/vendor/session-store.js +1 -1
- package/vendor/desktop/vendor/skills.js +1 -1
- package/vendor/desktop/vendor/topup.js +1 -1
- package/vendor/desktop/vendor/touch.js +1 -1
- package/vendor/desktop/vendor/update.js +1 -1
- package/vendor/desktop/vendor/user-models.js +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
3
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
4
|
-
"use strict";const path=require("node:path");for(const e of[process.stdout,process.stderr])e.on("error",
|
|
4
|
+
"use strict";const path=require("node:path");for(const e of[process.stdout,process.stderr])e.on("error",e=>{throw!e||"EPIPE"!==e.code&&"ERR_STREAM_DESTROYED"!==e.code||process.exit(0),e});const HELP="aegiscode — AEGIS in your shell.\n\nUsage:\n aegiscode interactive session\n aegiscode \"question\" one-shot, then exit\n aegiscode -p \"question\" same, explicit\n echo \"q\" | aegiscode -p - read the prompt from stdin\n\nAccount:\n aegiscode connect sign this machine in — registers a device account\n if it has none (idempotent per machine), and that\n key is what cloud memory and the record vault use\n aegiscode connect --status is this machine connected? (--json; exit 1 if not)\n aegiscode connect --logout sign out (forget the saved key here)\n aegiscode login [<key>] save your AEGIS API key (prompts, no echo, if omitted)\n aegiscode logout remove the saved key\n aegiscode key status show which key is in use and where it came from\n aegiscode topup [EUR] add credit to the token bank (2..1000, default 10):\n opens the payment page, then confirms the credit\n here — the account this machine auto-provisions\n has no browser session, so the page cannot show it\n\nAutomation:\n aegiscode autonomous help run queued tasks with no terminal at all\n aegiscode dream --since 7d build the local wiki over recent transcripts\n + cloud notes (offline, --dry-run to preview)\n aegiscode mcp install put AEGIS inside VS Code / Cursor / Zed /\n Cline / Windsurf / … ('mcp list' shows them)\n aegiscode mcp status which editors are configured, and do they work\n aegiscode mcp shim OpenAI-compatible endpoint for clients that\n take a base URL but speak no MCP\n aegiscode mcp help all subcommands and their flags\n\nAttestation (φ(α) — a sealed record of what a session was):\n aegiscode fingerprint status which authorship key is in use, and where\n aegiscode fingerprint keygen mint a private key (0600, never printed)\n aegiscode fingerprint mint seal the last session as a record\n aegiscode fingerprint verify <file> recompute a record's attestation\n aegiscode fingerprint backup --to DIR copy the key somewhere safe\n aegiscode fingerprint publish [<file>] publish a record, link the copy\n aegiscode fingerprint anchor <file> is the published copy still ours?\n aegiscode fingerprint vault --audit what is in the vault, and is a key in it\n aegiscode fingerprint help all subcommands and their flags\n\nCode protection (the agent-key gate on aegiscodex-dev / aegiscode-plugin):\n aegiscode gate status can THIS machine edit a gated tree?\n aegiscode gate import-key [PATH] adopt a key dropped at PATH\n (default ~/Downloads/agent.key),\n then delete PATH\n aegiscode gate bind-machine trust this machine in the manifest\n aegiscode gate rotate mint a fresh key, burn the old one\n aegiscode gate add-key add another key (from stdin)\n aegiscode gate lock-status the server-side half of the lock\n aegiscode gate help all subcommands and their flags\n\nProvenance (this binary, and whether it is still the published one):\n aegiscode provenance licence, source, and a self-check of\n this build against the published seal\n (--json for scripts; exit 1 if a\n sealed unit has moved)\n\nOptions:\n -m, --model <id> pin a model id (see /models; default: server choice)\n --class <name> run this turn on aegis|byok|local|pro. The one-shot\n path had no way to state a class, so '-p' always ran\n the pooled route (DEFAULT_CLASS) no matter what was\n pinned — a headless turn could not use a BYOK key at\n all. '--class byok' needs '--model <provider>:<model>'.\n --base <url> API base (default $AEGIS_API_BASE or aegiscloud.org)\n --key <key> API key for THIS RUN only — it is not saved. Use\n \"aegiscode login\" to store one for good.\n --json with -p: emit JSON instead of text\n --no-stream buffer the answer instead of streaming it\n --max-tokens <n> output ceiling hint\n --light light theme\n --width <cols> force a render width (useful for piping/logs)\n --automode skip tool-approval prompts (exec/writeFile/editFile\n run without asking) — same as the in-session /automode\n --yolo alias of --automode (the pre-rename spelling)\n --ascii draw with the ASCII mark and glyph set (no Unicode).\n Same as AEGIS_ART=ascii; /terminal ascii toggles it\n mid-session.\n --no-color no colour at all (same as NO_COLOR=1)\n --terminal print the resolved terminal capabilities and exit —\n one report shape on every platform, so pasting it\n from PowerShell (or into a bug report) reads the same\n as pasting it from zsh\n -c, --continue skip onboarding and resume the most recent session\n -h, --help this text\n -v, --version print the version\n\nIn-session: type /help for commands, /quit to exit, esc/ctrl+c to interrupt a\nrunning call. Plain text is a prompt (identical to /ask) — a question that\nneeds a file read, a shell command, or an edit is handled the same turn.\n";function parseArgs(e){const s={model:null,base:null,key:null,json:!1,class:null,stream:!0,maxTokens:void 0,light:!1,width:null,yolo:!1,ascii:null,color:null,terminal:!1,continue:!1,prompt:null,help:!1,version:!1,command:null,commandArg:null,commandArgv:null},t=[],n=e[0];if(n&&!n.startsWith("-")&&ACCOUNT_COMMANDS.has(n)){const t=e[1];s.command=n,s.commandArg=t&&!t.startsWith("-")?t:null,e=e.slice(s.commandArg?2:1)}else if("autonomous"===n){const t=e[1]&&!e[1].startsWith("-")?e[1]:"help";s.command="autonomous",s.commandArg=t,s.commandArgv=e.slice(e[1]&&!e[1].startsWith("-")?2:1),e=[]}else if("mcp"===n){const t=e[1]&&!e[1].startsWith("-")?e[1]:"status";s.command="mcp",s.commandArg=t,s.commandArgv=e.slice(e[1]&&!e[1].startsWith("-")?2:1),e=[]}else if("fingerprint"===n){const t=e[1]&&!e[1].startsWith("-")?e[1]:"status";s.command="fingerprint",s.commandArg=t,s.commandArgv=e.slice(e[1]&&!e[1].startsWith("-")?2:1),e=[]}else if("gate"===n){const t=e[1]&&!e[1].startsWith("-")?e[1]:"status";s.command="gate",s.commandArg=t,s.commandArgv=e.slice(e[1]&&!e[1].startsWith("-")?2:1),e=[]}else if("dream"===n)s.command="dream",s.commandArgv=e.slice(1),e=[];else if("connect"===n)s.command="connect",s.commandArg=null,s.commandArgv=e.slice(1),e=[];else if("provenance"===n)s.command="provenance",e=e.slice(1);else if("topup"===n){const t=e[1]&&!e[1].startsWith("-")?e[1]:null;s.command="topup",s.commandArg=t,e=t?e.slice(2):e.slice(1)}for(let n=0;n<e.length;n++){const o=e[n],r=()=>{const s=e[++n];if(void 0===s)throw new Error(`${o} needs a value`);return s};switch(o){case"-h":case"--help":s.help=!0;break;case"-v":case"--version":s.version=!0;break;case"-p":case"--print":s.prompt=e[n+1]&&!e[n+1].startsWith("-")?r():"-";break;case"-m":case"--model":s.model=r();break;case"--class":s.class=r();break;case"--base":s.base=r();break;case"--key":s.key=r();break;case"--json":s.json=!0;break;case"--no-stream":s.stream=!1;break;case"--stream":s.stream=!0;break;case"--max-tokens":s.maxTokens=Number(r());break;case"--light":s.light=!0;break;case"--automode":case"--yolo":s.yolo=!0;break;case"-c":case"--continue":s.continue=!0;break;case"--width":s.width=Number(r());break;case"--ascii":s.ascii=!0;break;case"--unicode":s.ascii=!1;break;case"--no-color":case"--no-colour":s.color=!1;break;case"--color":case"--colour":s.color=!0;break;case"--terminal":case"--caps":s.terminal=!0;break;default:if(o.startsWith("-")&&"-"!==o)throw new Error(`unknown option: ${o}`);t.push(o)}}return!s.prompt&&t.length&&(s.prompt=t.join(" ")),s}
|
|
5
5
|
/**
|
|
6
6
|
* `aegiscode provenance` — what this binary is, and whether its safety files are
|
|
7
7
|
* the ones that were published.
|
|
@@ -17,4 +17,4 @@
|
|
|
17
17
|
* cheap attack must be the loud one). A fork that has deliberately rebuilt is
|
|
18
18
|
* expected to regenerate the manifest and exit 0 naming itself; one that has
|
|
19
19
|
* not now says so instead of staying silent.
|
|
20
|
-
*/function runProvenance(e={}){const s=require(path.join(__dirname,"..","package.json")),t=require("../src/provenance.js"),n=t.describe({version:s.version});return e.json?(process.stdout.write(JSON.stringify({product:t.IDENTITY.product,bin:t.IDENTITY.bin,version:s.version,license:t.IDENTITY.license,source:t.IDENTITY.source,homepage:t.IDENTITY.homepage,copyright:t.IDENTITY.copyright,safety:{ok:n.report.ok,checked:n.report.checked,problems:n.report.problems}},null,2)+"\n"),n.ok?0:1):(process.stdout.write(n.text),n.ok?0:1)}const ACCOUNT_COMMANDS=new Set(["login","logout","key"]);async function runAccountCommand(e,s,t={}){const n=t.stdout||process.stdout,o=t.stderr||process.stderr,r=t.stdin||process.stdin,{credentials:i,readSecret:a,maskKey:c}=loadAccountDeps();if("logout"===e||"key"===e&&["clear","remove","rm"].includes(String(s||"").toLowerCase())){const e=i.clearApiKey();return n.write(e.cleared?`aegiscode: key removed from ${e.path}\n`:"aegiscode: no saved key to remove\n"),i.legacyKeyOnDisk()&&n.write('aegiscode: note — a plaintext copy is also in config.json, written by an older AEGIS CLI; delete its "aegiscloud" block as well to finish removing it\n'),0}if("key"===e&&["status","show",""].includes(String(s||"").toLowerCase())){const e=i.keyStatus();return t.json?(n.write(JSON.stringify({configured:e.configured,source:e.source,source_label:i.sourceLabel(e.source),path:e.path,file_mode:e.fileMode,masked:e.configured?c(e.key):null,memory_token:e.memoryToken,verified_at:e.verifiedAt,plaintext_copy_in_config:e.legacyPlaintext},null,2)+"\n"),e.configured?0:1):(n.write([`key: ${e.configured?c(e.key):"not set"}`,`source: ${i.sourceLabel(e.source)}`,`file: ${e.path}${e.fileMode?` (${e.fileMode})`:""}`,"memory: "+(e.memoryToken?"token held (cloud sync ready)":"no token"),e.verifiedAt?`verified: ${e.verifiedAt}`:null,e.legacyPlaintext?"note: a plaintext copy also sits in config.json — re-save with `aegiscode login` to move it":null].filter(Boolean).join("\n")+"\n"),e.configured?0:1)}let d=s&&"status"!==s?String(s).trim():"";if(!d){if(!r.isTTY)return o.write("aegiscode: no terminal to prompt on — pass the key: `aegiscode login <api_key>`\n (or set AEGIS_API_KEY for a single run)\n"),2;d=await a("AEGIS API key (kept off screen, Enter to cancel): ",{stdin:r,stdout:n})}if(!d)return o.write("aegiscode: no key given — nothing saved\n"),2;const{createApp:l}=require("../src/app.js"),u=l({interactive:!1}),m=await u.setApiKey(d);if(!m.ok)return o.write(`aegiscode: ${m.message||"that key could not be saved"}\n`),2;const p=m.account&&(m.account.email||m.account.plan);if(n.write(`aegiscode: key saved to ${m.path}${p?` — ${p}`:""}\n`),m.error){const e=m.error.status;return o.write(`aegiscode: the account check failed: ${m.error.message}\n`),401===e||403===e?(o.write("aegiscode: the key is stored but the server refused it — re-run with a fresh key\n"),1):(o.write("aegiscode: (stored anyway — the server could not be reached to confirm it)\n"),0)}return n.write("aegiscode: verified — run `aegiscode` to start a session\n"),0}function loadAccountDeps(){const e=require("../src/credentials.js"),{readSecret:s}=require("../src/secret.js"),{maskKey:t}=require("../src/format.js");return{credentials:e,readSecret:s,maskKey:t}}function readStdin(){return new Promise(
|
|
20
|
+
*/function runProvenance(e={}){const s=require(path.join(__dirname,"..","package.json")),t=require("../src/provenance.js"),n=t.describe({version:s.version});return e.json?(process.stdout.write(JSON.stringify({product:t.IDENTITY.product,bin:t.IDENTITY.bin,version:s.version,license:t.IDENTITY.license,source:t.IDENTITY.source,homepage:t.IDENTITY.homepage,copyright:t.IDENTITY.copyright,safety:{ok:n.report.ok,checked:n.report.checked,problems:n.report.problems}},null,2)+"\n"),n.ok?0:1):(process.stdout.write(n.text),n.ok?0:1)}const ACCOUNT_COMMANDS=new Set(["login","logout","key"]);async function runAccountCommand(e,s,t={}){const n=t.stdout||process.stdout,o=t.stderr||process.stderr,r=t.stdin||process.stdin,{credentials:i,readSecret:a,maskKey:c}=loadAccountDeps();if("logout"===e||"key"===e&&["clear","remove","rm"].includes(String(s||"").toLowerCase())){const e=i.clearApiKey();return n.write(e.cleared?`aegiscode: key removed from ${e.path}\n`:"aegiscode: no saved key to remove\n"),i.legacyKeyOnDisk()&&n.write('aegiscode: note — a plaintext copy is also in config.json, written by an older AEGIS CLI; delete its "aegiscloud" block as well to finish removing it\n'),0}if("key"===e&&["status","show",""].includes(String(s||"").toLowerCase())){const e=i.keyStatus();return t.json?(n.write(JSON.stringify({configured:e.configured,source:e.source,source_label:i.sourceLabel(e.source),path:e.path,file_mode:e.fileMode,masked:e.configured?c(e.key):null,memory_token:e.memoryToken,verified_at:e.verifiedAt,plaintext_copy_in_config:e.legacyPlaintext},null,2)+"\n"),e.configured?0:1):(n.write([`key: ${e.configured?c(e.key):"not set"}`,`source: ${i.sourceLabel(e.source)}`,`file: ${e.path}${e.fileMode?` (${e.fileMode})`:""}`,"memory: "+(e.memoryToken?"token held (cloud sync ready)":"no token"),e.verifiedAt?`verified: ${e.verifiedAt}`:null,e.legacyPlaintext?"note: a plaintext copy also sits in config.json — re-save with `aegiscode login` to move it":null].filter(Boolean).join("\n")+"\n"),e.configured?0:1)}let d=s&&"status"!==s?String(s).trim():"";if(!d){if(!r.isTTY)return o.write("aegiscode: no terminal to prompt on — pass the key: `aegiscode login <api_key>`\n (or set AEGIS_API_KEY for a single run)\n"),2;d=await a("AEGIS API key (kept off screen, Enter to cancel): ",{stdin:r,stdout:n})}if(!d)return o.write("aegiscode: no key given — nothing saved\n"),2;const{createApp:l}=require("../src/app.js"),u=l({interactive:!1}),m=await u.setApiKey(d);if(!m.ok)return o.write(`aegiscode: ${m.message||"that key could not be saved"}\n`),2;const p=m.account&&(m.account.email||m.account.plan);if(n.write(`aegiscode: key saved to ${m.path}${p?` — ${p}`:""}\n`),m.error){const e=m.error.status;return o.write(`aegiscode: the account check failed: ${m.error.message}\n`),401===e||403===e?(o.write("aegiscode: the key is stored but the server refused it — re-run with a fresh key\n"),1):(o.write("aegiscode: (stored anyway — the server could not be reached to confirm it)\n"),0)}return n.write("aegiscode: verified — run `aegiscode` to start a session\n"),0}function loadAccountDeps(){const e=require("../src/credentials.js"),{readSecret:s}=require("../src/secret.js"),{maskKey:t}=require("../src/format.js");return{credentials:e,readSecret:s,maskKey:t}}function readStdin(){return new Promise(e=>{let s="";process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{s+=e}),process.stdin.on("end",()=>e(s.trim()))})}async function main(e=process.argv.slice(2)){let s;try{s=parseArgs(e)}catch(e){return process.stderr.write(`aegiscode: ${e.message}\n\n${HELP}`),2}if(s.help)return process.stdout.write(HELP),0;const t=require(path.join(__dirname,"..","package.json"));let n=!1,o=0;try{const e=require("../src/limits.js");if(n=e.armed(),n&&(o=e.refuse(),e.isPrivileged(s.command)))return o}catch{}if(s.version)return process.stdout.write(t.version+"\n"),n?o:0;try{const{resolveClientModule:e}=require("../src/shared.js"),s=require(e("env-file.js")).loadEnvFile();s.loose&&process.stderr.write(`aegiscode: ${s.file} is readable by other accounts (mode ${s.mode.toString(8)}) — consider \`chmod 600\` on it.\n`)}catch(e){process.stderr.write(`aegiscode: could not read ~/.aegiscode/.env: ${e&&e.message}\n`)}const{setCaps:r,describe:i}=require("../src/caps.js"),a={...process.env};if(!0===s.ascii&&(a.AEGIS_ART="ascii"),!1===s.ascii&&(a.AEGIS_ART="unicode"),!1===s.color&&(a.NO_COLOR="1"),!0===s.color&&(delete a.NO_COLOR,a.FORCE_COLOR="3"),s.width&&(a.AEGIS_WIDTH=String(s.width)),r(null,a),s.terminal){const e=i(),s=e.reduce((e,[s])=>Math.max(e,s.length),0);process.stdout.write(`aegiscode ${t.version} — terminal capabilities\n\n`);for(const[t,n]of e)process.stdout.write(` ${t.padEnd(s)} ${n}\n`);return process.stdout.write("\nOverride with --ascii / --color / --light / --width, or AEGIS_ART,\nAEGIS_STAR, AEGIS_COLOR, AEGIS_BACKGROUND, AEGIS_BACKGROUND_PROBE, AEGIS_VT,\nAEGIS_WIDTH (see README).\n"),0}if(s.base&&(process.env.AEGIS_API_BASE=s.base),s.key&&(process.env.AEGIS_API_KEY=s.key),"fingerprint"===s.command){const{runFingerprint:e}=require("../src/fingerprint.js");return e(s.commandArg||"status",s.commandArgv||[],{json:s.json,stdout:process.stdout,stderr:process.stderr})}if("connect"===s.command){const{runConnect:e}=require("../src/connect.js");return e(s.commandArgv||[],{json:s.json,stdout:process.stdout,stderr:process.stderr})}if("gate"===s.command){const{runGate:e}=require("../src/gate.js");return e(s.commandArg||"status",s.commandArgv||[])}if("topup"===s.command){const{runTopupCommand:e}=require("../src/topup.js");return e(s.commandArg,{json:s.json,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}if(ACCOUNT_COMMANDS.has(s.command))return runAccountCommand(s.command,s.commandArg,{json:s.json,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr});if("autonomous"===s.command){const e=require("../src/presence.js"),t=require("../src/credentials.js");e.start({credentials:t,autonomous:!0,queueDepth:e.queueDepthReader()}),process.once("exit",()=>e.stop());const{runQueueCommand:n}=require("../src/autonomous.js");return n(s.commandArg,s.commandArgv||[],{json:s.json,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}if("mcp"===s.command){const{runMcpCommand:e}=require("../src/mcp.js");return e(s.commandArg,s.commandArgv||[],{json:s.json,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}if("dream"===s.command){const{runDreamCommand:e}=require("../src/dream-cmd.js");return e(s.commandArgv||[],{stdout:process.stdout,stderr:process.stderr})}if("provenance"===s.command&&!n)return runProvenance({json:s.json});const{createApp:c}=require("../src/app.js");if(!n)try{const e=require("../src/provenance.js"),s=e.warning(e.selfCheck());s&&process.stderr.write(s)}catch{}const d=require("../src/presence.js");d.start({credentials:require("../src/credentials.js"),queueDepth:d.queueDepthReader()}),process.once("exit",()=>d.stop());let l=s.prompt;if("-"===l){if(process.stdin.isTTY)return process.stderr.write("aegiscode: -p - expects a prompt on stdin\n"),2;if(l=await readStdin(),!l)return process.stderr.write("aegiscode: empty stdin\n"),2}const u=c({model:s.model,class:s.class,stream:s.stream,light:s.light,maxTokens:s.maxTokens,...s.effort?{effort:s.effort}:{},width:s.width?()=>s.width:void 0,interactive:!l&&Boolean(process.stdin.isTTY),confirmMode:!s.yolo&&void 0,continue:s.continue});if(l)return u.runOnce(l,{json:s.json});if(!process.stdin.isTTY)return process.stderr.write('aegiscode: no terminal and no prompt. Use `aegiscode -p "question"` or pipe a prompt in.\n'),2;const m=require("../src/screen.js");m.queueExitNotice("\nResume this session with:\n aegiscode --continue (or /resume for the list)\n");const p=()=>{try{m.isAltScreen()&&m.leaveAltScreen(),m.flushExitNotice()}catch{}},h=u.runInteractive();process.once("exit",p);const g=await h;return p(),g}require.main===module&&main().then(async e=>{try{await require("../src/presence.js").flush()}catch{}process.exit(e||0)}).catch(e=>{process.stderr.write(`aegiscode: ${e&&e.message?e.message:e}\n`),process.exit(1)}),module.exports={main:main,parseArgs:parseArgs,HELP:HELP,ACCOUNT_COMMANDS:ACCOUNT_COMMANDS,runAccountCommand:runAccountCommand};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aegiscode",
|
|
3
3
|
"productName": "AEGIS Code",
|
|
4
|
-
"version": "7.0.
|
|
4
|
+
"version": "7.0.58",
|
|
5
5
|
"description": "aegiscode — the command-line version of AEGIS One. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "AEGIS Code",
|
|
@@ -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
|
-
import{readdirSync as s}from"node:fs";import{spawnSync as e}from"node:child_process";import{dirname as t,join as o,resolve as r}from"node:path";import{fileURLToPath as i}from"node:url";const c=t(i(import.meta.url)),n=r(c,".."),a=o(n,"src"),p=[o(n,"bin","aegiscode.js"),...s(a).filter(
|
|
4
|
+
import{readdirSync as s}from"node:fs";import{spawnSync as e}from"node:child_process";import{dirname as t,join as o,resolve as r}from"node:path";import{fileURLToPath as i}from"node:url";const c=t(i(import.meta.url)),n=r(c,".."),a=o(n,"src"),p=[o(n,"bin","aegiscode.js"),...s(a).filter(s=>s.endsWith(".js")).sort().map(s=>o(a,s)),o(c,"predist.mjs")];0===p.length&&(process.stderr.write("check: no files to check\n"),process.exit(1));const d=[];for(const s of p){const t=e(process.execPath,["--check",s],{stdio:"inherit"});0!==t.status&&d.push({file:s,status:t.status})}if(d.length){process.stderr.write(`\ncheck failed (${d.length}):\n`);for(const{file:s,status:e}of d)process.stderr.write(` ✗ ${s} (exit ${e})\n`);process.exit(1)}process.stdout.write(`check ok: ${p.length} files\n`);
|
|
@@ -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
|
-
import{createRequire as e}from"node:module";import n from"node:path";import{fileURLToPath as r}from"node:url";const t=e(import.meta.url),s=n.dirname(r(import.meta.url)),o=n.join(s,"..","src"),i=t(n.join(o,"render.js")),{stripAnsi:a}=t(n.join(o,"screen.js")),d=t(n.join(o,"art.js")),{version:u}=t(n.join(s,"..","package.json")),l=process.argv.slice(2),m=Number(((
|
|
4
|
+
import{createRequire as e}from"node:module";import n from"node:path";import{fileURLToPath as r}from"node:url";const t=e(import.meta.url),s=n.dirname(r(import.meta.url)),o=n.join(s,"..","src"),i=t(n.join(o,"render.js")),{stripAnsi:a}=t(n.join(o,"screen.js")),d=t(n.join(o,"art.js")),{version:u}=t(n.join(s,"..","package.json")),l=process.argv.slice(2),m=Number((()=>{const e=l.indexOf("--width");return-1===e?0:l[e+1]})())||Math.min(96,Math.max(48,process.stdout.columns||84)),c={light:l.includes("--light")},g=l.includes("--plain"),p=[],h=e=>p.push(...Array.isArray(e)?e:[e]);h(i.renderBanner(c,{width:m,version:u,model:"nexus-brain",base:"https://aegiscloud.org",key:"aegis_••••4f2a",stream:!0})),h(""),h(i.renderTurn(c,{role:"user",text:"summarise what changed in the token accounting"},m)),h(i.renderTurn(c,{role:"assistant",text:["Three things changed, and one of them was costing you money:","","- the pool **merges** worker usage instead of overwriting it","- cache reads and writes are billed, not ignored","- a zero-token call no longer refunds its reservation","","```","merge_usage({input_tokens: 1250}, {output_tokens: 312})","=> 1562 total","```","","Use `/balance` to see tokens beside € on every row."].join("\n"),meta:{model:"nexus-brain",tokens:1562,usage:{input:1250,output:312},eur:7e-4,ms:4200,calls:4}},m)),h(""),h(i.renderWorking(c,{tick:3,verb:"Consulting",elapsedMs:2100})),h(i.renderStatus(c,{model:"nexus-brain",tokens:1562,spend:7e-4,mode:"stream"},m)),process.stdout.write((g?p.map(a):p).join("\n")+"\n\n"),g||process.stdout.write(a(`${d.WELCOME_TITLE} — ${p.length} lines rendered at ${m} cols${c.light?" (light)":""}\n`));
|
|
@@ -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
|
-
import{existsSync as t}from"node:fs";import{createRequire as n}from"node:module";import{dirname as r,join as o}from"node:path";import{fileURLToPath as e}from"node:url";const i=r(e(import.meta.url));(async function(){const r=function(){const n=[o(i,"..","vendor","client","install-register.js"),o(i,"..","..","client","install-register.js"),o(i,"..","vendor","client","install-register.js")];for(const r of n)if(t(r))return r;return null}();if(!r)return;const e=n(import.meta.url)(r);await e.runPostinstall({app:"npm-postinstall"})})().catch((
|
|
4
|
+
import{existsSync as t}from"node:fs";import{createRequire as n}from"node:module";import{dirname as r,join as o}from"node:path";import{fileURLToPath as e}from"node:url";const i=r(e(import.meta.url));(async function(){const r=function(){const n=[o(i,"..","vendor","client","install-register.js"),o(i,"..","..","client","install-register.js"),o(i,"..","vendor","client","install-register.js")];for(const r of n)if(t(r))return r;return null}();if(!r)return;const e=n(import.meta.url)(r);await e.runPostinstall({app:"npm-postinstall"})})().catch(()=>{});
|
|
@@ -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
|
-
import e from"node:path";import{fileURLToPath as t,pathToFileURL as r}from"node:url";import{sealGate as s}from"./seal-gate.mjs";const a=e.dirname(t(import.meta.url)),i=e.join(a,"..","..","one","scripts","predist.mjs");async function o(e){const t=(Array.isArray(e)?e:process.argv.slice(2)).includes("--quiet")?["--quiet"]:[],a=s();if(!a.ok&&!process.env.AEGIS_ALLOW_UNSEALED)return process.stderr.write(`${a.line}\ncut: refusing to stage a package from it. Reseal the tree deliberately, or set AEGIS_ALLOW_UNSEALED=1 to stage a build that is known not to be the published one.\n`),1;let o;process.stderr.write(a.ok?`${a.line}\n`:`${a.line}\ncut: AEGIS_ALLOW_UNSEALED is set — staging anyway; this artifact will not match the published manifest.\n`);try{o=await
|
|
4
|
+
import e from"node:path";import{fileURLToPath as t,pathToFileURL as r}from"node:url";import{sealGate as s}from"./seal-gate.mjs";const a=e.dirname(t(import.meta.url)),i=e.join(a,"..","..","one","scripts","predist.mjs");async function o(e){const t=(Array.isArray(e)?e:process.argv.slice(2)).includes("--quiet")?["--quiet"]:[],a=s();if(!a.ok&&!process.env.AEGIS_ALLOW_UNSEALED)return process.stderr.write(`${a.line}\ncut: refusing to stage a package from it. Reseal the tree deliberately, or set AEGIS_ALLOW_UNSEALED=1 to stage a build that is known not to be the published one.\n`),1;let o;process.stderr.write(a.ok?`${a.line}\n`:`${a.line}\ncut: AEGIS_ALLOW_UNSEALED is set — staging anyway; this artifact will not match the published manifest.\n`);try{o=await(import(r(i).href))}catch(e){return process.stderr.write(`predist: the shared stager is not reachable at ${i}.\npredist: it lives in the repo (one/scripts/predist.mjs) and is not shipped inside the aegiscode tarball — a built package already carries its vendor tree.\n${e&&e.message||e}\n`),1}return o.main(["--mirror-only",...t])}process.argv[1]&&e.resolve(process.argv[1])===t(import.meta.url)&&(process.exitCode=await o(process.argv.slice(2)));export{o as main,s as sealGate};
|
|
@@ -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
|
-
import{readdirSync as s}from"node:fs";import{spawnSync as t}from"node:child_process";import{dirname as e,join as o,resolve as r}from"node:path";import{fileURLToPath as n}from"node:url";const i=r(e(n(import.meta.url)),"..","..","test"),a=s(i).filter(
|
|
4
|
+
import{readdirSync as s}from"node:fs";import{spawnSync as t}from"node:child_process";import{dirname as e,join as o,resolve as r}from"node:path";import{fileURLToPath as n}from"node:url";const i=r(e(n(import.meta.url)),"..","..","test"),a=s(i).filter(s=>/^cli-.*\.test\.mjs$/.test(s)).sort();0===a.length&&(process.stderr.write(`no cli-*.test.mjs found in ${i}\n`),process.exit(1));const c=[],p=[],l=["AEGIS_REDUCED_MODE","AEGIS_SKIP_PERMISSIONS","AEGISONE_SKIP_PERMISSIONS","AEGIS_NO_PROVENANCE_CHECK","AEGIS_SKIP_PROVENANCE","AEGIS_NO_INTERLOCK"],E={...process.env};for(const s of l)delete E[s];for(const s of a){const e=o(i,s);process.stdout.write(`\n── ${s} ${"─".repeat(Math.max(0,60-s.length))}\n`);const r=t(process.execPath,[e],{stdio:"inherit",env:E});0===r.status?p.push(s):c.push({f:s,status:r.status,signal:r.signal})}if(process.stdout.write(`\n${"═".repeat(64)}\n`),process.stdout.write(`cli suite: ${p.length}/${a.length} files passed\n`),c.length){process.stdout.write(`\nFAILED (${c.length}):\n`);for(const{f:s,status:t,signal:e}of c)process.stdout.write(` ✗ ${s}${e?` (signal ${e})`:` (exit ${t})`}\n`);process.exit(1)}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const readline=require("node:readline"),os=require("node:os"),{randomUUID:randomUUID}=require("node:crypto"),{createTools:createTools,createClient:createClient,usageTokens:usageTokens,usageBuckets:usageBuckets,buildSystemPrompt:buildSystemPrompt,autoProvisionApiKey:autoProvisionApiKey,provisionFailureText:provisionFailureText,trialNote:trialNote,hostEnv:hostEnv,autonomous:autonomous,claudePro:claudePro}=require("./deps.js"),{createEngine:createEngine,HOST_CLASSES:HOST_CLASSES,DEFAULT_CLASS:DEFAULT_CLASS,byokNamespace:byokNamespace,effortRung:effortRung,offeredClasses:offeredClasses,proEnabled:proEnabled}=require("./engine.js"),{GLYPH:GLYPH,VERBS:VERBS,themeOf:themeOf,RESET:RESET,THEME_TABLE:THEME_TABLE,AUTO_THEME_INDEX:AUTO_THEME_INDEX,themeIsLight:themeIsLight,reconcileThemeIndex:reconcileThemeIndex}=require("./theme.js"),{probeTerminalBackground:probeTerminalBackground}=require("./caps.js"),{LiveRegion:LiveRegion,termWidth:termWidth,w:w}=require("./screen.js"),{estimateTokensFromCells:estimateTokensFromCells}=require("./tokens.js"),{editPreview:editPreview}=require("./diff.js"),{defaultOpen:defaultOpen}=require("./diffview.js"),{parseLine:parseLine,COMMANDS:COMMANDS,visibleCommands:visibleCommands,runAutoModelSync:runAutoModelSync}=require("./commands.js"),{updateConfig:updateConfig,loadPermissions:loadPermissions,loadConfig:loadConfig,configExists:configExists,memoryPersistState:memoryPersistState,memoryPersistEnabled:memoryPersistEnabled,setMemoryPersist:setMemoryPersist,confirmPosture:confirmPosture,permissionMode:permissionMode}=require("./config.js"),credentials=require("./credentials.js"),events=require("./events.js"),cloudsync=require("./cloudsync.js"),{readSecret:readSecret}=require("./secret.js"),{normalizeModelCatalog:normalizeModelCatalog,pickerEntries:pickerEntries,catalogIds:catalogIds,providerForModel:providerForModel,withAutoRow:withAutoRow,AUTO_MODEL_ID:AUTO_MODEL_ID}=require("./models.js"),{appendHistory:appendHistory,readSessionTranscript:readSessionTranscript,readOwnSessions:readOwnSessions,setSessionTitle:setSessionTitle}=require("./history.js"),naming=require("./naming.js"),{snapshotCheckpoint:snapshotCheckpoint}=require("./checkpoint.js"),screens=require("./screens.js"),chatflow=require("./chatflow.js"),overlays=require("./overlays.js"),render=require("./render.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,maskKey:maskKey,feeBillable:feeBillable}=require("./format.js"),{resolveSkip:resolveSkip}=require("./permissions.js"),VERSION=require("../package.json").version;let _defaultSystem=null;function defaultSystemPrompt(){if(null===_defaultSystem)try{_defaultSystem=buildSystemPrompt(hostEnv({},{},null))}catch{_defaultSystem=""}return _defaultSystem||void 0}function normalizeDecision(e){const t="string"==typeof e?e.trim().toLowerCase():"";return"session"===t?"session":"once"===t||"allow"===t||"yes"===t||"approve"===t||"approved"===t?"once":"deny"}const PROVIDER_REFUSAL_PATTERNS=Object.freeze([/^invalid api key\b/i,/^fix external api key\b/i,/^you've hit your session limit\b/i,/^you have hit your session limit\b/i,/^provider request timed out\b/i,/^insufficient (?:credit|balance|quota)\b/i,/^rate limit(?:ed)?\b/i,/^unauthorized\b/i]);function providerRefusal(e,t){if("string"!=typeof e)return null;const n=t&&(t.total_tokens||0),r=t&&(t.output_tokens||t.completion_tokens||0);if(n>0||r>0)return null;const o=e.trim();if(!o||o.length>160||o.includes("\n"))return null;for(const e of PROVIDER_REFUSAL_PATTERNS)if(e.test(o))return o;return null}function briefArgs(e){let t;try{t="string"==typeof e?e:JSON.stringify(e??"")}catch{t=String(e)}return t=String(t).replace(/\s+/g," ").trim(),t.length>140?`${t.slice(0,137)}...`:t}function createApp(e={}){const t={model:null,stream:!0,light:!1,maxTokens:void 0,system:void 0,interactive:!0,...e},n=e.out||process.stdout,r=e.err||process.stderr,o=e.client||createClient(credentials.clientOptions({channel:"cli"})),{TOOLS:s,toolList:i}=e.tools||createTools(o);let a=!1,l="";async function c(){const e=await autoProvisionApiKey(o,credentials,{app:"cli"});return l=e.key?"":provisionFailureText(e),e}async function d(){if(o.apiKey||a)return;a=!0;const e=await c();e.key&&Y(render.renderNotice(b(),"info","auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.`))}let u=!1!==e.confirmMode,m=(()=>{try{return autonomous.autoRoundsDefault(process.env)}catch{return!0}})();const f=e.engine||createEngine({client:o,getClass:()=>g.modelClass,getProEnabled:()=>{try{return proEnabled(loadConfig())}catch{return!1}},getConfirmMode:()=>{if(void 0!==e.confirmMode)return u;try{const e=resolveSkip({env:process.env,interactive:Boolean(process.stdin.isTTY&&process.stdout.isTTY)});if(e.warned&&!skipEnvWarned&&(skipEnvWarned=!0,process.stderr.write(`aegiscode: ${e.warning}\n`)),e.skip)return!1}catch{}try{return confirmPosture().enabled}catch{return u}},getPermissionMode:()=>{try{return permissionMode()}catch{return null}}}),p=e=>"function"==typeof f.classLabel?f.classLabel(e):String(e||"");let y=null;const h=()=>e.width?e.width():termWidth(),g={light:t.light,model:t.model,modelClass:DEFAULT_CLASS,effort:null,thinking:!1,recallDeep:!1,themeIndex:t.light?2:AUTO_THEME_INDEX,vim:!1,stream:t.stream,cwd:process.cwd(),lastRecap:null,sessionId:randomUUID()};g.themeIndex===AUTO_THEME_INDEX&&(g.light=themeIsLight(AUTO_THEME_INDEX));const k=[];let v=!1;const b=()=>({light:g.light}),S={turns:0,calls:0,tokens:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,cost:0,balance:null,seenLedgerRows:new Map,ledgerBaselined:!1,startedAt:Date.now()};let T=null,E=!1;function C(e){if(!e||"object"!=typeof e)return null;if("usage"!==e.kind)return null;const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6;return Number.isFinite(t)?Math.abs(t):null}function I(e){return[e.created_at||"",e.kind||"",null!=e.amount_eur?e.amount_eur:"",null!=e.charged_micros?e.charged_micros:"",null!=e.id?e.id:"",null!=e.note?e.note:""].join("|")}async function N(){try{const e=await o.tokenBankBalance(),t=Number(e.balance_eur);Number.isFinite(t)&&(S.balance=t);let n=null;const r=Array.isArray(e.ledger)?e.ledger:[],s=new Map;for(const e of r){const t=I(e),n=s.get(t);n?n.n+=1:s.set(t,{n:1,row:e})}for(const[e,{n:t,row:r}]of s){const o=S.seenLedgerRows.get(e)||0;if(S.seenLedgerRows.set(e,t),!S.ledgerBaselined)continue;const s=t-o;if(s<=0)continue;const i=C(r);null!=i&&i>0&&(S.cost+=i*s,null==n&&(n=i))}return S.ledgerBaselined=!0,{balance:S.balance,lastCost:n}}catch{return null}}async function A(e,{verify:t=!0}={}){const n=credentials.saveApiKey(e);if(!n.ok)return n;o.setApiKey(n.key),R.models=[],R.at=0;let r=null,s=null;if(t)try{const e=await o.verifyApiKey()||{};r=e;const t={verifiedAt:(new Date).toISOString()};e.memory_token&&(t.memoryToken=e.memory_token),e.plan&&(t.plan=e.plan),t.account={plan:e.plan||null,email:e.email||null,valid:!1!==e.valid},credentials.writeCredentials(t),e.plan&&(S.plan=e.plan),e.email&&(S.account={...S.account||{},email:e.email})}catch(e){s=e}return{...n,account:r,error:s}}function P(){const e=credentials.clearApiKey();return o.setApiKey(""),R.models=[],R.at=0,e}function x(){try{return memoryPersistEnabled()}catch{return!0}}function M(){try{return memoryPersistState()}catch{return{enabled:!0,source:"default",explicit:!1}}}function O(e){return setMemoryPersist(e)}function L(){try{return"config"!==credentials.resolveApiKey().source?[]:credentials.adoptLegacy().adopted}catch{return[]}}const _=3e5,R={at:0,models:[]},$={at:0,models:[],declared:""};async function K({force:e=!1}={}){const t=function(){try{if("function"!=typeof f.userModels)return"";const e=(f.userModels()||{}).map||{};return JSON.stringify(Object.keys(e).sort().map((t=>[t,e[t]])))}catch{return""}}(),n=$.models.length&&Date.now()-$.at<_&&t===$.declared;if(!e&&n)return $.models;if("function"!=typeof f.listModels)return[];const r=await f.listModels("byok");return $.models=(r&&r.models||[]).map((e=>({...e,note:e.configured?"key on this machine":`no key — /byok-key ${e.provider}`}))),$.at=Date.now(),$.declared=t,$.models}async function D(e){const t=U();if(e&&!t.includes(e)&&HOST_CLASSES.includes(e))return[];const n=t.includes(e)?e:g.modelClass;try{if("byok"===n){const e=await K();if(!R.models.length)try{await H()}catch{}return q(e,n)}if("pro"===n){const e=await f.listModels("pro");return(e&&e.models||[]).map((e=>({...e,cls:"pro"})))}if("aegis"!==n){const e=await f.listModels(n);return e&&e.models||[]}return await H()}catch{return[]}}function j(){return withAutoRow(pickerEntries(R.models)).map((e=>({...e,cls:"aegis"})))}function q(e,t){const n=U(),r=n.includes(t)?t:g.modelClass;if("pro"===t&&!n.includes("pro"))return[];if("pro"===r)return pickerEntries(claudePro.PRO_MODELS.map((e=>({id:e.id,label:e.label,note:e.note})))).map((e=>({...e,cls:"pro"})));if("byok"!==r)return j();const o=Array.isArray(e)?e.map((e=>({...e,cls:"byok"}))):pickerEntries($.models).map((e=>({...e,cls:"byok"})));return[...j(),...o]}function B(){return new Set(claudePro.PRO_MODELS.map((e=>String(e.id).toLowerCase())))}function U(){try{return offeredClasses(proEnabled(loadConfig()))}catch{return offeredClasses(!1)}}async function H({force:e=!1}={}){const t=R.models.length&&Date.now()-R.at<_;if(!e&&t)return R.models;const n=await o.listModels();return R.models=normalizeModelCatalog(n&&n.models),R.at=Date.now(),R.models}async function F(){const e=g.model;if(!e)return null;if("byok"===g.modelClass)return String(e).includes(":")?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" belongs to the pooled class — on BYOK an id is "<provider>:<model>"; pin cleared, /models lists what this machine can relay.`)),e);if("pro"===g.modelClass){if(!B().has(String(e).toLowerCase()))return g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" is not one the Claude Code CLI resolves — pin cleared, the CLI will choose; /models lists the aliases (${claudePro.PRO_MODELS.map((e=>e.id)).join(", ")}).`)),e;let t=!0;try{t=!!claudePro.claudeProStatus({env:process.env}).credentialPresent}catch{t=!0}return t?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" needs a Claude Pro subscription or an ANTHROPIC_API_KEY, and this host has neither — pin cleared. Run \`claude /login\`, export a console key, or \`/class pro off\`.`)),e)}let t;try{t=await H()}catch{return null}return t.length?String(e).trim().toLowerCase()===AUTO_MODEL_ID||catalogIds(t).has(String(e).toLowerCase())?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" is not advertised by AEGIS Cloud — pin cleared, the pool will choose; /models lists what you can pin.`)),e):null}function W(){return render.renderBanner(b(),{width:h(),version:VERSION,model:g.model||"server default",base:o.apiBase,key:maskKey(o.apiKey),stream:g.stream})}function Y(e){const t="string"==typeof e?[e]:e;for(const e of t)n.write(e+"\n")}async function V(e,{history:o=[],presenter:s=null,signal:i=null}={}){const a=Date.now(),l=!s&&t.interactive&&t.stream&&n.isTTY?new LiveRegion(n):null;let c=0,d=0,u="",m=0,p=0,k=VERBS[Math.floor(Math.random()*VERBS.length)],v=!1,S=!1;const E=()=>{l&&l.update([render.renderWorking(b(),{tick:c++,verb:k,elapsedMs:Date.now()-a,streamed:estimateTokensFromCells(d+m)+p,streamedFloor:p>0})])},C=l?setInterval(E,90):null;C&&C.unref&&C.unref(),E();const I=s||{},N=new Map,A=randomUUID();T=A;let P=!1;const x=()=>{P=!0,f.cancel(A)},M=()=>x();process.once("SIGINT",M),i&&(i.aborted?x():i.addEventListener("abort",x,{once:!0}));const O=e=>(r.write(`aegiscode: ${e.tool} needs confirmation but this run has no prompt for it — denied (pass --automode (alias --yolo) to auto-approve mutating tools).\n`),Promise.resolve("deny")),L=()=>Promise.resolve(!1),_=e=>{if(e){if(e.thinkingTokens&&(p+=e.thinkingTokens,v||(v=!0,k="Reasoning"),(e=>{I.thinkingTokens&&I.thinkingTokens(e)})(e.thinkingTokens),E()),e.reasoning&&(m+=w(e.reasoning),v||(v=!0,k="Reasoning",E()),(e=>{I.reasoning&&I.reasoning(e)})(e.reasoning)),e.delta&&(d+=w(e.delta),u+=e.delta,(e=>{if(I.text)return I.text(e);l&&c%2==0&&E()})(e.delta)),e.tool&&(S=!0,(e=>{if(I.tool)return I.tool(e);l&&l.clear();const t=(e=>{const t=e&&void 0!==e.id?`id:${e.id}`:`${e&&e.name}:${JSON.stringify(e&&e.args)}`;return N.has(t)||N.set(t,editPreview(e&&e.name,e&&e.args,{cwd:process.cwd()})),N.get(t)})(e);Y(render.renderTurn(b(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:defaultOpen(t)},h())),E()})(e.tool)),e.approval){const t=e.approval;l&&l.clear();const n=I.approval||y||O;Promise.resolve(n(t)).catch((()=>"deny")).then((e=>f.respondApproval(t.id,normalizeDecision(e))))}if(e.rounds){const t=e.rounds;l&&l.clear();const n=I.rounds||L;Promise.resolve(n(t)).catch((()=>!1)).then((e=>f.respondRoundsAsk(t.id,!0===e)))}}};try{const n=await f.chat({prompt:e,messages:o,model:g.model||void 0,system:t.system||defaultSystemPrompt(),maxTokens:t.maxTokens,effort:effortRung(g.effort),recallDeep:!0===g.recallDeep||void 0,stream:!1!==g.stream,sessionId:A,sessionKey:g.sessionId,rootSessionId:g.sessionId,roundsAsk:Boolean(I.rounds)},_),r=n.choices&&n.choices[0]||{};return{text:r.message&&r.message.content||u,usage:n.usage||null,model:n.model||g.model||null,ms:Date.now()-a,interrupted:P,reasoningChars:m,usedTools:S}}catch(e){if(P&&u)return{text:u,usage:null,model:g.model||null,ms:Date.now()-a,interrupted:!0,reasoningChars:m,usedTools:S};throw e}finally{C&&clearInterval(C),process.removeListener("SIGINT",M),i&&i.removeEventListener("abort",x),l&&l.clear(),T=null}}function G(e){Y(render.renderTurn(b(),e,h()))}async function z(e,{label:t="you"}={}){if(!e)return void Y(render.renderNotice(b(),"warn","nothing to ask — give /ask a prompt"));if(o.apiKey||await d(),!o.apiKey)return void Y(render.renderNotice(b(),"error",`no AEGIS account key — ${credentials.HOW_TO_SET} (or set $${credentials.KEY_ENV})`));const n=k.filter((e=>"user"===e.role||"assistant"===e.role)).map((e=>({role:e.role,content:e.text})));let r;G({role:"user",text:e,label:t}),k.push({role:"user",text:e});try{r=await V(e,{history:n})}catch(t){return ae(e,{text:"",error:t.message},"error"),void Y(render.renderTurn(b(),{role:"error",text:t.message},h()))}r.text&&k.push({role:"assistant",text:r.text});const s=ie(r);let i=null;try{const e=await N();i=e?e.lastCost:null}catch{}ae(e,r,r.interrupted?"stopped":r.error?"error":"done",i),G({role:"assistant",text:r.text||"(the pool returned no text — see /balance for what it charged)",meta:{model:r.model,tokens:s,usage:null==r.usage?null:usageBuckets(r.usage),eur:i,ms:r.ms,calls:1}}),r.interrupted&&Y(render.renderNotice(b(),"warn","interrupted — the pool may still be running and billing this call"))}async function X(e,t){const n=s[e];if(!n)throw new Error(`unknown tool: ${e}`);if(o.apiKey||await d(),!o.apiKey)throw new Error(`no AEGIS account key — ${credentials.HOW_TO_SET}`);const r=await n.run(t||{});Y(render.renderToolResult(b(),e,r,h()))}function J(e){const t=String(e||"").toLowerCase();if(!t)return null;let n=null;for(const e of COMMANDS)for(const r of[e.name,...e.aliases||[]])r!==t&&(r.startsWith(t)||t.startsWith(r))&&(null==n||Math.abs(r.length-t.length)<Math.abs(n.length-t.length))&&(n=r);return n}function Q(){const e=loadPermissions(),t=confirmPosture();return{version:VERSION,model:g.model||"server default",class:g.modelClass,effort:g.effort,thinking:g.thinking,theme:g.light?"light":"dark",themeIndex:g.themeIndex,vim:g.vim,stream:g.stream,cwd:g.cwd,home:os.homedir(),sessionId:g.sessionId,base:o.apiBase,keyMask:maskKey(o.apiKey),online:!!o.apiKey,turns:S.turns,calls:S.calls,startedAt:S.startedAt,tokens:{input:S.inputTokens,output:S.outputTokens,cacheRead:S.cacheReadTokens,cacheWrite:S.cacheWriteTokens,total:S.tokens},costEur:S.cost,balance:S.balance,plan:S.plan||null,account:S.account||null,permissions:{mode:t.enabled?e.defaultMode:"allow",confirm:t.enabled,source:t.source,rules:e},models:q(),commands:visibleCommands(),transcript:k.slice(),sessions:[],memory:{},lastRecap:g.lastRecap,backend:g.modelClass,url:o.apiBase}}function Z(e){return Array.isArray(e)?e.map((e=>e&&(e.s||"")+(null==e.t?"":e.t)||"")).join(""):String(null==e?"":e)}function ee(e){if(!e||"object"!=typeof e)return;const t=h();switch(e.role){case"panel":{const t=Array.isArray(e.lines)?e.lines:[];for(const e of t)Y(Z(e));return}case"note":case"tip":return void Y(render.renderNotice(b(),"info",e.text));case"done":return void Y(render.renderNotice(b(),"ok",e.text));case"error":return void Y(render.renderNotice(b(),"error",e.text));case"user":return void Y(render.renderTurn(b(),{role:"user",text:e.text,label:e.label},t));case"assistant":return void Y(render.renderTurn(b(),{role:"assistant",text:e.text},t));case"tool":return void 0===e.diff&&(e.diff=editPreview(e.name||e.label,e.args,{cwd:process.cwd()}),e.diffOpen=defaultOpen(e.diff)),void Y(render.renderTurn(b(),{role:"tool",label:e.label||e.name,args:e.args,ok:e.ok,diff:e.diff,diffOpen:!!e.diffOpen},t));default:return void Y(render.renderNotice(b(),"info",null==e.text?"":String(e.text)))}}function te(e){return{t:e,s:"",w:w(e)}}async function ne(){return!e.readline&&process.stdin.isTTY&&process.stdout.isTTY&&!1!==e.chatflow?screens.showThemePicker(g):(g.light=!g.light,g.themeIndex=g.light?2:1,Y(render.renderNotice(b(),"ok","theme: "+(g.light?"light":"dark"))),g.themeIndex)}function re(){const e={ctx:g,transcript:k,push:e=>ee(e),note:e=>ee({role:"note",text:e}),panel:e=>ee({role:"panel",lines:e}),render:()=>{},openOverlay:e=>function(e){if(!e||"object"!=typeof e)return;const t=h(),n=Math.max(5,process.stdout&&process.stdout.rows||24);let r=null;if("panel"===e.type?r=e.lines:"palette"===e.type?r=overlays.renderPalette(visibleCommands(),{query:e.query||"",sel:e.sel||0},t,n):"model"===e.type?r=overlays.renderModelPicker(e.items||[],e.sel||0,t,n,null!=e.current?e.current:g.model,e.cls||g.modelClass,p):"effort"===e.type?r=overlays.renderEffortPicker(e.sel||0,t,g.effort):"class"===e.type?r=overlays.renderClassPicker(e.items||[],e.sel||0,t,e.current||g.modelClass,p):"provider"===e.type?r=overlays.renderProviderPicker(e.items||[],e.sel||0,t,e.current,e.hint):"resume"===e.type?r=overlays.renderResumeList(e.items||[],e.sel||0,t,n):"confirm"===e.type&&(r=render.renderApproval(b(),e.info||{},t).map((e=>[te(e)]))),r)for(const e of r)Y(Z(e))}(e),closeOverlay:()=>{},setAutoRounds:e=>{m=Boolean(e)},askInput:()=>Promise.resolve(null),withWorking:e=>async function(e){const r=new AbortController,o=t.interactive&&n.isTTY?new LiveRegion(n):null;let s=null;if(o){let e=0;const t=Date.now(),n=()=>o.update([render.renderWorking(b(),{tick:e++,verb:VERBS[0],elapsedMs:Date.now()-t})]);n(),s=setInterval(n,90),s.unref&&s.unref()}try{return await e(r.signal)}finally{s&&clearInterval(s),o&&o.clear()}}(e),runPrompt:e=>z(e),ask:e=>V(e),runTool:(e,t)=>X(e,t),loadModels:()=>D(g.modelClass),settings:()=>f.settings||null,byokNamespace:e=>byokNamespace(e),listModelsFor:e=>D(e),refreshByokModels:()=>K({force:!0}),switchClass:e=>function(e){const t=String(null==e?"":e).trim().toLowerCase(),n=U();if(!n.includes(t))return"pro"===t?{ok:!1,error:"the pro class (your Claude Code subscription) is off by default — enable it once with `/class pro on`"}:{ok:!1,error:`unknown class "${e}" — classes: ${n.join(", ")}`};const r=g.modelClass;g.modelClass=t;let o=null;return r!==t&&g.model&&(function(e,t){const n=String(null==t?"":t);return"byok"===e?n.includes(":"):"pro"===e?B().has(n.toLowerCase()):!n.includes(":")}(t,g.model)||(o=g.model,g.model=null)),updateConfig({modelClass:t,model:g.model,currentModelId:g.model}),{ok:!0,class:t,prev:r,cleared:o}}(e),classLabel:e=>p(e),classes:()=>"function"==typeof f.listClasses?f.listClasses():[],refreshSpend:()=>N(),state:()=>Q(),setInput:()=>{},exit:()=>{v=!0},client:o,TOOLS:s,saveConfig:e=>updateConfig(e),showThemePicker:()=>ne(),keyStatus:()=>credentials.keyStatus(),setApiKey:(e,t)=>A(e,t),forgetApiKey:()=>P(),registerAccount:()=>async function(){return o.apiKey?{alreadyKeyed:!0}:c()}(),readSecret:e=>readSecret(e,{stdin:process.stdin,stdout:n}),cloudsync:cloudsync,cloudSyncEnabled:()=>x(),cloudSyncState:()=>M(),setCloudSync:e=>O(e),adoptLegacyKey:()=>L()};return Object.defineProperty(e,"sessionId",{enumerable:!0,get:()=>g.sessionId,set:e=>{g.sessionId=e}}),e.clearConversationMemory=()=>{f&&"function"==typeof f.clearSessionApprovals&&f.clearSessionApprovals(g.sessionId)},e.listUndoable=()=>f&&"function"==typeof f.listUndoable?f.listUndoable(g.sessionId):[],e.undoMutation=e=>f&&"function"==typeof f.undoMutation?f.undoMutation(g.sessionId,e):{ok:!1,error:"undo is not available on this engine"},e}async function oe(e,t=null){const r=parseLine(e);if("empty"===r.kind)return!0;if("prompt"===r.kind)return await z(r.text),!0;if("unknown"===r.kind){const e=J(r.name);return Y(render.renderNotice(b(),"error",`unknown command: /${r.name}${e?` — did you mean /${e}?`:" — try /help"}`)),!0}if("unavailable"===r.kind){const e=r.command;if(Y(render.renderNotice(b(),"warn",`/${e.name} is not available in aegiscode — ${e.unavailable}`)),e.alt)Y(render.renderNotice(b(),"info",`try ${e.alt} instead`));else{const t=J(e.name);t&&Y(render.renderNotice(b(),"info",`try /${t} instead`))}return!0}const s=r.command,i=r.arg;if(s.generic){let t;try{t=s.build(i)}catch(e){return Y(render.renderNotice(b(),"error",e.message)),!0}const{tool:n,args:r}=t;if(!n)return Y(render.renderNotice(b(),"error","/tool needs a tool name — see /help")),!0;try{await X(n,r)}catch(e){Y(render.renderNotice(b(),"error",e.message))}return!0}if("function"==typeof s.handler){const n=function(e,t){const n=String(null==t?"":t),r=Array.isArray(e.args)?e.args:[],o=function(e){const t=[];let n="",r=null,o=!1;for(const s of String(e||""))r?s===r?r=null:n+=s:'"'!==s&&"'"!==s?/\s/.test(s)?(n||o)&&(t.push(n),n="",o=!1):(n+=s,o=!0):(r=s,o=!0);return(n||o)&&t.push(n),t}(n),s={_rest:n.trim()};return r.forEach(((e,t)=>{void 0!==o[t]&&(s[e]=o[t])})),s}(s,i),r=t||re();try{return!1!==await s.handler(r,n)}catch(e){return Y(render.renderNotice(b(),"error",e&&e.message?e.message:String(e))),!0}}try{let e=s.build(i);if(s.secret){const t=await async function(e,t){if("function"!=typeof e.secretDescribe)return null;try{const n=await e.secretDescribe(t,o);return n&&"object"==typeof n?n:null}catch{return null}}(s,e);if(t&&t.note&&Y(render.renderNotice(b(),"info",t.note)),t&&null===t.prompt)return!0;t&&t.provider&&(e={...e,provider:t.provider});const r=await function(e){const t=themeOf(b());return readSecret(t.gray+e+RESET,{stdin:process.stdin,stdout:n})}(t&&t.prompt||`provider key for ${e.provider}: `);if(!r)return Y(render.renderNotice(b(),"warn","empty key — nothing sent")),!0;e={...e,api_key:r}}if("aegis_ask"===s.tool)return await z(e.prompt);await X(s.tool,e),"aegis_memory_list"!==s.tool&&"aegis_memory_search"!==s.tool||function(){let e;try{e=cloudsync.status()}catch{return}const t=e.quota;if(!t)return;const n=fmtTokens(t.used||0),r=fmtTokens(t.limit||0);e.overQuota?Y(render.renderNotice(b(),"warn",`cloud memory: ${n} of ${r} synced tokens — at the plan's ceiling. Everything stored stays readable; new writes are paused until there is room. /cloud memory for the full state.`)):Y(render.renderNotice(b(),"info",`cloud memory: ${n} of ${r} synced tokens — /cloud memory for the full state`))}()}catch(e){Y(render.renderNotice(b(),"error",e.message))}return!0}async function se(){if(f&&"function"==typeof f.unloadLocalModels)try{await f.unloadLocalModels()}catch{}}function ie(e){S.turns++,S.calls+=Number(e&&e.calls||1)||1;const t=e&&e.usage,n=usageTokens(t);if(null!=n){S.tokens+=n;const e=usageBuckets(t);S.inputTokens+=e.input,S.outputTokens+=e.output,S.cacheReadTokens+=e.cacheRead,S.cacheWriteTokens+=e.cacheWrite}return n}function ae(e,t,n="done",r=null){try{const o=t&&t.usage,s="number"==typeof r&&Number.isFinite(r)?r:null,i=String(t&&t.model||g.model||"").trim();appendHistory({sessionId:g.sessionId,prompt:e,reply:t&&t.text||"",status:n,model:i||void 0,provider:i&&providerForModel({id:i,cls:g.modelClass})||void 0,usage:o?{...usageBuckets(o),...null!=s?{costUsd:s}:{}}:null!=s?{input:0,output:0,cacheRead:0,cacheWrite:0,costUsd:s}:null}),snapshotCheckpoint(g.sessionId,k)}catch{}x()&&o.apiKey&&Promise.resolve().then((()=>cloudsync.push(o))).then((e=>{if(e&&e.failed&&e.failed.length){const t=e.failed[0];if(le.has(t.kind))return;if(le.add(t.kind),"quota"===t.kind)return void Y(render.renderNotice(b(),"warn","cloud memory: the plan's synced-token ceiling is reached — earlier sessions stay readable, only NEW writes pause. /cloud memory shows the quota; /cloud memory off stops trying."));const n=t.hint?` — ${t.hint}`:"";Y(render.renderNotice(b(),"error",`cloud sync: ${t.message}${n}`))}})).catch((()=>{}))}let le=new Set;function ce(){const e=[S.outputTokens>0?`${fmtTokens(S.outputTokens)} tokens`:`${fmtTokens(S.tokens)} tokens`,`${S.calls} call${1===S.calls?"":"s"}`];return feeBillable()&&(e.push(fmtEur(S.cost)),null!=S.balance&&e.push(`balance ${fmtEur(S.balance)}`)),e.join(" · ")}async function de(e){if(!e||!e.id)return;const t=readSessionTranscript(e.id);if(t.length){k.length=0;for(const e of t)k.push(e);g.sessionId=e.id,Y(render.renderNotice(b(),"ok",`resumed ${e.id} — ${t.length} turn(s)`))}else Y(render.renderNotice(b(),"warn",`no stored turns for ${e.id}`))}function ue(){return{ctx:g,version:VERSION,transcript:k,session:S,client:o,TOOLS:s,ask:(e,t)=>V(e,t),makeCommandContext:()=>re(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=f.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},loadModels:e=>H(e),buildState:()=>Q(),dispatchLine:(e,t)=>oe(e,t),refreshSpend:()=>N(),updateConfig:e=>updateConfig(e),showThemePicker:()=>ne(),persistTurn:(e,t,n,r)=>ae(e,t,n,r),nameConversation:(e,t)=>async function(e,{signal:t=null}={}){const n=await naming.nameConversation(e,{signal:t,callModel:(e,n)=>V(e,{system:n&&n.system||naming.TITLE_SYSTEM,maxTokens:64,signal:n&&n.signal||t}).then((e=>e&&e.text||null))}),r=String(n||"").trim();return r&&setSessionTitle(g.sessionId,r),r}(e,t),visibleCommands:()=>visibleCommands(),tokensFor:e=>usageTokens(e),recordTurn:e=>ie(e),tokenSummary:()=>ce(),resumeSession:e=>de(e),requestExit:()=>{v=!0},wantsExit:()=>v,keyNotice:()=>o.apiKey?"":l,isYolo:()=>{if(!m)return!1;try{return!1===confirmPosture().enabled}catch{return!1}},setAutoRounds:e=>{m=Boolean(e)}}}async function me(){Y(W()),await N(),n.write("\n");const t=e.readline||readline.createInterface({input:process.stdin,output:n,terminal:!0}),r=themeOf(b()).gold+GLYPH.cursor+" "+RESET;return t.setPrompt(r),t.prompt(),new Promise((e=>{t.on("line",(async e=>{t.pause();let n=!0;try{n=await oe(e)}catch(e){Y(render.renderNotice(b(),"error",e.message))}if(!n||v)return E=!0,void t.close();t.resume(),t.prompt()})),t.on("close",(()=>{E||n.write("\n"),e(0)}))}))}function fe(){if(e.readline)return;if(!configExists())return;let n;try{n=loadConfig()}catch{return}if(U().includes(n.modelClass)&&(g.modelClass=n.modelClass),t.class){const e=String(t.class).trim().toLowerCase();if(!U().includes(e))throw new Error(`--class ${t.class}: not available on this host (offered: ${U().join(", ")})`);g.modelClass=e}if(!t.model&&n.model&&(g.model=n.model),g.effort=effortRung(t.effort||n.effort),"boolean"==typeof n.vim&&(g.vim=n.vim),n.lastRecap&&(g.lastRecap=n.lastRecap),!t.light&&"number"==typeof n.themeIndex&&THEME_TABLE[n.themeIndex]){g.themeIndex=n.themeIndex,g.light=themeIsLight(n.themeIndex);const e=reconcileThemeIndex(g.themeIndex);if(e.changed){g.themeIndex=e.index,g.light=themeIsLight(e.index),g.themeNotice=e.reason;try{updateConfig({themeIndex:e.index,light:themeIsLight(e.index)})}catch{g.themeNotice+=" (could not save it)"}}}}return{opts:t,session:S,client:o,TOOLS:s,toolList:i,ctx:g,transcript:k,ask:V,runPrompt:z,handleLine:oe,runOnce:async function(e,t={}){try{return await async function(e,{json:t=!1}={}){if(fe(),L(),!o.apiKey&&!a){a=!0;const e=await autoProvisionApiKey(o,credentials,{app:"cli"});e.key&&r.write("aegiscode: auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.\n`)}if(!o.apiKey)return r.write(`aegiscode: no AEGIS account key. ${credentials.HOW_TO_SET}, or set $${credentials.KEY_ENV}.\n`),2;await N();const s=[],i=[],l=t?{tool:e=>{if("done"===(e&&e.phase)){const t=e.id&&i.find((t=>t.id===e.id&&!0!==t.settled))||(e.id?null:i[i.length-1]);t?(t.settled=!0,t.ok=!1!==e.ok):(e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!0,ok:!1!==e.ok}))}else e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!1,ok:null});const t=e&&void 0!==e.preview?e.preview:null,n=render.renderTurn(b(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:!1},h());for(const e of Array.isArray(n)?n:[n])r.write(e+"\n")}}:null,c=await V(e,l?{presenter:l}:{});await N();const d=usageTokens(c.usage),u=providerRefusal(c.text,c.usage);if(t)n.write(JSON.stringify({text:c.text,model:c.model,class:g.modelClass,rounds:c.usage&&Number(c.usage.calls)||null,usage:c.usage,reasoning_chars:"number"==typeof c.reasoningChars?c.reasoningChars:null,tokens:d,ms:c.ms,interrupted:c.interrupted,...s.length?{tools:s}:{},...i.length?{tool_log:i}:{},...u?{error:u}:{},balance_eur:S.balance},null,2)+"\n");else if(n.write(c.text+"\n"),u&&r.write(`aegiscode: the provider refused this turn — ${u}\n`),null!=d){const e=themeOf(b());n.write(e.dim+GLYPH.hook+" "+e.blue+(c.model||"aegis")+RESET+e.dim+" "+GLYPH.bullet+" "+RESET+e.white+`${fmtTokens(d)} tokens`+RESET+"\n")}return c.interrupted?130:u?1:0}(e,t)}finally{await se()}},runInteractive:async function(){try{return await async function(){if(!e.readline&&!1!==e.chatflow&&process.stdin.isTTY&&process.stdout.isTTY){await probeTerminalBackground({onLeftover:e=>events.feedKeys(e,{keystrokes:!0})}),fe(),function(){if(!g.themeNotice)return;const e=g.themeNotice;g.themeNotice="",Y(render.renderNotice(b(),"warn",`theme: ${e} (saved)`))}(),L(),o.apiKey||await d();const t=await screens.runOnboarding(g,{continue:!!e.continue,seen:e.seen||configExists,save:e=>updateConfig(e),needsKey:()=>!o.apiKey,submitKey:e=>A(e)});if(!t.ok)return 0;if(t.key&&t.key.set&&Y(render.renderNotice(b(),"info",`key saved to ${credentials.credentialsPath()} — no export needed from now on`)),t.key&&t.key.skipped&&!o.apiKey&&Y(render.renderNotice(b(),"warn","no key saved — /key <api_key> or `aegiscode login` whenever you are ready")),t.firstRun&&function(){if(!M().enabled)return void Y(render.renderNotice(b(),"info","cross-session memory: off (you turned it off) — /cloud memory on stores sessions so an interrupted turn can be picked up later"));const e=cloudsync.status().quota,t=e&&e.limit?` (used ${fmtTokens(e.used||0)} of ${fmtTokens(e.limit)} tokens)`:"";Y(render.renderNotice(b(),"info",`cross-session memory: on${t} — sessions are stored to your account so a turn that is interrupted can be resumed. /cloud memory shows the quota; /cloud memory off stops it. Past the ceiling, saved memory stays readable and only new writes pause.`))}(),await F(),e.continue){const e=readOwnSessions(1)[0];e&&(g.continueSession=e.id,await de({id:e.id}))}return await N(),runAutoModelSync(g).catch((()=>{})),await chatflow.runSession(ue()),0}return fe(),L(),me()}()}finally{await se()}},runLinearRepl:me,refreshSpend:N,bannerLines:W,makeHost:ue,loadModels:H,validatePinnedModel:F,recordTurn:ie,persistTurn:ae,restorePrefs:fe,setApiKey:A,forgetApiKey:P,adoptLegacyKeyOnce:L,cloudSyncEnabled:x,cloudSyncState:M,setCloudSync:O,cloudsync:cloudsync,keyStatus:()=>credentials.keyStatus(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=f.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},sessionId:()=>g.sessionId,tokenSummary:ce,resumeSession:de,makeCommandContext:re,buildState:Q,get aborted(){return!1}}}module.exports={createApp:createApp,VERSION:VERSION,normalizeDecision:normalizeDecision};
|
|
3
|
+
"use strict";const readline=require("node:readline"),os=require("node:os"),{randomUUID:randomUUID}=require("node:crypto"),{createTools:createTools,createClient:createClient,usageTokens:usageTokens,usageBuckets:usageBuckets,buildSystemPrompt:buildSystemPrompt,autoProvisionApiKey:autoProvisionApiKey,provisionFailureText:provisionFailureText,trialNote:trialNote,hostEnv:hostEnv,autonomous:autonomous,claudePro:claudePro}=require("./deps.js"),{createEngine:createEngine,HOST_CLASSES:HOST_CLASSES,DEFAULT_CLASS:DEFAULT_CLASS,byokNamespace:byokNamespace,effortRung:effortRung,offeredClasses:offeredClasses,proEnabled:proEnabled}=require("./engine.js"),{GLYPH:GLYPH,VERBS:VERBS,themeOf:themeOf,RESET:RESET,THEME_TABLE:THEME_TABLE,AUTO_THEME_INDEX:AUTO_THEME_INDEX,themeIsLight:themeIsLight,reconcileThemeIndex:reconcileThemeIndex}=require("./theme.js"),{probeTerminalBackground:probeTerminalBackground}=require("./caps.js"),{LiveRegion:LiveRegion,termWidth:termWidth,w:w}=require("./screen.js"),{estimateTokensFromCells:estimateTokensFromCells}=require("./tokens.js"),{editPreview:editPreview}=require("./diff.js"),{defaultOpen:defaultOpen}=require("./diffview.js"),{parseLine:parseLine,COMMANDS:COMMANDS,visibleCommands:visibleCommands,runAutoModelSync:runAutoModelSync}=require("./commands.js"),{updateConfig:updateConfig,loadPermissions:loadPermissions,loadConfig:loadConfig,configExists:configExists,memoryPersistState:memoryPersistState,memoryPersistEnabled:memoryPersistEnabled,setMemoryPersist:setMemoryPersist,confirmPosture:confirmPosture,permissionMode:permissionMode}=require("./config.js"),credentials=require("./credentials.js"),events=require("./events.js"),cloudsync=require("./cloudsync.js"),{readSecret:readSecret}=require("./secret.js"),{normalizeModelCatalog:normalizeModelCatalog,pickerEntries:pickerEntries,catalogIds:catalogIds,providerForModel:providerForModel,withAutoRow:withAutoRow,AUTO_MODEL_ID:AUTO_MODEL_ID}=require("./models.js"),{appendHistory:appendHistory,readSessionTranscript:readSessionTranscript,readOwnSessions:readOwnSessions,setSessionTitle:setSessionTitle}=require("./history.js"),naming=require("./naming.js"),{snapshotCheckpoint:snapshotCheckpoint}=require("./checkpoint.js"),screens=require("./screens.js"),chatflow=require("./chatflow.js"),overlays=require("./overlays.js"),render=require("./render.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,maskKey:maskKey,feeBillable:feeBillable}=require("./format.js"),{resolveSkip:resolveSkip}=require("./permissions.js"),VERSION=require("../package.json").version;let _defaultSystem=null;function defaultSystemPrompt(){if(null===_defaultSystem)try{_defaultSystem=buildSystemPrompt(hostEnv({},{},null))}catch{_defaultSystem=""}return _defaultSystem||void 0}function normalizeDecision(e){const t="string"==typeof e?e.trim().toLowerCase():"";return"session"===t?"session":"once"===t||"allow"===t||"yes"===t||"approve"===t||"approved"===t?"once":"deny"}const PROVIDER_REFUSAL_PATTERNS=Object.freeze([/^invalid api key\b/i,/^fix external api key\b/i,/^you've hit your session limit\b/i,/^you have hit your session limit\b/i,/^provider request timed out\b/i,/^insufficient (?:credit|balance|quota)\b/i,/^rate limit(?:ed)?\b/i,/^unauthorized\b/i]);function providerRefusal(e,t){if("string"!=typeof e)return null;const n=t&&(t.total_tokens||0),r=t&&(t.output_tokens||t.completion_tokens||0);if(n>0||r>0)return null;const o=e.trim();if(!o||o.length>160||o.includes("\n"))return null;for(const e of PROVIDER_REFUSAL_PATTERNS)if(e.test(o))return o;return null}function briefArgs(e){let t;try{t="string"==typeof e?e:JSON.stringify(e??"")}catch{t=String(e)}return t=String(t).replace(/\s+/g," ").trim(),t.length>140?`${t.slice(0,137)}...`:t}function createApp(e={}){const t={model:null,stream:!0,light:!1,maxTokens:void 0,system:void 0,interactive:!0,...e},n=e.out||process.stdout,r=e.err||process.stderr,o=e.client||createClient(credentials.clientOptions({channel:"cli"})),{createLocalWiki:s}=require("./dream-cmd.js"),{TOOLS:i,toolList:a}=e.tools||createTools(o,{localWiki:s()});let l=!1,c="";async function d(){const e=await autoProvisionApiKey(o,credentials,{app:"cli"});return c=e.key?"":provisionFailureText(e),e}async function u(){if(o.apiKey||l)return;l=!0;const e=await d();e.key&&Y(render.renderNotice(b(),"info","auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.`))}let m=!1!==e.confirmMode,f=(()=>{try{return autonomous.autoRoundsDefault(process.env)}catch{return!0}})();const p=e.engine||createEngine({client:o,getClass:()=>g.modelClass,getProEnabled:()=>{try{return proEnabled(loadConfig())}catch{return!1}},getConfirmMode:()=>{if(void 0!==e.confirmMode)return m;try{const e=resolveSkip({env:process.env,interactive:Boolean(process.stdin.isTTY&&process.stdout.isTTY)});if(e.warned&&!skipEnvWarned&&(skipEnvWarned=!0,process.stderr.write(`aegiscode: ${e.warning}\n`)),e.skip)return!1}catch{}try{return confirmPosture().enabled}catch{return m}},getPermissionMode:()=>{try{return permissionMode()}catch{return null}}}),y=e=>"function"==typeof p.classLabel?p.classLabel(e):String(e||""),h=()=>e.width?e.width():termWidth(),g={light:t.light,model:t.model,modelClass:DEFAULT_CLASS,effort:null,thinking:!1,recallDeep:!1,themeIndex:t.light?2:AUTO_THEME_INDEX,vim:!1,stream:t.stream,cwd:process.cwd(),lastRecap:null,sessionId:randomUUID()};g.themeIndex===AUTO_THEME_INDEX&&(g.light=themeIsLight(AUTO_THEME_INDEX));const k=[];let v=!1;const b=()=>({light:g.light}),S={turns:0,calls:0,tokens:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,cost:0,balance:null,seenLedgerRows:new Map,ledgerBaselined:!1,startedAt:Date.now()};let T=null,E=!1;function C(e){if(!e||"object"!=typeof e)return null;if("usage"!==e.kind)return null;const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6;return Number.isFinite(t)?Math.abs(t):null}function I(e){return[e.created_at||"",e.kind||"",null!=e.amount_eur?e.amount_eur:"",null!=e.charged_micros?e.charged_micros:"",null!=e.id?e.id:"",null!=e.note?e.note:""].join("|")}async function N(){try{const e=await o.tokenBankBalance(),t=Number(e.balance_eur);Number.isFinite(t)&&(S.balance=t);let n=null;const r=Array.isArray(e.ledger)?e.ledger:[],s=new Map;for(const e of r){const t=I(e),n=s.get(t);n?n.n+=1:s.set(t,{n:1,row:e})}for(const[e,{n:t,row:r}]of s){const o=S.seenLedgerRows.get(e)||0;if(S.seenLedgerRows.set(e,t),!S.ledgerBaselined)continue;const s=t-o;if(s<=0)continue;const i=C(r);null!=i&&i>0&&(S.cost+=i*s,null==n&&(n=i))}return S.ledgerBaselined=!0,{balance:S.balance,lastCost:n}}catch{return null}}async function A(e,{verify:t=!0}={}){const n=credentials.saveApiKey(e);if(!n.ok)return n;o.setApiKey(n.key),R.models=[],R.at=0;let r=null,s=null;if(t)try{const e=await o.verifyApiKey()||{};r=e;const t={verifiedAt:(new Date).toISOString()};e.memory_token&&(t.memoryToken=e.memory_token),e.plan&&(t.plan=e.plan),t.account={plan:e.plan||null,email:e.email||null,valid:!1!==e.valid},credentials.writeCredentials(t),e.plan&&(S.plan=e.plan),e.email&&(S.account={...S.account||{},email:e.email})}catch(e){s=e}return{...n,account:r,error:s}}function P(){const e=credentials.clearApiKey();return o.setApiKey(""),R.models=[],R.at=0,e}function x(){try{return memoryPersistEnabled()}catch{return!0}}function M(){try{return memoryPersistState()}catch{return{enabled:!0,source:"default",explicit:!1}}}function O(e){return setMemoryPersist(e)}function L(){try{return"config"!==credentials.resolveApiKey().source?[]:credentials.adoptLegacy().adopted}catch{return[]}}const _=3e5,R={at:0,models:[]},$={at:0,models:[],declared:""};async function K({force:e=!1}={}){const t=function(){try{if("function"!=typeof p.userModels)return"";const e=(p.userModels()||{}).map||{};return JSON.stringify(Object.keys(e).sort().map(t=>[t,e[t]]))}catch{return""}}(),n=$.models.length&&Date.now()-$.at<_&&t===$.declared;if(!e&&n)return $.models;if("function"!=typeof p.listModels)return[];const r=await p.listModels("byok");return $.models=(r&&r.models||[]).map(e=>({...e,note:e.configured?"key on this machine":`no key — /byok-key ${e.provider}`})),$.at=Date.now(),$.declared=t,$.models}async function D(e){const t=U();if(e&&!t.includes(e)&&HOST_CLASSES.includes(e))return[];const n=t.includes(e)?e:g.modelClass;try{if("byok"===n){const e=await K();if(!R.models.length)try{await H()}catch{}return q(e,n)}if("pro"===n){const e=await p.listModels("pro");return(e&&e.models||[]).map(e=>({...e,cls:"pro"}))}if("aegis"!==n){const e=await p.listModels(n);return e&&e.models||[]}return await H()}catch{return[]}}function j(){return withAutoRow(pickerEntries(R.models)).map(e=>({...e,cls:"aegis"}))}function q(e,t){const n=U(),r=n.includes(t)?t:g.modelClass;if("pro"===t&&!n.includes("pro"))return[];if("pro"===r)return pickerEntries(claudePro.PRO_MODELS.map(e=>({id:e.id,label:e.label,note:e.note}))).map(e=>({...e,cls:"pro"}));if("byok"!==r)return j();const o=Array.isArray(e)?e.map(e=>({...e,cls:"byok"})):pickerEntries($.models).map(e=>({...e,cls:"byok"}));return[...j(),...o]}function B(){return new Set(claudePro.PRO_MODELS.map(e=>String(e.id).toLowerCase()))}function U(){try{return offeredClasses(proEnabled(loadConfig()))}catch{return offeredClasses(!1)}}async function H({force:e=!1}={}){const t=R.models.length&&Date.now()-R.at<_;if(!e&&t)return R.models;const n=await o.listModels();return R.models=normalizeModelCatalog(n&&n.models),R.at=Date.now(),R.models}async function F(){const e=g.model;if(!e)return null;if("byok"===g.modelClass)return String(e).includes(":")?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" belongs to the pooled class — on BYOK an id is "<provider>:<model>"; pin cleared, /models lists what this machine can relay.`)),e);if("pro"===g.modelClass){if(!B().has(String(e).toLowerCase()))return g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" is not one the Claude Code CLI resolves — pin cleared, the CLI will choose; /models lists the aliases (${claudePro.PRO_MODELS.map(e=>e.id).join(", ")}).`)),e;let t=!0;try{t=!!claudePro.claudeProStatus({env:process.env}).credentialPresent}catch{t=!0}return t?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" needs a Claude Pro subscription or an ANTHROPIC_API_KEY, and this host has neither — pin cleared. Run \`claude /login\`, export a console key, or \`/class pro off\`.`)),e)}let t;try{t=await H()}catch{return null}return t.length?String(e).trim().toLowerCase()===AUTO_MODEL_ID||catalogIds(t).has(String(e).toLowerCase())?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" is not advertised by AEGIS Cloud — pin cleared, the pool will choose; /models lists what you can pin.`)),e):null}function W(){return render.renderBanner(b(),{width:h(),version:VERSION,model:g.model||"server default",base:o.apiBase,key:maskKey(o.apiKey),stream:g.stream})}function Y(e){const t="string"==typeof e?[e]:e;for(const e of t)n.write(e+"\n")}async function V(e,{history:o=[],presenter:s=null,signal:i=null}={}){const a=Date.now(),l=!s&&t.interactive&&t.stream&&n.isTTY?new LiveRegion(n):null;let c=0,d=0,u="",m=0,f=0,y=VERBS[Math.floor(Math.random()*VERBS.length)],k=!1,v=!1;const S=()=>{l&&l.update([render.renderWorking(b(),{tick:c++,verb:y,elapsedMs:Date.now()-a,streamed:estimateTokensFromCells(d+m)+f,streamedFloor:f>0})])},E=l?setInterval(S,90):null;E&&E.unref&&E.unref(),S();const C=s||{},I=new Map,N=randomUUID();T=N;let A=!1;const P=()=>{A=!0,p.cancel(N)},x=()=>P();process.once("SIGINT",x),i&&(i.aborted?P():i.addEventListener("abort",P,{once:!0}));const M=e=>(r.write(`aegiscode: ${e.tool} needs confirmation but this run has no prompt for it — denied (pass --automode (alias --yolo) to auto-approve mutating tools).\n`),Promise.resolve("deny")),O=()=>Promise.resolve(!1),L=e=>{if(e){if(e.thinkingTokens&&(f+=e.thinkingTokens,k||(k=!0,y="Reasoning"),(e=>{C.thinkingTokens&&C.thinkingTokens(e)})(e.thinkingTokens),S()),e.reasoning&&(m+=w(e.reasoning),k||(k=!0,y="Reasoning",S()),(e=>{C.reasoning&&C.reasoning(e)})(e.reasoning)),e.delta&&(d+=w(e.delta),u+=e.delta,(e=>{if(C.text)return C.text(e);l&&c%2==0&&S()})(e.delta)),e.tool&&(v=!0,(e=>{if(C.tool)return C.tool(e);l&&l.clear();const t=(e=>{const t=e&&void 0!==e.id?`id:${e.id}`:`${e&&e.name}:${JSON.stringify(e&&e.args)}`;return I.has(t)||I.set(t,editPreview(e&&e.name,e&&e.args,{cwd:process.cwd()})),I.get(t)})(e);Y(render.renderTurn(b(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:defaultOpen(t)},h())),S()})(e.tool)),e.approval){const t=e.approval;l&&l.clear();const n=C.approval||M;Promise.resolve(n(t)).catch(()=>"deny").then(e=>p.respondApproval(t.id,normalizeDecision(e)))}if(e.rounds){const t=e.rounds;l&&l.clear();const n=C.rounds||O;Promise.resolve(n(t)).catch(()=>!1).then(e=>p.respondRoundsAsk(t.id,!0===e))}}};try{const n=await p.chat({prompt:e,messages:o,model:g.model||void 0,system:t.system||defaultSystemPrompt(),maxTokens:t.maxTokens,effort:effortRung(g.effort),recallDeep:!0===g.recallDeep||void 0,stream:!1!==g.stream,sessionId:N,sessionKey:g.sessionId,rootSessionId:g.sessionId,roundsAsk:Boolean(C.rounds)},L),r=n.choices&&n.choices[0]||{};return{text:r.message&&r.message.content||u,usage:n.usage||null,model:n.model||g.model||null,ms:Date.now()-a,interrupted:A,reasoningChars:m,usedTools:v}}catch(e){if(A&&u)return{text:u,usage:null,model:g.model||null,ms:Date.now()-a,interrupted:!0,reasoningChars:m,usedTools:v};throw e}finally{E&&clearInterval(E),process.removeListener("SIGINT",x),i&&i.removeEventListener("abort",P),l&&l.clear(),T=null}}function G(e){Y(render.renderTurn(b(),e,h()))}async function z(e,{label:t="you"}={}){if(!e)return void Y(render.renderNotice(b(),"warn","nothing to ask — give /ask a prompt"));if(o.apiKey||await u(),!o.apiKey)return void Y(render.renderNotice(b(),"error",`no AEGIS account key — ${credentials.HOW_TO_SET} (or set $${credentials.KEY_ENV})`));const n=k.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.text}));let r;G({role:"user",text:e,label:t}),k.push({role:"user",text:e});try{r=await V(e,{history:n})}catch(t){return ae(e,{text:"",error:t.message},"error"),void Y(render.renderTurn(b(),{role:"error",text:t.message},h()))}r.text&&k.push({role:"assistant",text:r.text});const s=ie(r);let i=null;try{const e=await N();i=e?e.lastCost:null}catch{}ae(e,r,r.interrupted?"stopped":r.error?"error":"done",i),G({role:"assistant",text:r.text||"(the pool returned no text — see /balance for what it charged)",meta:{model:r.model,tokens:s,usage:null==r.usage?null:usageBuckets(r.usage),eur:i,ms:r.ms,calls:1}}),r.interrupted&&Y(render.renderNotice(b(),"warn","interrupted — the pool may still be running and billing this call"))}async function X(e,t){const n=i[e];if(!n)throw new Error(`unknown tool: ${e}`);if(o.apiKey||await u(),!o.apiKey)throw new Error(`no AEGIS account key — ${credentials.HOW_TO_SET}`);const r=await n.run(t||{});Y(render.renderToolResult(b(),e,r,h()))}function J(e){const t=String(e||"").toLowerCase();if(!t)return null;let n=null;for(const e of COMMANDS)for(const r of[e.name,...e.aliases||[]])r!==t&&(r.startsWith(t)||t.startsWith(r))&&(null==n||Math.abs(r.length-t.length)<Math.abs(n.length-t.length))&&(n=r);return n}function Q(){const e=loadPermissions(),t=confirmPosture();return{version:VERSION,model:g.model||"server default",class:g.modelClass,effort:g.effort,thinking:g.thinking,theme:g.light?"light":"dark",themeIndex:g.themeIndex,vim:g.vim,stream:g.stream,cwd:g.cwd,home:os.homedir(),sessionId:g.sessionId,base:o.apiBase,keyMask:maskKey(o.apiKey),online:!!o.apiKey,turns:S.turns,calls:S.calls,startedAt:S.startedAt,tokens:{input:S.inputTokens,output:S.outputTokens,cacheRead:S.cacheReadTokens,cacheWrite:S.cacheWriteTokens,total:S.tokens},costEur:S.cost,balance:S.balance,plan:S.plan||null,account:S.account||null,permissions:{mode:t.enabled?e.defaultMode:"allow",confirm:t.enabled,source:t.source,rules:e},models:q(),commands:visibleCommands(),transcript:k.slice(),sessions:[],memory:{},lastRecap:g.lastRecap,backend:g.modelClass,url:o.apiBase}}function Z(e){return Array.isArray(e)?e.map(e=>e&&(e.s||"")+(null==e.t?"":e.t)||"").join(""):String(null==e?"":e)}function ee(e){if(!e||"object"!=typeof e)return;const t=h();switch(e.role){case"panel":{const t=Array.isArray(e.lines)?e.lines:[];for(const e of t)Y(Z(e));return}case"note":case"tip":return void Y(render.renderNotice(b(),"info",e.text));case"done":return void Y(render.renderNotice(b(),"ok",e.text));case"error":return void Y(render.renderNotice(b(),"error",e.text));case"user":return void Y(render.renderTurn(b(),{role:"user",text:e.text,label:e.label},t));case"assistant":return void Y(render.renderTurn(b(),{role:"assistant",text:e.text},t));case"tool":return void 0===e.diff&&(e.diff=editPreview(e.name||e.label,e.args,{cwd:process.cwd()}),e.diffOpen=defaultOpen(e.diff)),void Y(render.renderTurn(b(),{role:"tool",label:e.label||e.name,args:e.args,ok:e.ok,diff:e.diff,diffOpen:!!e.diffOpen},t));default:return void Y(render.renderNotice(b(),"info",null==e.text?"":String(e.text)))}}function te(e){return{t:e,s:"",w:w(e)}}async function ne(){return!e.readline&&process.stdin.isTTY&&process.stdout.isTTY&&!1!==e.chatflow?screens.showThemePicker(g):(g.light=!g.light,g.themeIndex=g.light?2:1,Y(render.renderNotice(b(),"ok","theme: "+(g.light?"light":"dark"))),g.themeIndex)}function re(){const e={ctx:g,transcript:k,push:e=>ee(e),note:e=>ee({role:"note",text:e}),panel:e=>ee({role:"panel",lines:e}),render:()=>{},openOverlay:e=>function(e){if(!e||"object"!=typeof e)return;const t=h(),n=Math.max(5,process.stdout&&process.stdout.rows||24);let r=null;if("panel"===e.type?r=e.lines:"palette"===e.type?r=overlays.renderPalette(visibleCommands(),{query:e.query||"",sel:e.sel||0},t,n):"model"===e.type?r=overlays.renderModelPicker(e.items||[],e.sel||0,t,n,null!=e.current?e.current:g.model,e.cls||g.modelClass,y):"effort"===e.type?r=overlays.renderEffortPicker(e.sel||0,t,g.effort):"class"===e.type?r=overlays.renderClassPicker(e.items||[],e.sel||0,t,e.current||g.modelClass,y):"provider"===e.type?r=overlays.renderProviderPicker(e.items||[],e.sel||0,t,e.current,e.hint):"resume"===e.type?r=overlays.renderResumeList(e.items||[],e.sel||0,t,n):"confirm"===e.type&&(r=render.renderApproval(b(),e.info||{},t).map(e=>[te(e)])),r)for(const e of r)Y(Z(e))}(e),closeOverlay:()=>{},setAutoRounds:e=>{f=Boolean(e)},askInput:()=>Promise.resolve(null),withWorking:e=>async function(e){const r=new AbortController,o=t.interactive&&n.isTTY?new LiveRegion(n):null;let s=null;if(o){let e=0;const t=Date.now(),n=()=>o.update([render.renderWorking(b(),{tick:e++,verb:VERBS[0],elapsedMs:Date.now()-t})]);n(),s=setInterval(n,90),s.unref&&s.unref()}try{return await e(r.signal)}finally{s&&clearInterval(s),o&&o.clear()}}(e),runPrompt:e=>z(e),ask:e=>V(e),runTool:(e,t)=>X(e,t),loadModels:()=>D(g.modelClass),settings:()=>p.settings||null,byokNamespace:e=>byokNamespace(e),listModelsFor:e=>D(e),refreshByokModels:()=>K({force:!0}),switchClass:e=>function(e){const t=String(null==e?"":e).trim().toLowerCase(),n=U();if(!n.includes(t))return"pro"===t?{ok:!1,error:"the pro class (your Claude Code subscription) is off by default — enable it once with `/class pro on`"}:{ok:!1,error:`unknown class "${e}" — classes: ${n.join(", ")}`};const r=g.modelClass;g.modelClass=t;let o=null;return r!==t&&g.model&&(function(e,t){const n=String(null==t?"":t);return"byok"===e?n.includes(":"):"pro"===e?B().has(n.toLowerCase()):!n.includes(":")}(t,g.model)||(o=g.model,g.model=null)),updateConfig({modelClass:t,model:g.model,currentModelId:g.model}),{ok:!0,class:t,prev:r,cleared:o}}(e),classLabel:e=>y(e),classes:()=>"function"==typeof p.listClasses?p.listClasses():[],refreshSpend:()=>N(),state:()=>Q(),setInput:()=>{},exit:()=>{v=!0},client:o,TOOLS:i,saveConfig:e=>updateConfig(e),showThemePicker:()=>ne(),keyStatus:()=>credentials.keyStatus(),setApiKey:(e,t)=>A(e,t),forgetApiKey:()=>P(),registerAccount:()=>async function(){return o.apiKey?{alreadyKeyed:!0}:d()}(),readSecret:e=>readSecret(e,{stdin:process.stdin,stdout:n}),cloudsync:cloudsync,cloudSyncEnabled:()=>x(),cloudSyncState:()=>M(),setCloudSync:e=>O(e),adoptLegacyKey:()=>L()};return Object.defineProperty(e,"sessionId",{enumerable:!0,get:()=>g.sessionId,set:e=>{g.sessionId=e}}),e.clearConversationMemory=()=>{p&&"function"==typeof p.clearSessionApprovals&&p.clearSessionApprovals(g.sessionId)},e.listUndoable=()=>p&&"function"==typeof p.listUndoable?p.listUndoable(g.sessionId):[],e.undoMutation=e=>p&&"function"==typeof p.undoMutation?p.undoMutation(g.sessionId,e):{ok:!1,error:"undo is not available on this engine"},e}async function oe(e,t=null){const r=parseLine(e);if("empty"===r.kind)return!0;if("prompt"===r.kind)return await z(r.text),!0;if("unknown"===r.kind){const e=J(r.name);return Y(render.renderNotice(b(),"error",`unknown command: /${r.name}${e?` — did you mean /${e}?`:" — try /help"}`)),!0}if("unavailable"===r.kind){const e=r.command;if(Y(render.renderNotice(b(),"warn",`/${e.name} is not available in aegiscode — ${e.unavailable}`)),e.alt)Y(render.renderNotice(b(),"info",`try ${e.alt} instead`));else{const t=J(e.name);t&&Y(render.renderNotice(b(),"info",`try /${t} instead`))}return!0}const s=r.command,i=r.arg;if(s.generic){let t;try{t=s.build(i)}catch(e){return Y(render.renderNotice(b(),"error",e.message)),!0}const{tool:n,args:r}=t;if(!n)return Y(render.renderNotice(b(),"error","/tool needs a tool name — see /help")),!0;try{await X(n,r)}catch(e){Y(render.renderNotice(b(),"error",e.message))}return!0}if("function"==typeof s.handler){const n=function(e,t){const n=String(null==t?"":t),r=Array.isArray(e.args)?e.args:[],o=function(e){const t=[];let n="",r=null,o=!1;for(const s of String(e||""))r?s===r?r=null:n+=s:'"'!==s&&"'"!==s?/\s/.test(s)?(n||o)&&(t.push(n),n="",o=!1):(n+=s,o=!0):(r=s,o=!0);return(n||o)&&t.push(n),t}(n),s={_rest:n.trim()};return r.forEach((e,t)=>{void 0!==o[t]&&(s[e]=o[t])}),s}(s,i),r=t||re();try{return!1!==await s.handler(r,n)}catch(e){return Y(render.renderNotice(b(),"error",e&&e.message?e.message:String(e))),!0}}try{let e=s.build(i);if(s.secret){const t=await async function(e,t){if("function"!=typeof e.secretDescribe)return null;try{const n=await e.secretDescribe(t,o);return n&&"object"==typeof n?n:null}catch{return null}}(s,e);if(t&&t.note&&Y(render.renderNotice(b(),"info",t.note)),t&&null===t.prompt)return!0;t&&t.provider&&(e={...e,provider:t.provider});const r=await function(e){const t=themeOf(b());return readSecret(t.gray+e+RESET,{stdin:process.stdin,stdout:n})}(t&&t.prompt||`provider key for ${e.provider}: `);if(!r)return Y(render.renderNotice(b(),"warn","empty key — nothing sent")),!0;e={...e,api_key:r}}if("aegis_ask"===s.tool)return await z(e.prompt);await X(s.tool,e),"aegis_memory_list"!==s.tool&&"aegis_memory_search"!==s.tool||function(){let e;try{e=cloudsync.status()}catch{return}const t=e.quota;if(!t)return;const n=fmtTokens(t.used||0),r=fmtTokens(t.limit||0);e.overQuota?Y(render.renderNotice(b(),"warn",`cloud memory: ${n} of ${r} synced tokens — at the plan's ceiling. Everything stored stays readable; new writes are paused until there is room. /cloud memory for the full state.`)):Y(render.renderNotice(b(),"info",`cloud memory: ${n} of ${r} synced tokens — /cloud memory for the full state`))}()}catch(e){Y(render.renderNotice(b(),"error",e.message))}return!0}async function se(){if(p&&"function"==typeof p.unloadLocalModels)try{await p.unloadLocalModels()}catch{}}function ie(e){S.turns++,S.calls+=Number(e&&e.calls||1)||1;const t=e&&e.usage,n=usageTokens(t);if(null!=n){S.tokens+=n;const e=usageBuckets(t);S.inputTokens+=e.input,S.outputTokens+=e.output,S.cacheReadTokens+=e.cacheRead,S.cacheWriteTokens+=e.cacheWrite}return n}function ae(e,t,n="done",r=null){try{const o=t&&t.usage,s="number"==typeof r&&Number.isFinite(r)?r:null,i=String(t&&t.model||g.model||"").trim();appendHistory({sessionId:g.sessionId,prompt:e,reply:t&&t.text||"",status:n,model:i||void 0,provider:i&&providerForModel({id:i,cls:g.modelClass})||void 0,usage:o?{...usageBuckets(o),...null!=s?{costUsd:s}:{}}:null!=s?{input:0,output:0,cacheRead:0,cacheWrite:0,costUsd:s}:null}),snapshotCheckpoint(g.sessionId,k)}catch{}x()&&o.apiKey&&Promise.resolve().then(()=>cloudsync.push(o)).then(e=>{if(e&&e.failed&&e.failed.length){const t=e.failed[0];if(le.has(t.kind))return;if(le.add(t.kind),"quota"===t.kind)return void Y(render.renderNotice(b(),"warn","cloud memory: the plan's synced-token ceiling is reached — earlier sessions stay readable, only NEW writes pause. /cloud memory shows the quota; /cloud memory off stops trying."));const n=t.hint?` — ${t.hint}`:"";Y(render.renderNotice(b(),"error",`cloud sync: ${t.message}${n}`))}}).catch(()=>{})}let le=new Set;function ce(){const e=[S.outputTokens>0?`${fmtTokens(S.outputTokens)} tokens`:`${fmtTokens(S.tokens)} tokens`,`${S.calls} call${1===S.calls?"":"s"}`];return feeBillable()&&(e.push(fmtEur(S.cost)),null!=S.balance&&e.push(`balance ${fmtEur(S.balance)}`)),e.join(" · ")}async function de(e){if(!e||!e.id)return;const t=readSessionTranscript(e.id);if(t.length){k.length=0;for(const e of t)k.push(e);g.sessionId=e.id,Y(render.renderNotice(b(),"ok",`resumed ${e.id} — ${t.length} turn(s)`))}else Y(render.renderNotice(b(),"warn",`no stored turns for ${e.id}`))}function ue(){return{ctx:g,version:VERSION,transcript:k,session:S,client:o,TOOLS:i,ask:(e,t)=>V(e,t),makeCommandContext:()=>re(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=p.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},loadModels:e=>H(e),buildState:()=>Q(),dispatchLine:(e,t)=>oe(e,t),refreshSpend:()=>N(),updateConfig:e=>updateConfig(e),showThemePicker:()=>ne(),persistTurn:(e,t,n,r)=>ae(e,t,n,r),nameConversation:(e,t)=>async function(e,{signal:t=null}={}){const n=await naming.nameConversation(e,{signal:t,callModel:(e,n)=>V(e,{system:n&&n.system||naming.TITLE_SYSTEM,maxTokens:64,signal:n&&n.signal||t}).then(e=>e&&e.text||null)}),r=String(n||"").trim();return r&&setSessionTitle(g.sessionId,r),r}(e,t),visibleCommands:()=>visibleCommands(),tokensFor:e=>usageTokens(e),recordTurn:e=>ie(e),tokenSummary:()=>ce(),resumeSession:e=>de(e),requestExit:()=>{v=!0},wantsExit:()=>v,keyNotice:()=>o.apiKey?"":c,isYolo:()=>{if(!f)return!1;try{return!1===confirmPosture().enabled}catch{return!1}},setAutoRounds:e=>{f=Boolean(e)}}}async function me(){Y(W()),await N(),n.write("\n");const t=e.readline||readline.createInterface({input:process.stdin,output:n,terminal:!0}),r=themeOf(b()).gold+GLYPH.cursor+" "+RESET;return t.setPrompt(r),t.prompt(),new Promise(e=>{t.on("line",async e=>{t.pause();let n=!0;try{n=await oe(e)}catch(e){Y(render.renderNotice(b(),"error",e.message))}if(!n||v)return E=!0,void t.close();t.resume(),t.prompt()}),t.on("close",()=>{E||n.write("\n"),e(0)})})}function fe(){if(e.readline)return;if(!configExists())return;let n;try{n=loadConfig()}catch{return}if(U().includes(n.modelClass)&&(g.modelClass=n.modelClass),t.class){const e=String(t.class).trim().toLowerCase();if(!U().includes(e))throw new Error(`--class ${t.class}: not available on this host (offered: ${U().join(", ")})`);g.modelClass=e}if(!t.model&&n.model&&(g.model=n.model),g.effort=effortRung(t.effort||n.effort),"boolean"==typeof n.vim&&(g.vim=n.vim),n.lastRecap&&(g.lastRecap=n.lastRecap),!t.light&&"number"==typeof n.themeIndex&&THEME_TABLE[n.themeIndex]){g.themeIndex=n.themeIndex,g.light=themeIsLight(n.themeIndex);const e=reconcileThemeIndex(g.themeIndex);if(e.changed){g.themeIndex=e.index,g.light=themeIsLight(e.index),g.themeNotice=e.reason;try{updateConfig({themeIndex:e.index,light:themeIsLight(e.index)})}catch{g.themeNotice+=" (could not save it)"}}}}return{opts:t,session:S,client:o,TOOLS:i,toolList:a,ctx:g,transcript:k,ask:V,runPrompt:z,handleLine:oe,runOnce:async function(e,t={}){try{return await async function(e,{json:t=!1}={}){if(fe(),L(),!o.apiKey&&!l){l=!0;const e=await autoProvisionApiKey(o,credentials,{app:"cli"});e.key&&r.write("aegiscode: auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.\n`)}if(!o.apiKey)return r.write(`aegiscode: no AEGIS account key. ${credentials.HOW_TO_SET}, or set $${credentials.KEY_ENV}.\n`),2;await N();const s=[],i=[],a=t?{tool:e=>{if("done"===(e&&e.phase)){const t=e.id&&i.find(t=>t.id===e.id&&!0!==t.settled)||(e.id?null:i[i.length-1]);t?(t.settled=!0,t.ok=!1!==e.ok):(e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!0,ok:!1!==e.ok}))}else e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!1,ok:null});const t=e&&void 0!==e.preview?e.preview:null,n=render.renderTurn(b(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:!1},h());for(const e of Array.isArray(n)?n:[n])r.write(e+"\n")}}:null,c=await V(e,a?{presenter:a}:{});await N();const d=usageTokens(c.usage),u=providerRefusal(c.text,c.usage);if(t)n.write(JSON.stringify({text:c.text,model:c.model,class:g.modelClass,rounds:c.usage&&Number(c.usage.calls)||null,usage:c.usage,reasoning_chars:"number"==typeof c.reasoningChars?c.reasoningChars:null,tokens:d,ms:c.ms,interrupted:c.interrupted,...s.length?{tools:s}:{},...i.length?{tool_log:i}:{},...u?{error:u}:{},balance_eur:S.balance},null,2)+"\n");else if(n.write(c.text+"\n"),u&&r.write(`aegiscode: the provider refused this turn — ${u}\n`),null!=d){const e=themeOf(b());n.write(e.dim+GLYPH.hook+" "+e.blue+(c.model||"aegis")+RESET+e.dim+" "+GLYPH.bullet+" "+RESET+e.white+`${fmtTokens(d)} tokens`+RESET+"\n")}return c.interrupted?130:u?1:0}(e,t)}finally{await se()}},runInteractive:async function(){try{return await async function(){if(!e.readline&&!1!==e.chatflow&&process.stdin.isTTY&&process.stdout.isTTY){await probeTerminalBackground({onLeftover:e=>events.feedKeys(e,{keystrokes:!0})}),fe(),function(){if(!g.themeNotice)return;const e=g.themeNotice;g.themeNotice="",Y(render.renderNotice(b(),"warn",`theme: ${e} (saved)`))}(),L(),o.apiKey||await u();const t=await screens.runOnboarding(g,{continue:!!e.continue,seen:e.seen||configExists,save:e=>updateConfig(e),needsKey:()=>!o.apiKey,submitKey:e=>A(e)});if(!t.ok)return 0;if(t.key&&t.key.set&&Y(render.renderNotice(b(),"info",`key saved to ${credentials.credentialsPath()} — no export needed from now on`)),t.key&&t.key.skipped&&!o.apiKey&&Y(render.renderNotice(b(),"warn","no key saved — /key <api_key> or `aegiscode login` whenever you are ready")),t.firstRun&&function(){if(!M().enabled)return void Y(render.renderNotice(b(),"info","cross-session memory: off (you turned it off) — /cloud memory on stores sessions so an interrupted turn can be picked up later"));const e=cloudsync.status().quota,t=e&&e.limit?` (used ${fmtTokens(e.used||0)} of ${fmtTokens(e.limit)} tokens)`:"";Y(render.renderNotice(b(),"info",`cross-session memory: on${t} — sessions are stored to your account so a turn that is interrupted can be resumed. /cloud memory shows the quota; /cloud memory off stops it. Past the ceiling, saved memory stays readable and only new writes pause.`))}(),await F(),e.continue){const e=readOwnSessions(1)[0];e&&(g.continueSession=e.id,await de({id:e.id}))}return await N(),runAutoModelSync(g).catch(()=>{}),await chatflow.runSession(ue()),0}return fe(),L(),me()}()}finally{await se()}},runLinearRepl:me,refreshSpend:N,bannerLines:W,makeHost:ue,loadModels:H,validatePinnedModel:F,recordTurn:ie,persistTurn:ae,restorePrefs:fe,setApiKey:A,forgetApiKey:P,adoptLegacyKeyOnce:L,cloudSyncEnabled:x,cloudSyncState:M,setCloudSync:O,cloudsync:cloudsync,keyStatus:()=>credentials.keyStatus(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=p.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},sessionId:()=>g.sessionId,tokenSummary:ce,resumeSession:de,makeCommandContext:re,buildState:Q,get aborted(){return!1}}}module.exports={createApp:createApp,VERSION:VERSION,normalizeDecision:normalizeDecision};
|
|
@@ -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,cells:cells,padCells:padCells}=require("./caps.js");function capsOf(t){return t?"string"==typeof t?detect(process.env,process.stdout,t):t:caps()}const WELCOME_MARK=["╔═╗╔═╗╔═╗╦╔═╗","╠═╣║╣ ║ ╦║╚═╗","╩ ╩╚═╝╚═╝╩╚═╝"],WELCOME_ART=WELCOME_MARK,WELCOME_ART_STACKED=WELCOME_MARK,WELCOME_TITLE="Welcome to AEGIS Code",WELCOME_BACK="Welcome back!",TAGLINE="Your intent, AI automated.",TAGLINE_SHORT="Your intent, automated.",STAR="✦",EDGE_RUNES=["▐","▛","▜","▌","▝","▘"],BOX_RUNES=["╔","╗","╚","╝","╠","╣","╦","╩","║","═"],BOX_STENCIL=new Map([...["╔","╗","╚","╝","╠","╣","╦","╩"].map(
|
|
3
|
+
"use strict";const{caps:caps,detect:detect,cells:cells,padCells:padCells}=require("./caps.js");function capsOf(t){return t?"string"==typeof t?detect(process.env,process.stdout,t):t:caps()}const WELCOME_MARK=["╔═╗╔═╗╔═╗╦╔═╗","╠═╣║╣ ║ ╦║╚═╗","╩ ╩╚═╝╚═╝╩╚═╝"],WELCOME_ART=WELCOME_MARK,WELCOME_ART_STACKED=WELCOME_MARK,WELCOME_TITLE="Welcome to AEGIS Code",WELCOME_BACK="Welcome back!",TAGLINE="Your intent, AI automated.",TAGLINE_SHORT="Your intent, automated.",STAR="✦",EDGE_RUNES=["▐","▛","▜","▌","▝","▘"],BOX_RUNES=["╔","╗","╚","╝","╠","╣","╦","╩","║","═"],BOX_STENCIL=new Map([...["╔","╗","╚","╝","╠","╣","╦","╩"].map(t=>[t,"+"]),["═","-"],["║","|"]]),ASCII_STENCIL=new Map([...BOX_STENCIL,["█","#"],["▓","@"],["▒","="],["░","."],...EDGE_RUNES.map(t=>[t,"#"]),["✦","*"],["·","."]]),EDGE_STENCIL=new Map(EDGE_RUNES.map(t=>[t,"#"])),STAR_STENCIL=new Map([["✦","*"]]),STENCILS={ascii:ASCII_STENCIL,edges:EDGE_STENCIL,star:STAR_STENCIL},PASSES=["native","star","edges","ascii"];function stencilFor(t=null){const e=capsOf(t);if("ascii"===e.glyphs)return ASCII_STENCIL;const E=new Map;if("edges"===e.face)for(const[t,e]of EDGE_STENCIL)E.set(t,e);if("narrow"===e.star)for(const[t,e]of STAR_STENCIL)E.set(t,e);return E.size?E:null}function stencilGlyph(t,e=null){const E=stencilFor(e);return E&&E.get(t)||t}function portabilityFor(t,e=null){const E=stencilFor(e);return E?t.map(t=>[...t].map(t=>E.get(t)??t).join("")):t}function portability(t){return portabilityFor(t,null)}function welcomeArtFor(){return portability(WELCOME_ART)}function welcomeArtParts(){const t=portability(WELCOME_MARK);return{rows:t.map(t=>[t,""]),width:Math.max(...t.map(cells)),gutter:0}}function center(t,e){return t.map(t=>{const E=Math.max(0,Math.floor((e-cells(t))/2));return" ".repeat(E)+padCells(t,e-E)})}function padBoth(t,e){const E=Math.max(...t.map(cells));return t.map(t=>{const r=Math.floor((e-E)/2);return" ".repeat(Math.max(0,r))+t})}module.exports={WELCOME_MARK:WELCOME_MARK,WELCOME_ART:WELCOME_ART,WELCOME_ART_STACKED:WELCOME_ART_STACKED,WELCOME_TITLE:WELCOME_TITLE,WELCOME_BACK:WELCOME_BACK,TAGLINE:TAGLINE,TAGLINE_SHORT:TAGLINE_SHORT,STAR:"✦",EDGE_RUNES:EDGE_RUNES,BOX_RUNES:BOX_RUNES,PASSES:PASSES,STENCILS:STENCILS,stencilFor:stencilFor,stencilGlyph:stencilGlyph,portability:portability,portabilityFor:portabilityFor,welcomeArtFor:welcomeArtFor,welcomeArtParts:welcomeArtParts,center:center,padBoth:padBoth};
|
|
@@ -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"),{queue:queue,autonomous:autonomous}=require("./deps.js"),{createEngine:createEngine,proEnabled:proEnabled}=require("./engine.js"),{loadConfig:loadConfig}=require("./config.js"),{fmtElapsed:fmtElapsed}=require("./format.js"),limits=require("./limits.js"),SUBCOMMANDS=new Set(["add","list","run","proceed","reconcile","clear","retry","help"]),EXECUTES=new Set(["run","proceed","retry","reconcile"]);function parseFlags(e){const t={terms:[],json:!1,flags:{}},n=new Set(["cwd","model","effort","workers","max","max-rounds","source","class"]);for(let o=0;o<e.length;o++){const r=e[o];if("--json"!==r)if(r.startsWith("--")){const[s,i]=r.slice(2).split("="),a=s.trim();if(new Set(["commit","all","auto","stop-on-error","single-pass","help"]).has(a)){t.flags[a]=!0;continue}if(!n.has(a))throw new Error(`unknown option: --${a}`);const u=void 0!==i?i:e[++o];if(void 0===u)throw new Error(`--${a} needs a value`);t.flags[a]=u}else t.terms.push(r);else t.json=!0}return t}function intFlag(e,t){const n=e[t];if(void 0===n||""===n)return null;const o=Number.parseInt(n,10);return Number.isFinite(o)&&o>0?o:null}function taskLine(e){const t=e.model||"(default)",n=String(e.status||"?").padEnd(7),o=`#${e.id}`.padEnd(4),r=String(e.task||"").replace(/\s+/g," ").trim();return`${o} ${n} ${t} ${r.length>72?`${r.slice(0,71)}…`:r}`}function describeCounts(e){const t={pending:0,running:0,done:0,error:0};for(const n of e)void 0!==t[n.status]&&(t[n.status]+=1);return t}function printRunReport(e,t){for(const n of e){const e=Boolean(n.ok&&n.stoppedOnRounds),o=e?"⏸":n.ok?"✓":"✗",r=e?"paused — will resume":n.ok?"done":"failed";if(t.stdout.write(`aegiscode: ${o} #${n.id} ${r} (${fmtElapsed(n.ms)})`),n.commit&&n.commit.ok&&n.commit.staged?t.stdout.write(` — committed ${n.commit.staged} path(s)`):n.commit&&n.commit.skipped&&n.commit.reason&&t.stdout.write(` — no commit (${n.commit.reason})`),t.stdout.write("\n"),!n.ok&&n.error&&t.stderr.write(`aegiscode: #${n.id}: ${n.error}\n`),n.ok&&n.output){const e=String(n.output).trim();t.stdout.write(`${e.length>4e3?`${e.slice(0,4e3)}\n… [output clipped]`:e}\n`)}}}function buildEngine({io:e,quiet:t=!1}){const n=require("./credentials.js"),o=require("./deps.js").createClient(n.clientOptions({channel:"cli"}));if(!o.apiKey)return{error:`no AEGIS account key — ${n.HOW_TO_SET}, or set ${n.KEY_ENV}`};const r=createEngine({client:o,getConfirmMode:()=>!1,getProEnabled:()=>{try{return proEnabled(loadConfig())}catch{return!1}}});let s=null;try{s=require("./entitlement.js").createCliEntitlement({aegis:o})}catch{s=null}return{client:o,engine:r,entitlement:s}}function progressSink(e,{json:t}){return t?()=>{}:t=>{if(t&&"object"==typeof t)if("start"!==t.type)if("tool"===t.type&&t.tool&&"run"===t.tool.phase){const n=t.tool.args||{},o=n.command||n.pattern||autonomous.writtenPath(t.tool)||"",r=String(o).slice(0,100);e.stderr.write(` ⚙ ${t.tool.name}${r?` ${r}`:""}\n`)}else"healed"!==t.type?"note"===t.type&&t.note?e.stderr.write(` ⓘ ${t.note}\n`):"recovered"===t.type&&e.stdout.write(`aegiscode: re-queued task(s) ${t.ids.join(", ")} from a dead worker\n`):e.stdout.write(`aegiscode: PLAN.md status list healed for phase(s) ${t.phases.join(", ")}\n`);else e.stdout.write(`aegiscode: #${t.taskId} running on ${t.model} in ${t.cwd}\n`)}}async function runQueueCommand(e,t,n={}){const o=n.stdout||process.stdout,r=n.stderr||process.stderr,s={stdout:o,stderr:r};let i;try{i=parseFlags(t||[])}catch(e){return r.write(`aegiscode autonomous: ${e.message}\n`),2}const a=Boolean(n.json||i.json),u=(e,t)=>{a?o.write(`${JSON.stringify(e,null,2)}\n`):void 0!==t&&o.write(t.endsWith("\n")?t:`${t}\n`)};if("help"===e||!SUBCOMMANDS.has(e))return o.write(usageText()),"help"===e?0:2;if(EXECUTES.has(e)&&limits.armed())return limits.refuse();const l=i.flags.cwd?path.resolve(String(i.flags.cwd)):process.cwd();if("add"===e){const t=i.terms.join(" ").trim();if(!t)return r.write('aegiscode autonomous add: a task needs text — `aegiscode autonomous add "…"`\n'),2;let n;try{n=queue.addTask(process.env,{task:t,cwd:l,class:i.flags.class||null,model:i.flags.model||null,effort:i.flags.effort||null,workers:intFlag(i.flags,"workers"),maxRounds:intFlag(i.flags,"max-rounds"),singlePass:Boolean(i.flags["single-pass"]),commit:Boolean(i.flags.commit),source:i.flags.source||"cli"})}catch(e){return r.write(`aegiscode autonomous add: ${e.message}\n`),2}return u({ok:!0,id:n.id,item:n,queue:queue.queuePath(process.env)},`aegiscode: queued #${n.id} — ${queue.pendingCount(queue.loadQueue(process.env))} pending`),0}if("list"===e){const e=queue.loadQueue(process.env),t=describeCounts(e);if(a)u({ok:!0,file:queue.queuePath(process.env),counts:t,tasks:e,runs:queue.readRuns(process.env,{limit:10})});else{o.write(`queue: ${queue.queuePath(process.env)}\n`),o.write(`tasks: ${e.length} (${t.pending} pending, ${t.running} running, ${t.done} done, ${t.error} error)\n`);for(const t of e)o.write(`${taskLine(t)}\n`);e.length||o.write("(empty)\n")}return 0}if("clear"===e){const e=queue.clearQueue(process.env,{all:Boolean(i.flags.all)});return u({ok:!0,...e},`aegiscode: removed ${e.removed} finished task(s); ${e.kept} kept`),0}if("retry"===e){const e=i.terms[0];if(!e)return r.write("aegiscode autonomous retry: which task? `aegiscode autonomous retry <id>`\n"),2;const t=queue.retryTask(process.env,e);return t?(u({ok:!0,id:t.id,item:t},`aegiscode: #${t.id} is pending again`),0):(r.write(`aegiscode autonomous retry: no task #${e}\n`),1)}const d=buildEngine({io:n});if(d.error)return r.write(`aegiscode autonomous: ${d.error}\n`),2;if(d.entitlement)try{await d.entitlement.refresh()}catch{}const c=autonomous.createQueueWorker({engine:d.engine,env:process.env,log:progressSink(s,{json:a}),canFanOut:()=>{if(!d.entitlement)return!1;try{const e=d.entitlement.current();return Boolean(e&&!0===e.entitled)}catch{return!1}}});if(d.entitlement)try{const e=d.entitlement.current();e&&!1===e.entitled&&!1===e.degraded&&e.refusal&&(r.write(`aegiscode autonomous: ${e.refusal}\n`),r.write(" ↳ write tasks like: Do X autonomously\n"),r.write("balance"===e.wall?" ↳ unlock: top up the Token Bank, or upgrade to Unlimited\n":" ↳ unlock: Unlimited, or any Token Bank balance\n"),e.upgradeUrl&&r.write(` ${e.upgradeUrl}\n`))}catch{}const m=!!i.flags.commit||void 0,g=()=>{const e=queue.loadQueue(process.env).find((e=>"running"===e.status&&e.pid===process.pid));e&&c.cancel(e.id)};process.on("SIGINT",g);try{if("reconcile"===e){const e=await c.reconcile({cwd:l,auto:Boolean(i.flags.auto),commit:m,max:intFlag(i.flags,"max")||0,stopOnError:Boolean(i.flags["stop-on-error"])});return e.ok?(a||printRunReport(e.ran||[],s),u(e,e.exhausted?"aegiscode: every phase in PLAN.md is done — nothing to queue":`aegiscode: phase ${e.phase} queued${e.ran?` — ${e.ran.length} task(s) run`:""}`),0):(r.write(`aegiscode autonomous reconcile: ${e.error||"reconcile failed"}\n`),u(e,void 0),1)}if("proceed"===e||"run"===e){const t="run"===e?1:intFlag(i.flags,"max")||0,n=await c.proceed({commit:m,max:t,stopOnError:Boolean(i.flags["stop-on-error"])});if(n.locked)return r.write(`aegiscode autonomous: another drain holds the queue lock (pid ${n.holder&&n.holder.pid})\n`),u({ok:!1,locked:!0,holder:n.holder},void 0),1;a||printRunReport(n.ran,s);const o=n.ran.filter((e=>!e.ok)).length;return u({ok:0===o,ran:n.ran.map((e=>({id:e.id,ok:e.ok,error:e.error||null,ms:e.ms}))),failed:o},n.ran.length?`aegiscode: ${n.ran.length} task(s) run${o?`, ${o} failed`:""}`:"aegiscode: nothing pending"),o?1:0}}finally{process.removeListener("SIGINT",g)}return o.write(usageText()),2}function usageText(){return["aegiscode autonomous <command> — the unattended work queue","","Commands:",' add "<task>" queue a task (--cwd, --class, --model, --effort, --commit,'," --single-pass, --workers N, --max-rounds N)"," --class aegis|byok|local|pro (default aegis); --model must"," match the class (pro takes a claude alias, or none at all)"," list show queued tasks and the tail of the runs log"," run drain ONE task, then stop"," proceed drain every pending task (--max N, --stop-on-error, --commit)"," reconcile queue the next unfinished PLAN.md phase (--auto drains it)"," retry <id> put a finished task back in the queue"," clear drop finished tasks (--all empties the queue)","","Options:"," --json emit JSON instead of text (also on add/list/clear/retry)","","A drain runs with tool approval DISABLED (nobody is there to click a card),","one task at a time, and commits only the paths the task itself changed."].join("\n")+"\n"}module.exports={runQueueCommand:runQueueCommand,parseFlags:parseFlags,taskLine:taskLine,usageText:usageText,SUBCOMMANDS:SUBCOMMANDS};
|
|
3
|
+
"use strict";const{spawn:spawn,spawnSync:spawnSync}=require("node:child_process"),os=require("node:os"),fs=require("node:fs"),path=require("node:path"),{queue:queue,autonomous:autonomous}=require("./deps.js"),{createEngine:createEngine,proEnabled:proEnabled}=require("./engine.js"),{loadConfig:loadConfig}=require("./config.js"),{fmtElapsed:fmtElapsed}=require("./format.js"),limits=require("./limits.js"),SUBCOMMANDS=new Set(["add","list","run","proceed","start","tick","timer","report","reconcile","clear","retry","help"]),EXECUTES=new Set(["run","proceed","start","tick","timer","retry","reconcile"]),DEFAULT_MAX_LOAD=4;function parseFlags(e){const t={terms:[],json:!1,flags:{}},r=new Set(["cwd","model","effort","workers","max","max-rounds","source","class","since","max-load","every"]);for(let n=0;n<e.length;n++){const s=e[n];if("--json"!==s){if(s.startsWith("--")){const[o,i]=s.slice(2).split("="),a=o.trim();if(new Set(["commit","all","auto","stop-on-error","single-pass","help","wait"]).has(a)){t.flags[a]=!0;continue}if(!r.has(a))throw new Error(`unknown option: --${a}`);const u=void 0!==i?i:e[++n];if(void 0===u)throw new Error(`--${a} needs a value`);t.flags[a]=u;continue}t.terms.push(s)}else t.json=!0}return t}function intFlag(e,t){const r=e[t];if(void 0===r||""===r)return null;const n=Number.parseInt(r,10);return Number.isFinite(n)&&n>0?n:null}function taskLine(e){const t=e.model||"(default)",r=String(e.status||"?").padEnd(7),n=`#${e.id}`.padEnd(4),s=String(e.task||"").replace(/\s+/g," ").trim();return`${n} ${r} ${t} ${s.length>72?`${s.slice(0,71)}…`:s}`}function describeCounts(e){const t={pending:0,running:0,done:0,error:0};for(const r of e)void 0!==t[r.status]&&(t[r.status]+=1);return t}function printRunReport(e,t){for(const r of e){const e=Boolean(r.ok&&r.stoppedOnRounds),n=e?"⏸":r.ok?"✓":"✗",s=e?"paused — will resume":r.ok?"done":"failed";if(t.stdout.write(`aegiscode: ${n} #${r.id} ${s} (${fmtElapsed(r.ms)})`),r.commit&&r.commit.ok&&r.commit.staged?t.stdout.write(` — committed ${r.commit.staged} path(s)`):r.commit&&r.commit.skipped&&r.commit.reason&&t.stdout.write(` — no commit (${r.commit.reason})`),t.stdout.write("\n"),!r.ok&&r.error&&t.stderr.write(`aegiscode: #${r.id}: ${r.error}\n`),r.ok&&r.output){const e=String(r.output).trim();t.stdout.write(`${e.length>4e3?`${e.slice(0,4e3)}\n… [output clipped]`:e}\n`)}}}function buildEngine({io:e,quiet:t=!1}){const r=require("./credentials.js"),n=require("./deps.js").createClient(r.clientOptions({channel:"cli"}));if(!n.apiKey)return{error:`no AEGIS account key — ${r.HOW_TO_SET}, or set ${r.KEY_ENV}`};const s=createEngine({client:n,getConfirmMode:()=>!1,getProEnabled:()=>{try{return proEnabled(loadConfig())}catch{return!1}}});let o=null;try{o=require("./entitlement.js").createCliEntitlement({aegis:n})}catch{o=null}return{client:n,engine:s,entitlement:o}}function progressSink(e,{json:t}){return t?()=>{}:t=>{if(t&&"object"==typeof t)if("start"!==t.type){if("tool"===t.type&&t.tool&&"run"===t.tool.phase){const r=t.tool.args||{},n=r.command||r.pattern||autonomous.writtenPath(t.tool)||"",s=String(n).slice(0,100);return void e.stderr.write(` ⚙ ${t.tool.name}${s?` ${s}`:""}\n`)}"healed"!==t.type?"note"===t.type&&t.note?e.stderr.write(` ⓘ ${t.note}\n`):"recovered"===t.type&&e.stdout.write(`aegiscode: re-queued task(s) ${t.ids.join(", ")} from a dead worker\n`):e.stdout.write(`aegiscode: PLAN.md status list healed for phase(s) ${t.phases.join(", ")}\n`)}else e.stdout.write(`aegiscode: #${t.taskId} running on ${t.model} in ${t.cwd}\n`)}}async function runQueueCommand(e,t,r={}){const n=r.stdout||process.stdout,s=r.stderr||process.stderr,o={stdout:n,stderr:s};let i;try{i=parseFlags(t||[])}catch(e){return s.write(`aegiscode autonomous: ${e.message}\n`),2}const a=Boolean(r.json||i.json),u=(e,t)=>{a?n.write(`${JSON.stringify(e,null,2)}\n`):void 0!==t&&n.write(t.endsWith("\n")?t:`${t}\n`)};if("help"===e||!SUBCOMMANDS.has(e))return n.write(usageText()),"help"===e?0:2;if(EXECUTES.has(e)&&limits.armed())return limits.refuse();const l=i.flags.cwd?path.resolve(String(i.flags.cwd)):process.cwd();if("add"===e){const t=i.terms.join(" ").trim();if(!t)return s.write('aegiscode autonomous add: a task needs text — `aegiscode autonomous add "…"`\n'),2;let r;try{r=queue.addTask(process.env,{task:t,cwd:l,class:i.flags.class||null,model:i.flags.model||null,effort:i.flags.effort||null,workers:intFlag(i.flags,"workers"),maxRounds:intFlag(i.flags,"max-rounds"),singlePass:Boolean(i.flags["single-pass"]),commit:Boolean(i.flags.commit),source:i.flags.source||"cli"})}catch(e){return s.write(`aegiscode autonomous add: ${e.message}\n`),2}return u({ok:!0,id:r.id,item:r,queue:queue.queuePath(process.env)},`aegiscode: queued #${r.id} — ${queue.pendingCount(queue.loadQueue(process.env))} pending`),0}if("list"===e){const e=queue.loadQueue(process.env),t=describeCounts(e);if(a)u({ok:!0,file:queue.queuePath(process.env),counts:t,tasks:e,runs:queue.readRuns(process.env,{limit:10})});else{n.write(`queue: ${queue.queuePath(process.env)}\n`),n.write(`tasks: ${e.length} (${t.pending} pending, ${t.running} running, ${t.done} done, ${t.error} error)\n`);for(const t of e)n.write(`${taskLine(t)}\n`);e.length||n.write("(empty)\n")}return 0}if("report"===e){const e=void 0!==i.flags.since?Number.parseInt(String(i.flags.since),10):null,t=intFlag(i.flags,"max")||20,r=queue.readRuns(process.env,{limit:t}),s=describeCounts(queue.loadQueue(process.env)),o=Number.isFinite(e)&&null!==e?r.filter(t=>Number(t.id)>e):r;if(a)return u({ok:!0,file:queue.runsPath(process.env),counts:s,runs:o}),0;n.write(`runs: ${queue.runsPath(process.env)}\n`),o.length||n.write(Number.isFinite(e)&&null!==e?`(nothing finished after #${e})\n`:"(no finished runs yet)\n");for(const e of o){const t="done"===e.status?"✓":"stopped"===e.status?"⏸":"✗";n.write(`${t} #${e.id} ${String(e.status||"?").padEnd(7)} ${e.model||"(default)"} ${fmtElapsed(e.ms)}\n`),n.write(` ${String(e.task||"").replace(/\s+/g," ").trim().slice(0,160)}\n`),e.error&&n.write(` error: ${String(e.error).split("\n")[0]}\n`),e.files&&e.files.length&&n.write(` files: ${e.files.slice(0,8).join(", ")}\n`)}return n.write(`queue: ${s.pending} pending, ${s.running} running, ${s.done} done, ${s.error} error\n`),0}if("clear"===e){const e=queue.clearQueue(process.env,{all:Boolean(i.flags.all)});return u({ok:!0,...e},`aegiscode: removed ${e.removed} finished task(s); ${e.kept} kept`),0}if("retry"===e){const e=i.terms[0];if(!e)return s.write("aegiscode autonomous retry: which task? `aegiscode autonomous retry <id>`\n"),2;const t=queue.retryTask(process.env,e);return t?(u({ok:!0,id:t.id,item:t},`aegiscode: #${t.id} is pending again`),0):(s.write(`aegiscode autonomous retry: no task #${e}\n`),1)}if("start"===e){const t=queue.loadQueue(process.env).filter(e=>"running"===e.status&&e.pid);if(t.length)return s.write(`aegiscode autonomous start: #${t[0].id} is already running (pid ${t[0].pid})\n`),1;const r=["autonomous","proceed"];i.flags.commit&&r.push("--commit"),intFlag(i.flags,"max")&&r.push("--max",String(intFlag(i.flags,"max"))),i.flags["stop-on-error"]&&r.push("--stop-on-error");const n=process.argv[1];if(!n)return s.write("aegiscode autonomous start: cannot locate the CLI entry point to detach\n"),2;let o;try{o=spawn(process.execPath,[n,...r],{cwd:l,env:process.env,detached:!0,stdio:"ignore"})}catch(e){return s.write(`aegiscode autonomous start: could not spawn the drain — ${e.message}\n`),1}return o.unref(),u({ok:!0,pid:o.pid,log:queue.dataDir(process.env)},`aegiscode: drain started in the background (pid ${o.pid})\n it writes ~/.aegiscode/runs.jsonl as tasks settle — read it back with \`aegiscode autonomous report\``),0}if("timer"===e){const t=(i.terms[0]||"status").toLowerCase(),r=intFlag(i.flags,"every")||5,o=void 0!==i.flags["max-load"]?Number(i.flags["max-load"]):4;if(!Number.isFinite(o)||o<0)return s.write("aegiscode autonomous timer: --max-load needs a number >= 0 (0 disables the gate)\n"),2;const c=process.argv[1]?path.resolve(process.argv[1]):null;if(!c)return s.write("aegiscode autonomous timer: cannot locate the CLI entry point to schedule\n"),2;const d=timerPlan({every:r,maxLoad:o,self:c,tickArgs:["autonomous","tick","--commit","--max-load",String(o)],cwd:l});if("status"===t){const e="unsupported"!==d.kind&&d.paths.every(e=>fs.existsSync(e)),t=d.state(),s=e&&("active"===t||"loaded"===t||"registered"===t||"schtasks"===d.kind),i=e&&"function"==typeof d.read?d.read():null,l=Boolean(i&&(null!=i.every||null!=i.maxLoad)),c=i&&null!=i.every?i.every:r,m=i&&null!=i.maxLoad?i.maxLoad:o;if(a)return u({ok:!0,installed:s,written:e,kind:d.kind,paths:d.paths,every:c,maxLoad:m,fromUnit:l,state:t}),0;n.write(`timer: ${d.kind} — ${s?"installed and armed":e?"WRITTEN BUT NOT ARMED":"not installed"}\n`);for(const e of d.paths)n.write(` ${fs.existsSync(e)?"✓":"·"} ${e}\n`);return n.write(` every ${c} min, load gate ${m>0?m:"off"}`+(l?" (from the installed unit)":"")+"\n"),l||e||n.write(" (requested values — nothing is installed, so nothing fires)\n"),t&&n.write(` state: ${t}\n`),s||n.write(e?"\n the units exist but the scheduler has not loaded them. finish it:\n systemctl --user daemon-reload && systemctl --user enable --now aegiscode-queue.timer\n":"\n install it: aegiscode autonomous timer install\n"),0}if("install"===t){if("unsupported"===d.kind)return s.write(`aegiscode autonomous timer: this platform (${process.platform}) has no supported scheduler\n`),2;try{d.install()}catch(e){return s.write(`aegiscode autonomous timer: install failed — ${e.message}\n`),1}return u({ok:!0,kind:d.kind,paths:d.paths,every:r,maxLoad:o},`aegiscode: timer installed — every ${r} min, load gate ${o>0?o:"off"}\n it runs: aegiscode autonomous tick --max-load ${o}\n collect what it did with \`aegiscode autonomous report\``),0}if("remove"===t){try{d.remove()}catch(e){return s.write(`aegiscode autonomous timer: remove failed — ${e.message}\n`),1}return u({ok:!0,kind:d.kind,paths:d.paths},"aegiscode: timer removed"),0}return s.write(`aegiscode autonomous timer: unknown action \`${t}\` — install | status | remove\n`),2}if("tick"===e){const e=void 0!==i.flags["max-load"]?Number(i.flags["max-load"]):4;if(!Number.isFinite(e)||e<0)return s.write("aegiscode autonomous tick: --max-load needs a number >= 0 (0 disables the gate)\n"),2;const t=os.loadavg()[0];if(e>0&&t>e)return u({ok:!0,skipped:"load",load:Number(t.toFixed(2)),maxLoad:e},`aegiscode: tick skipped — load ${t.toFixed(2)} > ${e}\n`),0}const c=buildEngine({io:r});if(c.error)return s.write(`aegiscode autonomous: ${c.error}\n`),2;if(c.entitlement)try{await c.entitlement.refresh()}catch{}const d=autonomous.createQueueWorker({engine:c.engine,env:process.env,log:progressSink(o,{json:a}),canFanOut:()=>{if(!c.entitlement)return!1;try{const e=c.entitlement.current();return Boolean(e&&!0===e.entitled)}catch{return!1}}});if(c.entitlement)try{const e=c.entitlement.current();e&&!1===e.entitled&&!1===e.degraded&&e.refusal&&(s.write(`aegiscode autonomous: ${e.refusal}\n`),s.write(" ↳ write tasks like: Do X autonomously\n"),s.write("balance"===e.wall?" ↳ unlock: top up the Token Bank, or upgrade to Unlimited\n":" ↳ unlock: Unlimited, or any Token Bank balance\n"),e.upgradeUrl&&s.write(` ${e.upgradeUrl}\n`))}catch{}const m=!!i.flags.commit||void 0;let g=0;const p=e=>()=>{g+=1,g>1&&(process.removeListener("SIGINT",f),process.removeListener("SIGTERM",h),process.removeListener("SIGHUP",k),process.exit(130));const t=queue.loadQueue(process.env).find(e=>"running"===e.status&&e.pid===process.pid);t&&d.cancel(t.id),"SIGINT"!==e&&(process.exitCode=130)},f=p("SIGINT"),h=p("SIGTERM"),k=p("SIGHUP");process.on("SIGINT",f),process.on("SIGTERM",h),process.on("SIGHUP",k);try{if("reconcile"===e){const e=await d.reconcile({cwd:l,auto:Boolean(i.flags.auto),commit:m,max:intFlag(i.flags,"max")||0,stopOnError:Boolean(i.flags["stop-on-error"])});return e.ok?(a||printRunReport(e.ran||[],o),u(e,e.exhausted?"aegiscode: every phase in PLAN.md is done — nothing to queue":`aegiscode: phase ${e.phase} queued${e.ran?` — ${e.ran.length} task(s) run`:""}`),0):(s.write(`aegiscode autonomous reconcile: ${e.error||"reconcile failed"}\n`),u(e,void 0),1)}if("proceed"===e||"run"===e||"tick"===e){const t="run"===e?1:intFlag(i.flags,"max")||0,r=await d.proceed({commit:m,max:t,stopOnError:Boolean(i.flags["stop-on-error"])});if(r.locked)return s.write(`aegiscode autonomous: another drain holds the queue lock (pid ${r.holder&&r.holder.pid})\n`),u({ok:!1,locked:!0,holder:r.holder},void 0),1;a||printRunReport(r.ran,o);const n=r.ran.filter(e=>!e.ok).length;return u({ok:0===n,ran:r.ran.map(e=>({id:e.id,ok:e.ok,error:e.error||null,ms:e.ms})),failed:n},r.ran.length?`aegiscode: ${r.ran.length} task(s) run${n?`, ${n} failed`:""}`:"aegiscode: nothing pending"),n?1:0}}finally{process.removeListener("SIGINT",f),process.removeListener("SIGTERM",h),process.removeListener("SIGHUP",k)}return n.write(usageText()),2}function timerPlan({every:e,maxLoad:t,self:r,tickArgs:n,cwd:s}){const o=Math.max(1,Math.floor(e)),i=[process.execPath,r,...n].map(shellQuote).join(" "),a=s||process.cwd();if("linux"===process.platform){const e=path.join(os.homedir(),".config","systemd","user"),t=path.join(e,"aegiscode-queue.service"),r=path.join(e,"aegiscode-queue.timer"),n=["[Unit]","Description=AEGIS Code — drain the unattended work queue (one gated tick)","","[Service]","Type=oneshot",`WorkingDirectory=${a}`,`ExecStart=${i}`,"Nice=10","TimeoutStartSec=6h",""].join("\n"),s=["[Unit]","Description=AEGIS Code — the queue tick timer","","[Timer]","OnActiveSec=1min",`OnUnitActiveSec=${o}min`,"Persistent=true","AccuracySec=30s","","[Install]","WantedBy=timers.target",""].join("\n");return{kind:"systemd-user",paths:[t,r],install(){fs.mkdirSync(e,{recursive:!0}),fs.writeFileSync(t,n),fs.writeFileSync(r,s),runScheduler(["systemctl","--user","daemon-reload"],{ignore:!0});const a=runScheduler(["systemctl","--user","enable","--now","aegiscode-queue.timer"],{ignore:!0});if(a.error||0!==a.status){const t=a.error?a.error.message:String(a.stderr||"").trim();throw new Error(`units were written to ${e}, but the scheduler refused to load them: ${t}\n finish it yourself: systemctl --user daemon-reload && systemctl --user enable --now aegiscode-queue.timer\n or use cron instead: */${o} * * * * ${i}`)}},remove(){try{runScheduler(["systemctl","--user","disable","--now","aegiscode-queue.timer"])}catch{}for(const e of[r,t])try{fs.unlinkSync(e)}catch{}try{runScheduler(["systemctl","--user","daemon-reload"])}catch{}},state(){try{const e=spawnSync("systemctl",["--user","is-active","aegiscode-queue.timer"],{encoding:"utf8"});return String(e.stdout||"").trim()||null}catch{return null}},read(){let e=null,n=null;try{const t=fs.readFileSync(r,"utf8"),n=/OnUnitActiveSec=(\d+)\s*min/.exec(t);n&&(e=Number(n[1]))}catch{}try{const e=fs.readFileSync(t,"utf8"),r=/--max-load\s+(\S+)/.exec(e);r&&(n=Number(r[1]))}catch{}return{every:e,maxLoad:n}}}}if("darwin"===process.platform){const e=path.join(os.homedir(),"Library","LaunchAgents"),t=path.join(e,"org.aegiscloud.aegiscode-queue.plist"),s="org.aegiscloud.aegiscode-queue",i=['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>"," <key>Label</key>",` <string>${s}</string>`," <key>ProgramArguments</key>"," <array>",` <string>${xmlEscape(process.execPath)}</string>`,` <string>${xmlEscape(r)}</string>`,...n.map(e=>` <string>${xmlEscape(e)}</string>`)," </array>"," <key>WorkingDirectory</key>",` <string>${xmlEscape(a)}</string>`," <key>StartInterval</key>",` <integer>${60*o}</integer>`," <key>RunAtLoad</key>"," <true/>"," <key>StandardErrorPath</key>",` <string>${xmlEscape(path.join(os.homedir(),".aegiscode","timer.log"))}</string>`,"</dict>","</plist>",""].join("\n");return{kind:"launchd",paths:[t],install(){fs.mkdirSync(e,{recursive:!0}),fs.writeFileSync(t,i),runScheduler(["launchctl","unload",t],{ignore:!0}),runScheduler(["launchctl","load","-w",t])},remove(){try{runScheduler(["launchctl","unload","-w",t])}catch{}try{fs.unlinkSync(t)}catch{}},state(){try{return 0===spawnSync("launchctl",["list",s],{encoding:"utf8"}).status?"loaded":"not loaded"}catch{return null}},read(){try{const e=fs.readFileSync(t,"utf8"),r=/<key>StartInterval<\/key>\s*<integer>(\d+)<\/integer>/.exec(e),n=/<string>--max-load<\/string>\s*<string>([^<]+)<\/string>/.exec(e);return{every:r?Math.round(Number(r[1])/60):null,maxLoad:n?Number(n[1]):null}}catch{return{every:null,maxLoad:null}}}}}if("win32"===process.platform){const e="AegisCodeQueue";return{kind:"schtasks",paths:[],install(){runScheduler(["schtasks","/Create","/tn",e,"/tr",i,"/sc","minute","/mo",String(o),"/f","/rl","LIMITED"])},remove(){try{runScheduler(["schtasks","/Delete","/tn",e,"/f"])}catch{}},state(){try{return 0===spawnSync("schtasks",["/Query","/tn",e],{encoding:"utf8"}).status?"registered":"not registered"}catch{return null}},read(){try{const t=spawnSync("schtasks",["/Query","/tn",e,"/XML"],{encoding:"utf8"}),r=String(t.stdout||""),n=/<Interval>PT(\d+)M<\/Interval>/i.exec(r),s=/--max-load\s+(\d+(?:\.\d+)?)/.exec(r);return{every:n?Number(n[1]):null,maxLoad:s?Number(s[1]):null}}catch{return{every:null,maxLoad:null}}}}}return{kind:"unsupported",paths:[],install(){},remove(){},state:()=>null,read:()=>({every:null,maxLoad:null})}}function runScheduler(e,{ignore:t=!1}={}){const[r,...n]=e,s=spawnSync(r,n,{encoding:"utf8"});if(t)return s;if(s.error)throw new Error(`${r}: ${s.error.message}`);if(0!==s.status)throw new Error(`${r} ${n.join(" ")} exited ${s.status}: ${String(s.stderr||"").trim()}`);return s}function shellQuote(e){const t=String(e);return/[\s"']/.test(t)?'"'+t.replace(/"/g,'\\"')+'"':t}function xmlEscape(e){return String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function usageText(){return["aegiscode autonomous <command> — the unattended work queue","","Commands:",' add "<task>" queue a task (--cwd, --class, --model, --effort, --commit,'," --single-pass, --workers N, --max-rounds N)"," --class aegis|byok|local|pro (default aegis); --model must"," match the class (pro takes a claude alias, or none at all)"," list show queued tasks and the tail of the runs log"," run drain ONE task, then stop"," proceed drain every pending task (--max N, --stop-on-error, --commit)"," start drain in the BACKGROUND (detached) and return its pid at once"," use this instead of `proceed` when nothing is waiting for the"," output — a long drain outlives a harness timeout this way"," (--max N, --stop-on-error, --commit)"," tick ONE drain, skipped when the machine is busy — the timer body"," (--max-load N, default 4.0; 0 disables the gate)"," timer install|status|remove the repeating timer that calls `tick`"," (--every MIN default 5, --max-load N default 4.0)"," report what finished: settled runs from the log (+ queue counts)"," --since <id> for only what happened after that task,"," --max N for more of the log"," reconcile queue the next unfinished PLAN.md phase (--auto drains it)"," retry <id> put a finished task back in the queue"," clear drop finished tasks (--all empties the queue)","","Options:"," --json emit JSON instead of text (also on add/list/clear/retry)","","A drain runs with tool approval DISABLED (nobody is there to click a card),","one task at a time, and commits only the paths the task itself changed."].join("\n")+"\n"}module.exports={runQueueCommand:runQueueCommand,parseFlags:parseFlags,taskLine:taskLine,usageText:usageText,SUBCOMMANDS:SUBCOMMANDS,timerPlan:timerPlan,DEFAULT_MAX_LOAD:4};
|
|
@@ -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 RE_ZERO=/[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE00-\uFE0F\uFE20-\uFE2F]/u,RE_WIDE=/[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA000-\uA4CF\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F64F}\u{1F680}-\u{1F6FF}\u{1F900}-\u{1F9FF}\u{1FA70}-\u{1FAFF}\u{20000}-\u{3FFFD}]/u,MODERN_WINDOWS=["WT_SESSION","WT_PROFILE_ID","ConEmuANSI","ANSICON","TERM_PROGRAM","WEZTERM_PANE","ALACRITTY_SOCKET","KITTY_WINDOW_ID"],TRUTHY_RE=/^(1|true|yes|on)$/i;function truthy(e){return null!=e&&(""===e||TRUTHY_RE.test(String(e).trim()))}function firstEnv(e,n){for(const r of n){const n=e[r];if(null!=n&&""!==n)return{name:r,value:String(n)}}return null}function modernWindows(e){return firstEnv(e,MODERN_WINDOWS)}function localeOf(e){const n=firstEnv(e,["LC_ALL","LC_CTYPE","LANG"]);return n?n.value:""}function artMode(e){const n=String(e.AEGIS_ART||"").trim().toLowerCase();return"ascii"===n||"plain"===n||"text"===n?"ascii":"unicode"===n||"native"===n||"utf8"===n||"utf-8"===n?"unicode":truthy(e.AEGIS_ASCII)||"0"===e.AEGIS_UNICODE?"ascii":truthy(e.AEGIS_UNICODE)?"unicode":"auto"}function resolveGlyphs(e,n){const r=String(e.AEGIS_STAR||"").trim().toLowerCase(),t=/^(native|wide)$/.test(r)?"native":/^(narrow|ascii)$/.test(r)?"narrow":null,o=artMode(e);return"ascii"===o?{glyphs:"ascii",face:"edges",star:"narrow",reason:"AEGIS_ART=ascii"}:"unicode"===o?{glyphs:"unicode",face:"native",star:t||"native",reason:"AEGIS_ART=unicode"}:{glyphs:"unicode",face:"native",star:t||"native",reason:"uniform default on every platform"+(t?` (AEGIS_STAR=${r})`:"")}}function resolveBackground(e=process.env,n=null){const r=String(e.AEGIS_BACKGROUND||e.AEGIS_THEME_BACKGROUND||"").trim().toLowerCase();if("light"===r)return{background:"light",known:!0,reason:"AEGIS_BACKGROUND=light"};if("dark"===r)return{background:"dark",known:!0,reason:"AEGIS_BACKGROUND=dark"};const t=String(e.TERM_BACKGROUND||"").trim().toLowerCase();if("light"===t||"dark"===t)return{background:t,known:!0,reason:`TERM_BACKGROUND=${t}`};const o=String(e.COLORFGBG||"").trim();if(o){const e=o.split(/[;:]/),n=Number(e[e.length-1]);if(Number.isInteger(n)&&n>=0&&n<=15)return{background:7===n||n>=11?"light":"dark",known:!0,reason:`COLORFGBG=${o}`}}return!n||"light"!==n.background&&"dark"!==n.background?{background:"dark",known:!1,reason:"no terminal background reported (dark default)"}:{background:n.background,known:!0,reason:n.reason||`osc11 ${n.background}`}}const PROBE_TIMEOUT_MS=120,OSC11_QUERY="]11;?",OSC11_REPLY=/\x1b\]11;([^\x07\x1b]*)(?:\x07|\x1b\\)/;function colorChannel(e){const n=parseInt(e,16);return Math.round(n/(Math.pow(16,e.length)-1)*255)}function parseBackgroundReply(e){const n=OSC11_REPLY.exec(String(null==e?"":e));if(!n)return null;const r=n[1].trim(),t=/^rgba?:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})/i.exec(r);if(t)return{r:colorChannel(t[1]),g:colorChannel(t[2]),b:colorChannel(t[3])};const o=/^#?([0-9a-f]{6})$/i.exec(r);if(o){const e=o[1];return{r:parseInt(e.slice(0,2),16),g:parseInt(e.slice(2,4),16),b:parseInt(e.slice(4,6),16)}}return null}function relativeLuminance({r:e,g:n,b:r}){const t=e=>{const n=e/255;return n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4)};return.2126*t(e)+.7152*t(n)+.0722*t(r)}const LIGHT_LUMINANCE=.5;function hexOf({r:e,g:n,b:r}){return"#"+[e,n,r].map(
|
|
3
|
+
"use strict";const RE_ZERO=/[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE00-\uFE0F\uFE20-\uFE2F]/u,RE_WIDE=/[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA000-\uA4CF\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F64F}\u{1F680}-\u{1F6FF}\u{1F900}-\u{1F9FF}\u{1FA70}-\u{1FAFF}\u{20000}-\u{3FFFD}]/u,MODERN_WINDOWS=["WT_SESSION","WT_PROFILE_ID","ConEmuANSI","ANSICON","TERM_PROGRAM","WEZTERM_PANE","ALACRITTY_SOCKET","KITTY_WINDOW_ID"],TRUTHY_RE=/^(1|true|yes|on)$/i;function truthy(e){return null!=e&&(""===e||TRUTHY_RE.test(String(e).trim()))}function firstEnv(e,n){for(const r of n){const n=e[r];if(null!=n&&""!==n)return{name:r,value:String(n)}}return null}function modernWindows(e){return firstEnv(e,MODERN_WINDOWS)}function localeOf(e){const n=firstEnv(e,["LC_ALL","LC_CTYPE","LANG"]);return n?n.value:""}function artMode(e){const n=String(e.AEGIS_ART||"").trim().toLowerCase();return"ascii"===n||"plain"===n||"text"===n?"ascii":"unicode"===n||"native"===n||"utf8"===n||"utf-8"===n?"unicode":truthy(e.AEGIS_ASCII)||"0"===e.AEGIS_UNICODE?"ascii":truthy(e.AEGIS_UNICODE)?"unicode":"auto"}function resolveGlyphs(e,n){const r=String(e.AEGIS_STAR||"").trim().toLowerCase(),t=/^(native|wide)$/.test(r)?"native":/^(narrow|ascii)$/.test(r)?"narrow":null,o=artMode(e);return"ascii"===o?{glyphs:"ascii",face:"edges",star:"narrow",reason:"AEGIS_ART=ascii"}:"unicode"===o?{glyphs:"unicode",face:"native",star:t||"native",reason:"AEGIS_ART=unicode"}:{glyphs:"unicode",face:"native",star:t||"native",reason:"uniform default on every platform"+(t?` (AEGIS_STAR=${r})`:"")}}function resolveBackground(e=process.env,n=null){const r=String(e.AEGIS_BACKGROUND||e.AEGIS_THEME_BACKGROUND||"").trim().toLowerCase();if("light"===r)return{background:"light",known:!0,reason:"AEGIS_BACKGROUND=light"};if("dark"===r)return{background:"dark",known:!0,reason:"AEGIS_BACKGROUND=dark"};const t=String(e.TERM_BACKGROUND||"").trim().toLowerCase();if("light"===t||"dark"===t)return{background:t,known:!0,reason:`TERM_BACKGROUND=${t}`};const o=String(e.COLORFGBG||"").trim();if(o){const e=o.split(/[;:]/),n=Number(e[e.length-1]);if(Number.isInteger(n)&&n>=0&&n<=15)return{background:7===n||n>=11?"light":"dark",known:!0,reason:`COLORFGBG=${o}`}}return!n||"light"!==n.background&&"dark"!==n.background?{background:"dark",known:!1,reason:"no terminal background reported (dark default)"}:{background:n.background,known:!0,reason:n.reason||`osc11 ${n.background}`}}const PROBE_TIMEOUT_MS=120,OSC11_QUERY="]11;?",OSC11_REPLY=/\x1b\]11;([^\x07\x1b]*)(?:\x07|\x1b\\)/;function colorChannel(e){const n=parseInt(e,16);return Math.round(n/(Math.pow(16,e.length)-1)*255)}function parseBackgroundReply(e){const n=OSC11_REPLY.exec(String(null==e?"":e));if(!n)return null;const r=n[1].trim(),t=/^rgba?:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})/i.exec(r);if(t)return{r:colorChannel(t[1]),g:colorChannel(t[2]),b:colorChannel(t[3])};const o=/^#?([0-9a-f]{6})$/i.exec(r);if(o){const e=o[1];return{r:parseInt(e.slice(0,2),16),g:parseInt(e.slice(2,4),16),b:parseInt(e.slice(4,6),16)}}return null}function relativeLuminance({r:e,g:n,b:r}){const t=e=>{const n=e/255;return n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4)};return.2126*t(e)+.7152*t(n)+.0722*t(r)}const LIGHT_LUMINANCE=.5;function hexOf({r:e,g:n,b:r}){return"#"+[e,n,r].map(e=>e.toString(16).padStart(2,"0")).join("")}function probeBackground({stdin:e=process.stdin,stdout:n=process.stdout,timeoutMs:r=120,onLeftover:t=null}={}){return new Promise(o=>{if(!(e&&n&&e.isTTY&&n.isTTY&&"function"==typeof e.setRawMode))return void o(null);const s=!!e.isRaw;let u="",a=!1,c=null;const i=(n,r)=>{if(!a){a=!0,c&&clearTimeout(c),e.pause(),e.removeListener("data",l);try{s||e.setRawMode(!1)}catch{}if(r)if("function"==typeof t)try{t(r)}catch{}else try{e.unshift(Buffer.from(r,"latin1"))}catch{}o(n)}},l=e=>{u+=e.toString("latin1");const n=parseBackgroundReply(u);n?i({background:relativeLuminance(n)>.5?"light":"dark",rgb:n,reason:`osc11 ${hexOf(n)}`},u.replace(OSC11_REPLY,"")):u.length>512&&i(null,u)};c=setTimeout(()=>i(null,u),r);try{e.setRawMode(!0),e.resume(),e.on("data",l),n.write("]11;?")}catch{i(null,"")}})}async function probeTerminalBackground({env:e=process.env,stdin:n=process.stdin,stdout:r=process.stdout,platform:t=process.platform,timeoutMs:o=120,onLeftover:s=null}={}){const u=resolveBackground(e),a=resolveBackground(e,u.known||"0"===String(e.AEGIS_BACKGROUND_PROBE||"").trim()?null:await probeBackground({stdin:n,stdout:r,timeoutMs:o,onLeftover:s})),c=axes();c.background=a.background,c.backgroundKnown=a.known,c.reasons&&(c.reasons.background=a.reason);for(const e of listeners)try{e(c)}catch{}return a}function resolveDepth(e){if(null!=e.NO_COLOR&&""!==e.NO_COLOR)return{depth:0,reason:"NO_COLOR"};const n=String(e.FORCE_COLOR||"").trim();if("0"===n)return{depth:0,reason:"FORCE_COLOR=0"};if(/^[123]$/.test(n))return{depth:"3"===n?24:"2"===n?8:4,reason:`FORCE_COLOR=${n}`};const r=String(e.AEGIS_COLOR||"").trim();return/^[0-3]$/.test(r)?{depth:"0"===r?0:"1"===r?4:"2"===r?8:24,reason:`AEGIS_COLOR=${r}`}:"0"===e.AEGIS_FORCE_TRUECOLOR?{depth:8,reason:"AEGIS_FORCE_TRUECOLOR=0"}:{depth:24,reason:"uniform default: truecolor on every platform"}}function resolveVt(e){const n=String(null==e.AEGIS_VT?"":e.AEGIS_VT).trim();return"0"===n?{vt:!1,reason:"AEGIS_VT=0"}:"1"===n||/^(true|yes|on)$/i.test(n)?{vt:!0,reason:"AEGIS_VT=1"}:{vt:!0,reason:"uniform default: ansi on every platform"}}function resolveSize(e,n){const r=parseInt(e.AEGIS_WIDTH||"",10),t=parseInt(e.COLUMNS||"",10),o=n&&Number.isFinite(n.columns)&&n.columns>0?n.columns:0,s=n&&Number.isFinite(n.rows)&&n.rows>0?n.rows:0,u=r>0?r:o||(t>0?t:80);return{cols:Math.max(20,Math.min(400,u)),rows:Math.max(5,s||24),reason:r>0?"AEGIS_WIDTH":o?"stdout.columns":t>0?"COLUMNS":"default 80"}}function resolveWideRunes(e){const n=new Map;for(const r of String(e.AEGIS_WIDE_RUNES||""))r.trim()&&n.set(r,2);return n}function detect(e=process.env,n=process.stdout,r=process.platform,t=null){const o=!(!n||!n.isTTY),s=resolveGlyphs(e,r),u=resolveDepth(e),a=resolveVt(e),c=resolveSize(e,n),i=resolveBackground(e,t),l="win32"===r?modernWindows(e):null;return{platform:r,isTTY:o,term:String(e.TERM||""),termProgram:String(e.TERM_PROGRAM||""),locale:localeOf(e),windowsHost:l?l.name:"",glyphs:s.glyphs,face:s.face,star:s.star,depth:u.depth,color:u.depth>0,background:i.background,backgroundKnown:i.known,vt:a.vt,cols:c.cols,rows:c.rows,eol:"\n",wideRunes:resolveWideRunes(e),reasons:{glyphs:s.reason,depth:u.reason,vt:a.reason,size:c.reason,background:i.reason}}}let cached=null,sizePinned=!1,sizeEnv=null;const listeners=[];function axes(){return cached||(cached=detect()),cached}function caps(){const e=axes();if(!sizePinned){const n=resolveSize(sizeEnv||process.env,process.stdout);e.cols=n.cols,e.rows=n.rows,e.reasons.size=n.reason}return e.pinned=sizePinned,e}function setCaps(e=null,n=process.env,r=process.stdout){cached=Object.assign(detect(n,r),e||{}),sizeEnv=n||process.env,sizePinned=!(!e||null==e.cols&&null==e.rows),e&&null!=e.cols&&cached.reasons&&(cached.reasons.size="pinned (override)");for(const e of listeners)try{e(cached)}catch{}return cached}function resetCaps(){cached=null,sizePinned=!1,sizeEnv=null}function onCapsChange(e){return listeners.push(e),()=>{const n=listeners.indexOf(e);n>=0&&listeners.splice(n,1)}}function cellWidth(e){const n=axes();if(n.wideRunes&&n.wideRunes.size){const r=n.wideRunes.get(e);if(null!=r)return r}return RE_ZERO.test(e)?0:RE_WIDE.test(e)?2:1}function cells(e){let n=0;for(const r of String(e))n+=cellWidth(r);return n}function padCells(e,n){const r=n-cells(e);return r>0?e+" ".repeat(r):e}function rgbTo256(e,n,r){if(e===n&&n===r)return e<8?16:e>248?231:232+Math.round((e-8)/247*24);const t=e=>Math.round(e/255*5);return 16+36*t(e)+6*t(n)+t(r)}function rgbTo16(e,n,r){const t=[[0,0,0,30],[205,0,0,31],[0,205,0,32],[205,205,0,33],[0,0,238,34],[205,0,205,35],[0,205,205,36],[229,229,229,37]];let o=t[7],s=1/0;for(const u of t){const t=(e-u[0])**2+(n-u[1])**2+(r-u[2])**2;t<s&&(s=t,o=u)}return o[3]}function rgb(e,n,r){const t=caps().depth;return t>=24?`[38;2;${e};${n};${r}m`:t>=8?`[38;5;${rgbTo256(e,n,r)}m`:t>=4?`[${rgbTo16(e,n,r)}m`:""}function bg(e,n,r){const t=caps().depth;return t>=24?`[48;2;${e};${n};${r}m`:t>=8?`[48;5;${rgbTo256(e,n,r)}m`:t>=4?`[${rgbTo16(e,n,r)+10}m`:""}function describe(e=caps()){const n=[e.platform,e.isTTY?"":"(no tty)"].filter(Boolean).join(" ");return[["platform",e.windowsHost?`${n} — ${e.windowsHost}`:n],["terminal",e.termProgram||e.term||"unknown"],["locale",e.locale||"unset"],["background",`${e.background} (${e.reasons.background})`],["mark","ascii"===e.glyphs?"ascii":"edges"===e.face?"unicode (edges stencilled)":"unicode"],["star",e.star],["color",0===e.depth?"none":e.depth>=24?"truecolor":e.depth>=8?"256":"16"],["control",e.vt?"ansi":"plain"],["size",`${e.cols}x${e.rows} (${e.reasons.size})`],["eol","\\n"],["why",`${e.reasons.glyphs}; ${e.reasons.depth}`]]}module.exports={detect:detect,caps:caps,setCaps:setCaps,resetCaps:resetCaps,onCapsChange:onCapsChange,cellWidth:cellWidth,cells:cells,padCells:padCells,rgb:rgb,bg:bg,rgbTo256:rgbTo256,rgbTo16:rgbTo16,describe:describe,resolveGlyphs:resolveGlyphs,resolveDepth:resolveDepth,resolveBackground:resolveBackground,resolveVt:resolveVt,resolveSize:resolveSize,MODERN_WINDOWS:MODERN_WINDOWS,probeBackground:probeBackground,probeTerminalBackground:probeTerminalBackground,parseBackgroundReply:parseBackgroundReply,relativeLuminance:relativeLuminance,PROBE_TIMEOUT_MS:120,LIGHT_LUMINANCE:.5,OSC11_QUERY:"]11;?"};
|