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,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{getSize:getSize,span:span,padLine:padLine,paint:paint,w:w,wrapBlock:wrapBlock,hideCursor:hideCursor,showCursor:showCursor,moveTo:moveTo,clearScreen:clearScreen,enterAltScreen:enterAltScreen,leaveAltScreen:leaveAltScreen,enableBracketedPaste:enableBracketedPaste,disableBracketedPaste:disableBracketedPaste,enableMouseTracking:enableMouseTracking,disableMouseTracking:disableMouseTracking,selectionRange:selectionRange,selectionText:selectionText,applySelection:applySelection}=require("./screen.js"),{KEY:KEY,STREAM_END:STREAM_END,attachKeyStream:attachKeyStream,nextKey:nextKey,nextKeyTimeout:nextKeyTimeout,requeueKeys:requeueKeys,resetKeyStream:resetKeyStream,markSessionStart:markSessionStart,isKeyStreamSuspended:isKeyStreamSuspended}=require("./events.js"),{GLYPH:GLYPH,VERBS:VERBS,DONE_VERBS:DONE_VERBS,BOLD:BOLD,BOLD_OFF:BOLD_OFF,themeOf:themeOf,RGB:RGB}=require("./theme.js"),{LineEditor:LineEditor}=require("./input.js"),{renderMarkdown:renderMarkdown}=require("./markdown.js"),overlays=require("./overlays.js"),models=require("./models.js"),{resolveShared:resolveShared}=require("./sharedpaths.js"),{validateApiKey:validateApiKey}=require(resolveShared(require("node:path").join("client","credentials.js"))),sessionSearch=require(resolveShared(require("node:path").join("client","session-search.js"))),claudePro=require(resolveShared(require("node:path").join("desktop","lib","local","claude-pro.js"))),fuzzy=require("./fuzzy.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,fmtElapsed:fmtElapsed,fmtUsageSplit:fmtUsageSplit,displayTokens:displayTokens,pathName:pathName,feeBillable:feeBillable}=require("./format.js"),{editPreview:editPreview}=require("./diff.js"),{renderDiffBlock:renderDiffBlock,defaultOpen:defaultOpen}=require("./diffview.js"),{copyToClipboard:copyToClipboard,describeCopy:describeCopy,readClipboardText:readClipboardText,readClipboardImage:readClipboardImage}=require("./clipboard.js"),{transcriptToMarkdown:transcriptToMarkdown}=require("./export.js"),fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir,loadConfig:loadConfig}=require("./config.js"),{effortRung:effortRung}=require("./engine.js"),{usageBuckets:usageBuckets,estimateTokensFromCells:estimateTokensFromCells}=require("./tokens.js"),{pingTurn:pingTurn}=require("./ping.js"),SUGGESTIONS=["edit <filepath> to...","refactor <filepath>","how do I log an error?","write a test for <filepath>","create a util logging.py that..."],{TITLE_SPIN:TITLE_SPIN,titleText:titleText,topicFrom:topicFrom,adoptTopic:adoptTopic,titleEnabled:titleEnabled,writeTitle:writeTitle}=require("./title.js"),{GENERIC_TITLE:GENERIC_TITLE,isGenericTitle:isGenericTitle}=require("./naming.js"),FRAME_MS=33;function isShellTool(e){return"exec"===e||"Bash"===e}function isAgentTool(e){return"task"===e||"Task"===e}function toolLabel(e,t){const n=isShellTool(e)?"shell command":isAgentTool(e)?"subagent":`${String(e).toLowerCase()} command`;return t>1?n+"s":n}function resolveToolDone(e,t){let n=-1;if(void 0!==t.id)for(let r=e.length-1;r>=0;r--){const o=e[r];if("tool"===o.role&&"run"===o.phase&&o.id===t.id){n=r;break}}if(-1===n)for(let r=e.length-1;r>=0;r--){const o=e[r];if("tool"===o.role&&"run"===o.phase&&o.name===t.name&&o.agent===t.agent){n=r;break}}if(-1===n)return null;const r=e[n],o=e.filter(((e,r)=>"tool"===e.role&&e.name===t.name&&e.agent===t.agent&&r<=n)).length;return r.phase="done",r.elapsed=t.elapsed,r.ok=t.ok,r.label=`Ran ${o} ${r.agent?`${r.agent} ▸ `:""}${toolLabel(t.name,o)}`,r}const MUTATING_FILES=new Set(["Edit","Write","MultiEdit","NotebookEdit","editFile","writeFile"]);function summarizeTurnTools(e,{maxNames:t=3}={}){const n=[],r=[];let o=0;for(const t of e||[]){if(!t)continue;!1===t.ok&&(o+=1);const e=t.args;if(!e||"object"!=typeof e)continue;const s=MUTATING_FILES.has(t.name)?e.file_path||e.path||e.notebook_path:null;"string"==typeof s&&s&&!n.includes(s)&&n.push(s);const i=e.command;if("string"==typeof i&&i.trim()){const e=pathName(i.trim().split(/\s+/)[0]);e&&!r.includes(e)&&r.push(e)}}return{tools:(e||[]).length,failed:o,files:n,names:n.slice(0,t).map((e=>pathName(e))),more:Math.max(0,n.length-t),commands:r}}function finalizeTurnText(e,{aborted:t,error:n,reasoned:r}={}){let o=String(null==e?"":e);if(n&&!t&&"stopped"!==n){const e=`(backend error: ${n})`;o=o.trim()?`${o.trimEnd()}\n\n${e}`:e}return t&&(o=o.trim()?`${o.trimEnd()} (stopped)`:"(stopped)"),o.trim()||(o=r?"(no answer — the model used its whole budget on hidden reasoning before writing one; retry, or raise the budget with /effort)":"(no response)"),o}function historyPairs(e){return e.filter((e=>"user"===e.role||"assistant"===e.role)).map((e=>({role:e.role,content:e.text})))}const PRO_ALIAS_KEYWORDS=Object.freeze(["opus","haiku","sonnet","fable"]);function overrideAnthropicByokWithPro(e,t={}){if(!e||"byok"!==e.cls)return{row:e,message:null};const n=String(e.id||""),r=n.indexOf(":");if(r<0||"anthropic"!==n.slice(0,r).trim().toLowerCase())return{row:e,message:null};if(!t.needsKey)return{row:e,message:null};if(!t.proLoggedIn)return{row:e,message:null};if(!0!==t.proEnabled)return{row:e,message:null};const o=n.slice(r+1).toLowerCase(),s=Array.isArray(t.proModels)&&t.proModels.length?t.proModels:[{id:"default",label:"Default",note:""}],i=PRO_ALIAS_KEYWORDS.find((e=>o.includes(e)))||"default",a=s.find((e=>e.id===i))||s[0];return{row:{id:a.id,label:a.label,note:a.note,cls:"pro"},message:`${n} has no Anthropic console key on this machine, but Claude Code Pro is signed in — using the subscription instead (claude --model ${a.id}). Add a real console key any time with /byok-key anthropic <key> to run this row directly.`}}function paletteQuery(e){const t=String(e||"").trim();return t.includes(" ")?t.split(/\s+/)[0]:t}function headerLine(e,t,n){const r=themeOf(n),o=` AEGIS Code v${e} `,s=Math.max(0,t-[...o].length-2),i=Math.floor(s/2);return[span(r.coral,`╭${"─".repeat(i)}${o}${"─".repeat(s-i)}╮`)]}const separatorLine=(e,t)=>[span(themeOf(t).dim,"─".repeat(e))];function effortLine(e,t){const n=themeOf(e),r=`● ${effortRung(e.effort)} · /effort`,o=" ".repeat(Math.max(0,t-[...r].length-4));return[span(n.gray,o+r)]}const SPINNER_TINT=RGB(235,159,127);function spinnerLine(e,t){const n=themeOf(t),r=Math.max(1,Math.round((e.elapsedMs||0)/1e3)),o=[...e.verb||VERBS[0]],s=Math.floor((e.frame||0)/2)%3,i=o.map(((e,t)=>span((t+s)%3==0?n.coral:SPINNER_TINT,e))),a=t&&t.thinking?span(n.gray,` (${r}s · thinking)`):span(n.gray,` (${r}s · ↓${e.streamedFloor?"≥":""}${fmtTokens(e.streamed||0)} tokens)`),l=GLYPH.spin[(e.frame||0)%GLYPH.spin.length];return[span(n.coral,l),...i,span(n.white,"… "),a]}function statusLine(e,t,n){const r=themeOf(n);let o;return o=e.inputPrompt?[span(r.gray,"enter to confirm · esc to cancel")]:e.working?[span(r.gray,` ${GLYPH.bullet} esc to interrupt`)]:e.streamJob?[span(r.gray,`${GLYPH.bullet} esc to stop`)]:e.keyNotice?[span(r.gray,` ${GLYPH.bullet} no AEGIS key: ${e.keyNotice} ${GLYPH.bullet} /key register to retry`)]:e.yolo?[span(r.gray,`${GLYPH.bullet} automode on ${GLYPH.bullet} ${autoContinueLimit()} rounds then it asks ${GLYPH.bullet} ? for shortcuts ${GLYPH.bullet} ${GLYPH.rightarrow} for manual mode`)]:[span(r.gray,`${GLYPH.pause} manual mode on ${GLYPH.bullet} ? for shortcuts ${GLYPH.bullet} ${GLYPH.rightarrow} for auto mode`)],padLine(o,t)}function shortcutsGrid(e,t){const n=themeOf(t),r=(e,t,r,o)=>[span(""," "),span(n.white,e),span(n.gray," "+t),span(""," "),span(n.white,r),span(n.gray," "+o)];return[r("/","for commands","?","for shortcuts"),r("ctrl + c","to quit","ctrl + o","for permissions"),r("alt + p","to switch model","alt + t","to toggle thinking"),r("shift + ↑/↓","pins as it moves","shift + enter","runs the row"),r("esc","to interrupt a turn","ctrl + l","to clear the screen"),r("ctrl + t","to show tokens","ctrl + r","to resume a session"),r("↑ / ↓","for history","tab","to complete a command")]}const APPROVE_ONCE="once",APPROVE_SESSION="session",DENY_TOKEN="deny",APPROVAL_CHOICES=["Yes","Yes, allow for this session","No"],APPROVAL_DECISIONS=["once","session","deny"];function confirmLines(e,t,n){const r=themeOf(n),o=[];o.push([span(r.gray,"─".repeat(Math.min(Math.max(10,t-4),80)))]),o.push([span(r.white,`${isShellTool(e.name)?"shell":e.name} command`)]),o.push([span("","")]);const s=isShellTool(e.name)?String(e.args&&e.args.command||""):String(e.args&&(e.args.file_path||e.args.pattern)||"");for(const e of wrapBlock(s,Math.max(8,t-4)))o.push([span(r.gray,e)]);o.push([span("","")]),o.push([span(r.white,"Do you want to proceed?")]);const i=e.name||"this tool";return APPROVAL_CHOICES.forEach(((t,n)=>{const s=1===n?`Yes, and allow ${i} for this session`:t;o.push(((t,n)=>{const o=e.sel===t;return[o?span(r.lavender,GLYPH.cursor):span(""," "),span(r.gray,` ${t+1}. `),span(o?r.lavender:r.white,n)]})(n,s))})),o.push([span("","")]),o.push([span(r.gray,"Esc to cancel")]),o}const AUTO_CONTINUE_LIMIT=3;function autoContinueLimit(e=process.env){const t=Number.parseInt(e&&e.AEGIS_AUTO_CONTINUE_MAX,10);return Number.isFinite(t)&&t>0?t:AUTO_CONTINUE_LIMIT}function autoContinuePlan({on:e=!1,used:t=0,limit:n=autoContinueLimit()}={}){const r=Number.isFinite(n)&&n>0?Math.floor(n):AUTO_CONTINUE_LIMIT,o=Number.isFinite(t)&&t>0?Math.floor(t):0;return e?o>=r?{auto:!1,used:0,cap:r}:{auto:!0,used:o+1,cap:r}:{auto:!1,used:o,cap:r}}function roundsLines(e,t,n){const r=themeOf(n),o=[];o.push([span(r.gray,"─".repeat(Math.min(Math.max(10,t-4),80)))]),o.push([span(r.white,`${e.spent}-round tool limit reached`)]),o.push([span("","")]);for(const e of wrapBlock("The turn is still working — it ended its last round on a tool call instead of an answer.",Math.max(8,t-4)))o.push([span(r.gray,e)]);o.push([span("","")]);const s=(t,n)=>{const o=e.sel===t;return[o?span(r.lavender,GLYPH.cursor):span(""," "),span(r.gray,` ${t+1}. `),span(o?r.lavender:r.white,n)]};return o.push(s(0,`Yes, continue with ${e.size} more rounds`)),o.push(s(1,"No, stop here and answer with what I have")),o.push([span("","")]),o.push([span(r.gray,`extension ${e.extensions} of ${e.max} · Esc to stop`)]),o}function metaBits(e,t,{omitMs:n=!1}={}){const r=[];e.model&&r.push(span(t.blue,e.model));const o=fmtUsageSplit(e);if(o)r.push(span(t.white,o.output));else{const n=displayTokens(e);null!=n&&r.push(span(t.white,`${fmtTokens(n)} tokens`))}return null!=e.eur&&feeBillable()&&r.push(span(e.eur>0?t.coral:t.green,fmtEur(e.eur))),null==e.ms||n||r.push(span(t.gray,fmtElapsed(e.ms))),e.calls>1&&r.push(span(t.gray,`${e.calls} calls`)),r}function joinBits(e,t){const n=[];return e.forEach(((e,r)=>{r&&n.push(span(t.dim,` ${GLYPH.bullet} `)),n.push(e)})),n}const DIR_MAX=40;function shortDir(e){let t=String(null==e?"":e).trim().replace(/\/+$/,"");if(!t)return"";const n=String(process.env.HOME||process.env.USERPROFILE||"").replace(/\/+$/,"");return n&&(t===n||t.startsWith(`${n}/`))&&(t=`~${t.slice(n.length)}`),t.length>DIR_MAX&&(t=`${GLYPH.ellipse}${t.slice(-(DIR_MAX-1))}`),t}function rowLines(e,t,n,r=Date.now()){const o=themeOf(n),s=[];if("tool"===e.role){const i=String(e.label||"").replace(/(?:…|\.\.\.)+$/,""),a=e.cwd?` · ${shortDir(e.cwd)}`:"";if("run"===e.phase){const t=e.start?Math.max(1,Math.round((r-e.start)/1e3)):0;s.push([span(o.gray,`${i}${GLYPH.ellipse} · ${t}s${a}`)])}else s.push([span(o.gray,`${i}${a}`)]);if(e.diff){for(const r of renderDiffBlock(e.diff,n,t,{open:!!e.diffOpen}))s.push([span("",r)]);return s}const l="string"==typeof e.args?e.args:e.args&&"object"==typeof e.args?e.args.command??e.args.file_path??e.args.description??Object.values(e.args).find((e=>"string"==typeof e))??"":"";return l&&s.push([span(o.gray,` ${GLYPH.hook} $ ${String(l)}`)]),s}if("note"===e.role)return s.push([span(o.gray,`· ${e.text}`)]),s;if("tip"===e.role){for(const n of wrapBlock(String(e.text),t))s.push([span(o.gray,n)]);return s}if("done"===e.role){const t=[span(o.gray,GLYPH.bloom),span(o.gray,` ${e.text}`)];if(e.meta){const n=metaBits(e.meta,o,{omitMs:!0});n.length&&t.push(span(o.dim," "),...joinBits(n,o))}return s.push(t),s}if("summary"===e.role){const t=e.counts||{};if(!t.tools)return s;const n=[span(o.dim,GLYPH.hook),span(""," ")],r=[span(o.white,String(t.tools)),span(o.gray," "+(1===t.tools?"command":"commands"))];if(t.files&&t.files.length&&(r.push(span(o.gray,` ${GLYPH.bullet} `)),r.push(span(o.white,String(t.files.length)),span(o.gray," "+(1===t.files.length?"file changed":"files changed")))),t.failed&&(r.push(span(o.gray,` ${GLYPH.bullet} `)),r.push(span(o.coral,`${t.failed} failed`))),t.names&&t.names.length){const e=t.more?` +${t.more}`:"";r.push(span(o.dim,` ${t.names.join(", ")}${e}`))}return n.push(...r),s.push(n),s}if("meta"===e.role){const t=metaBits(e.meta||{},o);return t.length&&s.push([span(o.dim,`${GLYPH.hook} `),...joinBits(t,o)]),s}if("panel"===e.role){for(const n of e.lines||[])s.push(padLine(n,t));return s.push([span("","")]),s}if("error"===e.role)return s.push([span(o.red,`✗ ${e.text}`)]),s;if("user"===e.role)return wrapBlock(String(e.text),Math.max(8,t-2)).forEach(((e,t)=>{0===t?s.push([span(o.gray,GLYPH.cursor),span(""," "),span(o.white,e)]):s.push([span(""," "),span(o.white,e)])})),s;const i="assistant"===e.role?renderMarkdown(String(null==e.text?"":e.text),t,n):wrapBlock(String(null==e.text?"":e.text),t).map((e=>[span(o.white,e)])),a=i.length?i:[[span("","")]];for(let e=0;e<a.length;e++){const t=a[e].slice();0===e&&t.unshift(span(o.white,GLYPH.block),span(""," ")),s.push(t)}return s}function transcriptLines(e,t,n,r=Date.now(),o=null){const{cols:s,rows:i}=t,a=Math.max(1,i-6),l=[],u=[];for(const t of e){const e=o||null,i="assistant"===t.role&&t.streaming||"tool"===t.role&&"run"===t.phase;if(!e||i)for(const e of rowLines(t,s,n,r))l.push(e),u.push(t);else{const o=e.get(t);if(o&&o.text===t.text&&o.cols===s&&o.diffOpen===t.diffOpen){for(const e of o.segment)l.push(e),u.push(t);continue}const i=rowLines(t,s,n,r);e.set(t,{text:t.text,cols:s,diffOpen:t.diffOpen,segment:i});for(const e of i)l.push(e),u.push(t)}}let c=t.scroll||0,p=null==t.anchorEnd?null:t.anchorEnd;const d=l.length,f=Math.max(0,d-a);let m;c>f&&(c=f),0===c?(p=null,m=d):(null===p&&(p=Math.max(0,d-c)),m=Math.min(p,d)),d<=a&&(c=0,p=null,m=d);const h=Math.max(0,m-a);return{lines:l.slice(h,m),owners:u.slice(h,m),scroll:c,anchorEnd:p}}function inputPreviewText(e){const t=e.indexOf("\n");if(-1===t)return e;const n=e.split("\n").length-1;return`${e.slice(0,t)} … (+${n} line${1===n?"":"s"})`}const inputRowCells=e=>Math.max(1,e-3),bufCells=e=>[...e].reduce(((e,t)=>e+w(t)),0);function cursorCells(e,t){const n=[...e];let r=0;for(let e=0;e<Math.min(t,n.length);e++)r+=w(n[e]);return r}function inputScroll(e,t,n){const r=inputRowCells(n),o=bufCells(e);if(o<=r)return 0;const s=r-1;return Math.max(0,Math.min(cursorCells(e,t)-s,o-s))}function inputStart(e,t){const n=[...e];let r=0;for(let e=0;e<n.length;e++){if(r>=t)return e;r+=w(n[e])}return n.length}function inputLine(e,t,n){const r=themeOf(n),o=[span(r.gray,GLYPH.cursor),span(""," ")];if(e.inputPrompt){o.push(span(r.white,`${e.inputPrompt.title}: `));for(const t of[...e.inputPrompt.buf])o.push(span(r.white,t));const n=Math.min(3+w(e.inputPrompt.title)+2+w(e.inputPrompt.buf),t);return{line:padLine(o,t),cursorCol:n}}if(e.working)return{line:padLine(o,t),cursorCol:3};const s=e.buf||"";if(!s.length){if(e.insertMode)return{line:padLine(o,t),cursorCol:3};const n=SUGGESTIONS[(e.suggestionIdx||0)%SUGGESTIONS.length];return o.push(span(r.white+BOLD,`Try "${n}"`),span(BOLD_OFF,"")),{line:padLine(o,t),cursorCol:3}}if(s.includes("\n")){const e=inputPreviewText(s);for(const t of[...e])o.push(span(r.white,t));return{line:padLine(o,t),cursorCol:Math.min(3+w(e),t)}}const i=inputScroll(s,e.cursor,t),a=inputStart(s,i);i>0&&o.push(span(r.dim,"…"));const l=[...s];for(let e=a;e<l.length;e++)o.push(span(r.white,l[e]));const u=l.slice(a,Math.min(e.cursor,l.length)).join(""),c=Math.min(3+(i>0?1:0)+w(u),t);return{line:padLine(o,t),cursorCol:c}}async function runSession(e){const t=e.ctx,n=new LineEditor,r=e.transcript,o=new WeakMap;let s=null;function i(t){const n=paletteQuery(null==t?s&&s.query||"":t);return fuzzy.fuzzyRankWithAliases(n,e.visibleCommands(),(e=>e.name),(e=>e.aliases||[]))}let a=0,l=!1,u=null,c=0,p=null,d=0,f=VERBS[0],m=0,h=0,g=[],y=0,E=0,S=null;const v=new Map;let T=null,C=null,L=[],b=!1,k=0,P="",$=null,x=null,O=0,Y=null,I="",K="",R=!1,A=!0;try{A=titleEnabled(process.env,e.loadConfig?e.loadConfig():e.config||{})}catch{A=!0}let M=!1,_=0;const N=e=>{if(!A)return;const t=e?TITLE_SPIN[Math.floor(c/2)%TITLE_SPIN.length]:null;writeTitle(titleText({topic:I,frame:t}),process.stdout)},D=t=>{if("function"!=typeof e.nameConversation)return;let n;R=!0;try{n=Promise.resolve(e.nameConversation(t,{signal:u?u.signal:null}))}catch{return}n.then((e=>{const t=String(e||"").trim();t&&(K=t,I=t,N(!!l),B())})).catch((()=>{}))},G=e=>{P=e,k=Date.now()+2500,setTimeout((()=>{Date.now()>=k&&B()}),2600),B()},B=()=>{if(isKeyStreamSuspended())return;const i=getSize().cols,{lines:a,inputCol:u,rows:p,inputRow:m}=(()=>{const{cols:s,rows:i}=getSize(),a=[];a.push(headerLine(e.version,s,t));const u=Math.max(1,i-6),p=transcriptLines(r,{cols:s,rows:i,scroll:E,anchorEnd:S},t,Date.now(),o);E=p.scroll,S=p.anchorEnd,v.clear();for(let e=0;e<p.lines.length;e++)v.set(1+e,p.owners[e]);for(const e of p.lines)a.push(e);for(;a.length<u+1;)a.push([span("","")]);const m=themeOf(t);if(l)a.push(spinnerLine({verb:f,frame:c,elapsedMs:Date.now()-d,streamed:estimateTokensFromCells(W())+V,streamedFloor:V>0},t));else if(Date.now()<k)a.push([span(m.gray,` ${P}`)]);else if(x){const e=Math.max(1,Math.round((Date.now()-O)/1e3));a.push([span(m.gray,` ${x.label||"running"}… (${e}s · esc to stop)`)])}else a.push(effortLine(t,s));a.push(separatorLine(s,t));const h=inputLine({buf:n.buf,cursor:n.cursor,working:l,insertMode:b,suggestionIdx:y,inputPrompt:$},s,t);return a.push(h.line),a.push(separatorLine(s,t)),a.push(statusLine({working:l,inputPrompt:$,streamJob:x,yolo:e.isYolo&&e.isYolo(),keyNotice:e.keyNotice&&e.keyNotice()},s,t)),{lines:a,inputCol:h.cursorCol,rows:i,inputRow:i-2}})();s&&H(a,p,i),L=a,paint(T?applySelection(a,selectionRange(T.anchor,T.head),i):a),_=Date.now(),s?hideCursor():$||!l?(moveTo(m,u),showCursor()):hideCursor()},q=()=>{if(M)return;M=!0;const e=Math.max(0,33-(Date.now()-_));setTimeout((()=>{M=!1,B()}),e)},H=(n,r,o)=>{if(!s)return;let i=null;if("palette"===s.type?i=overlays.renderPalette(e.visibleCommands(),{query:paletteQuery(s.query),sel:s.sel},o,r):"model"===s.type?i=overlays.renderModelPicker(s.items||[],s.sel||0,o,r,s.current,s.cls||t.modelClass,"function"==typeof e.classLabel?e.classLabel:null):"effort"===s.type?i=overlays.renderEffortPicker(s.sel||0,o,t.effort):"class"===s.type?i=overlays.renderClassPicker(s.items||[],s.sel||0,o,s.current||t.modelClass,"function"==typeof e.classLabel?e.classLabel:null):"provider"===s.type?i=overlays.renderProviderPicker(s.items||[],s.sel||0,o,s.current,s.hint):"resume"===s.type?i=overlays.renderResumeList(s.items||[],s.sel||0,o,r,s.query||""):"shortcuts"===s.type?i=shortcutsGrid(o,t):"confirm"===s.type?i=confirmLines(s,o,t):"rounds"===s.type?i=roundsLines(s,o,t):"panel"===s.type&&(i=s.lines||[]),!i)return;if("shortcuts"===s.type){const e=Math.max(2,r-i.length-1);for(let t=0;t<i.length;t++)n[e+t]=padLine(i[t],o);return void hideCursor()}const a=Math.max(2,Math.floor((r-i.length)/2));for(let e=0;e<i.length;e++)n[a+e]=padLine(i[e],o);hideCursor()},j=(e,t)=>(r.push(e),t&&!1===t.follow||(E=0,S=null),e),F=(e,t)=>{const n=t?r.indexOf(t):-1;return n<0?r.push(e):r.splice(n,0,e),e},U=e=>j({role:"note",text:e},{follow:!1});let z=0,V=0;const W=()=>z;let Q=Promise.resolve();const X=e=>{const t=Q.then(e,e);return Q=t.then((()=>{}),(()=>{})),t},J=async t=>{l=!0,c=0,d=Date.now(),z=0,V=0,h=0,g=[],f=VERBS[m%VERBS.length],I=K||adoptTopic(I,t),(e=>{K?isGenericTitle(K)&&D(e):R||D(e)})(t),u=new AbortController,p=setInterval((()=>{c++,N(!0),c%3==0&&B()}),100),p.unref&&p.unref(),N(!0),j({role:"user",text:t});const n=j({role:"assistant",text:"",streaming:!0});let o=!1;const i={text:e=>{n.text+=e,z+=w(e),q()},reasoning:e=>{o=!0,z+=w(e)},thinkingTokens:e=>{o=!0,V+=e,q()},tool:e=>{if(e&&void 0!==e.id){const t=g.findIndex((t=>t&&void 0!==t.id&&t.id===e.id));t>=0?g[t]=e:g.push(e)}else g.push(e);if("run"===e.phase){const t=++h,r=e.agent?`${e.agent} ▸ `:"",o=editPreview(e.name,e.args,{cwd:e.cwd});F({role:"tool",phase:"run",name:e.name,args:e.args,agent:e.agent,id:e.id,label:`Running ${t} ${r}${toolLabel(e.name,t)}…`,start:Date.now(),diff:o,diffOpen:defaultOpen(o)},n)}else if(!resolveToolDone(r,e)){const t=++h,r=editPreview(e.name,e.args,{cwd:e.cwd});F({role:"tool",phase:"done",name:e.name,args:e.args,agent:e.agent,id:e.id,ok:e.ok,label:`Ran ${t} ${e.agent?`${e.agent} ▸ `:""}${toolLabel(e.name,t)}`,diff:r,diffOpen:defaultOpen(r)},n)}q()},approval:e=>(e=>new Promise((t=>{X((async()=>{s={type:"confirm",name:e.tool||e.name||"tool",args:e.args||{},sel:0,info:e},B();const n=e=>{s=null,B(),t(e)};for(;;){const e=await nextKey();if(e===STREAM_END||!e)return void n("deny");if(e.name===KEY.UP||e.name===KEY.DOWN||e.name===KEY.TAB){const t=e.name===KEY.UP?-1:1;s.sel=(s.sel+t+APPROVAL_CHOICES.length)%APPROVAL_CHOICES.length,B()}else{if(e.name===KEY.ENTER)return void n(APPROVAL_DECISIONS[s.sel]||"deny");if(e.name===KEY.ESC||e.name===KEY.CTRL_C)return void n("deny");if("char"===e.name){const t=String(e.ch).trim(),r=Number(t)-1;if(Number.isInteger(r)&&r>=0&&r<APPROVAL_DECISIONS.length)return void n(APPROVAL_DECISIONS[r])}}}}))})))(e),rounds:t=>(t=>new Promise((n=>{const r=Boolean(e.isYolo&&e.isYolo()),o=autoContinuePlan({on:r,used:a});if(a=o.used,o.auto)return U(`auto: ${t.spent}-round limit reached — continuing automatically (${o.used}/${o.cap}, then it asks).`),B(),void n(!0);r&&(U(`auto: ${o.cap} automatic continuations used — asking you now (answering restarts the block).`),B()),X((async()=>{s={type:"rounds",spent:Number(t.spent)||0,extensions:Number(t.extensions)||1,max:Number(t.max)||8,size:Number(t.size)||Number(t.spent)||0,sel:1},B();const e=e=>{s=null,B(),n(e)};for(;;){const t=await nextKey();if(t===STREAM_END||!t)return void e(!1);if(t.name===KEY.UP||t.name===KEY.DOWN||t.name===KEY.TAB)s.sel=1-s.sel,B();else{if(t.name===KEY.ENTER)return void e(0===s.sel);if(t.name===KEY.ESC||t.name===KEY.CTRL_C)return void e(!1);if("char"===t.name){const n=String(t.ch).trim();if("1"===n)return void e(!0);if("2"===n)return void e(!1)}}}}))})))(t)};let S=null;try{S=await e.ask(t,{history:historyPairs(r),presenter:i,signal:u.signal})}catch(e){S={error:e&&e.message||String(e)}}finally{n.streaming=!1,!String(n.text||"").trim()&&S&&"string"==typeof S.text&&S.text.trim()&&(n.text=S.text),l=!1,clearInterval(p),p=null,N(!1);const r=Math.max(1,Math.round((Date.now()-d)/1e3)),s=!(!u||!u.signal.aborted);n.text=finalizeTurnText(n.text,{aborted:s,error:S&&S.error,reasoned:o}),j({role:"done",text:`${h>0?DONE_VERBS[1]:DONE_VERBS[0]} for ${r}s`},{follow:!1}),S&&S.pooled_notice&&j({role:"note",text:S.pooled_notice},{follow:!1}),y=m+1,m++,u=null;try{const e=loadConfig(),t=pingTurn({stream:process.stdout,mode:e.ping,minSeconds:e.pingMinSeconds,elapsedMs:Date.now()-d,isTTY:!!process.stdout.isTTY,aborted:s});t&&j({role:"note",text:t},{follow:!1})}catch{}e.recordTurn(S);let i=null;try{const t=await e.refreshSpend();i=t?t.lastCost:null}catch{}e.persistTurn&&e.persistTurn(t,S,s?"stopped":S&&S.error?"error":"done",i);const a=S&&S.usage,c=e.tokensFor?e.tokensFor(a):null,f=a?usageBuckets(a):null;j({role:"meta",meta:{model:S&&S.model,tokens:c,input:f?f.input:null,output:f?f.output:null,eur:i,ms:S&&S.ms,calls:S&&S.calls||1}},{follow:!1});const w=summarizeTurnTools(g);w.tools>0&&j({role:"summary",counts:w},{follow:0===E}),B()}},Z=e=>{let r=null;if(e.name===KEY.PAGE_UP)r=5;else if(e.name===KEY.PAGE_DOWN)r=-5;else if("wheel"===e.name)r="up"===e.dir?3:-3;else{if("click"===e.name||"drag"===e.name||"release"===e.name)return!(e=>{const t={col:e.col-1,row:e.row-1};if("click"===e.name)return C=t,!1;if("drag"===e.name)return T?T.head=t:T={anchor:C||t,head:t},C=null,!0;const n=C;C=null;const r=T?selectionRange(T.anchor,T.head):null,o=!(!r||r.startRow===r.endRow&&r.startCol===r.endCol);if(T=null,!o)return(e=>{const t=v.get(e);return!(!t||!t.diff||(t.diffOpen=!t.diffOpen,0))})((n||t).row);const s=selectionText(L,r);if(!s)return!0;const i=copyToClipboard(s,{stdout:process.stdout,env:process.env}),a=s.split("\n").length;return P=describeCopy(i,`Marked ${a} line${1===a?"":"s"}`),k=Date.now()+2500,setTimeout((()=>{Date.now()>=k&&B()}),2600),!0})(e)||(q(),!0);"char"!==e.name||!t.vim||b||n.buf||("j"===e.ch?r=1:"k"===e.ch&&(r=-1))}return null!==r&&(E=Math.max(0,E+r),S=null,q(),!0)},ee=()=>{if(!s||"resume"!==s.type)return;const e=Array.isArray(s.all)?s.all:[];s.items=sessionSearch.rankSessions(s.query||"",e),s.sel=0,B()},te=()=>s?"palette"===s.type?fuzzy.fuzzyRankWithAliases(paletteQuery(s.query),e.visibleCommands(),(e=>e.name),(e=>e.aliases||[])).length:"model"===s.type||"resume"===s.type||"class"===s.type||"provider"===s.type?(s.items||[]).length:"effort"===s.type?overlays.EFFORT_VALUES.length:0:0,ne=async n=>{if(n){{const t=models.modelKeyPlan(n,{hasStored:!!e.hasProviderKey&&!!e.hasProviderKey("anthropic")}),{row:r,message:o}=overrideAnthropicByokWithPro(n,{needsKey:!(!t||!t.needed),proLoggedIn:models.claudeProLoggedIn(),proEnabled:(()=>{try{return!0===loadConfig().proEnabled}catch{return!1}})(),proModels:claudePro.PRO_MODELS});n=r,o&&U(o)}if(n.cls&&"aegis"!==n.cls&&t.modelClass!==n.cls){const e="string"==typeof t.modelClass;if(await ie(`/class ${n.cls}`),e&&t.modelClass!==n.cls)return void U(`${n.id} runs on the ${n.cls} class, and this session is on ${t.modelClass} — run /class ${n.cls}${"pro"===n.cls?" on":""}, then pick it again.`)}t.model=n.id,e.updateConfig({model:n.id,currentModelId:n.id,modelClass:t.modelClass}),U(`model: ${n.id}${"byok"===n.cls?" (byok)":"pro"===n.cls?" (Claude Code Pro)":""}`),await(async t=>{const n=models.modelKeyQueue(t,{accountConfigured:!!e.accountConfigured&&!!e.accountConfigured(),hasStoredFor:t=>!!e.hasProviderKey&&!!e.hasProviderKey(t)});if(!n.length)return;let r=null;try{r=e.makeCommandContext()}catch{r=null}if(r&&"function"==typeof r.readSecret)for(const e of n){const n="account"===e.role?"AEGIS account key":"claude-pro"===e.role?"Claude Code OAuth token (`claude setup-token` mints one)":`${e.provider} key`,o=String(await r.readSecret(`${n} → ${e.env} (kept off screen, Enter to skip): `)||"").trim();if(!o){U(`no key given — ${e.env} is still unset, so ${t.id} will fail until it is.`);continue}const s="account"===e.role?"AEGIS":"claude-pro"===e.role?"Claude Code OAuth":e.provider||"that provider",i=validateApiKey(o,{label:s});if(!i.ok){U(`not saved — ${i.message}. ${e.env} is still unset.`);continue}const a=models.storeModelKey(t,i.key,{env:e.env});a.ok?U(a.changed?a.foreign?`${e.env} saved to ${a.file} (0600) — read only by the Claude Code Pro transport, never exported.`:`${e.env} saved to ${a.file} (0600) — both hosts read that file; nothing to export.`:`${e.env} was already set in ${a.file}.`):U(`could not save the key: ${a.error||"unknown error"}`)}else{const e=n.map((e=>`${e.env}: ${e.why}`)).join(" · ");U(`${t.id} has no key: ${e}. Set the ones above and pick it again.`)}})(n)}},re=async e=>{e&&e.class&&await ie(`/class ${e.class}`)},oe=n=>{const r=overlays.EFFORT_VALUES[n||0];s=null,t.effort=r||"high",e.updateConfig({effort:t.effort}),U(`effort: ${t.effort}`),B()},se=async o=>{if(o)if(s)await(async t=>{const n=s.type;if(t.name===KEY.ESC||t.name===KEY.CTRL_C)return s=null,void B();if("shortcuts"===n||"panel"===n)return s=null,void B();if(t.name!==KEY.TAB||"palette"!==n)if(t.name!==KEY.TAB||"model"!==n&&"effort"!==n&&"class"!==n&&"provider"!==n){if(t.name===KEY.ENTER){if("palette"===n){const e=i()[s.sel||0],t=String(s.query||"").trim().split(/\s+/).slice(1).join(" ");return s=null,B(),void(e&&await ie(t?`/${e.name} ${t}`:`/${e.name}`))}if("model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ne(e),void B()}if("effort"===n)return void oe(s.sel||0);if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await re(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await ie(`/${t} ${e.id}`))}if("resume"===n){const t=(s.items||[])[s.sel||0];return s=null,B(),void(t&&e.resumeSession&&await e.resumeSession(t))}return s=null,void B()}if(t.name===KEY.SHIFT_UP||t.name===KEY.SHIFT_DOWN){const e=t.name===KEY.SHIFT_UP?-1:1,r=Math.max(0,te()-1);if(s.sel=Math.min(r,Math.max(0,(s.sel||0)+e)),"model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ne(e),void B()}if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await re(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await ie(`/${t} ${e.id}`))}return"effort"===n?void oe(s.sel||0):void B()}if(t.name===KEY.SHIFT_ENTER){if("palette"===n){const e=i()[s.sel||0];return s=null,B(),void(e&&await ie(`/${e.name}`))}if("model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ne(e),void B()}if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await re(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await ie(`/${t} ${e.id}`))}return"effort"===n?void oe(s.sel||0):void 0}if(t.name===KEY.UP||t.name===KEY.DOWN){const e=(s.items||[]).length||te(),n=t.name===KEY.UP?-1:1;return s.sel=Math.min(Math.max(0,e-1),Math.max(0,(s.sel||0)+n)),void B()}if("char"===t.name){if("palette"===n)return s.query=(s.query||"")+t.ch,s.sel=0,void B();if("resume"===n)return s.query=(s.query||"")+t.ch,void ee();if("model"===n){const e=parseInt(t.ch,10),n=s.items||[];return void(Number.isFinite(e)&&e>=1&&e<=n.length&&(s.sel=e-1,B()))}if("effort"===n||"class"===n||"provider"===n){const e=parseInt(t.ch,10),n=te();return void(Number.isFinite(e)&&e>=1&&e<=n&&(s.sel=e-1,B()))}}if(t.name===KEY.BACKSPACE&&"resume"===n)return s.query=String(s.query||"").slice(0,-1),void ee();t.name===KEY.BACKSPACE&&"palette"===n&&(s.query=String(s.query||"").slice(0,-1),B())}else{const e="model"===n||"class"===n||"provider"===n?(s.items||[]).length:overlays.EFFORT_VALUES.length;e&&(s.sel=((s.sel||0)+1)%e,B())}else{const e=i()[s.sel||0];e&&(s.query=e.name,s.sel=0,B())}})(o);else{if("char"===o.name&&!n.buf){if("/"===o.ch)return s={type:"palette",query:"",sel:0},void B();if("?"===o.ch)return s={type:"shortcuts"},void B()}if(!t.vim||b||n.buf||"char"!==o.name){if(t.vim&&b&&o.name===KEY.ESC)return b=!1,n.cursor>0&&n.cursor--,void B()}else{const e=o.ch;if("i"===e||"a"===e||"o"===e||"s"===e||"S"===e)return"s"===e&&n.substChar(),"S"===e&&n.substLine(),"a"===e&&n.right(),b=!0,void B();if("h"===e)return n.left(),void B();if("l"===e)return n.right(),void B();if("0"===e)return n.home(),void B();if("$"===e)return n.end(),void B();if("x"===e)return n.delete(),void B();if("D"===e)return n.killToEnd(),void B();if("A"===e)return n.end(),b=!0,void B();if(Z(o))return}if(o.name===KEY.ENTER){const e=n.submit();return Y=null,b=!1,e?void await ie(e):void B()}if(o.name!==KEY.CTRL_V)if(o.name!==KEY.CTRL_B){if("paste"===o.name)return t.vim&&(b=!0),n.insert(String(o.text)),void B();if("char"===o.name)return t.vim&&!b||n.insert(o.ch),void B();if(o.name===KEY.BACKSPACE)return n.backspace(),void B();if(o.name===KEY.DELETE)return n.delete(),void B();if(o.name===KEY.LEFT||o.name===KEY.CTRL_LEFT)return o.name===KEY.CTRL_LEFT?n.wordBack():n.left(),void B();if(o.name!==KEY.RIGHT||n.buf){if(o.name===KEY.RIGHT||o.name===KEY.CTRL_RIGHT)return n.right(),void B();if(o.name===KEY.HOME||o.name===KEY.CTRL_A)return n.home(),void B();if(o.name===KEY.END||o.name===KEY.CTRL_E)return n.end(),void B();if(o.name===KEY.UP)return n.historyUp(),void B();if(o.name===KEY.DOWN)return n.historyDown(),void B();if(o.name===KEY.TAB)return(()=>{const t=n.buf;if(!t.startsWith("/")||t.includes(" "))return!1;const r=t.slice(1),o=e.visibleCommands().flatMap((e=>[e.name,...e.aliases||[]])).filter((e=>e.startsWith(r))).sort();return!!o.length&&(Y&&Y.q===r||(Y={q:r,i:-1}),Y.i=(Y.i+1)%o.length,n.buf="/"+o[Y.i],n.end(),!0)})()||(P=n.buf?"Tab completes commands":"Use alt+t to toggle thinking",k=Date.now()+2500,setTimeout((()=>{Date.now()>=k&&B()}),2600)),void B();if(o.name===KEY.CTRL_U)return n.buf="",n.cursor=0,void B();if(o.name===KEY.CTRL_K)return n.killToEnd(),void B();if(o.name===KEY.CTRL_W)return n.wordBack(),void B();if(o.name===KEY.CTRL_L)return clearScreen(),void B();if(o.name===KEY.CTRL_T)return U(e.tokenSummary?e.tokenSummary():"no token usage yet this session"),void B();if(o.name!==KEY.CTRL_R)if(o.name!==KEY.CTRL_O)if("click"!==o.name&&"drag"!==o.name&&"release"!==o.name)if(o.name!==KEY.PAGE_UP&&o.name!==KEY.PAGE_DOWN&&"wheel"!==o.name)if("alt"!==o.name||"p"!==o.ch){if("alt"===o.name&&"t"===o.ch){const n=!(!0===t.thinking);return t.thinking=n,e.updateConfig({thinking:n}),U("Thinking blocks: "+(n?"expanded":"collapsed")),void B()}if(o.name!==KEY.ESC)return o.name===KEY.CTRL_C?n.buf?(n.buf="",n.cursor=0,void B()):void await ue():void(o.name!==KEY.CTRL_D||n.buf||await ue());n.buf&&(n.buf="",n.cursor=0,B())}else await ie("/model");else Z(o);else Z(o);else await ie("/permissions");else await ie("/resume")}else await ie(e.isYolo&&e.isYolo()?"/automode off":"/automode on")}else(()=>{if(!r.length)return void G("Nothing to copy yet");const e=copyToClipboard(transcriptToMarkdown(r),{stdout:process.stdout,env:process.env});G(describeCopy(e,"Copied the conversation"))})();else(()=>{const e=readClipboardImage({env:process.env});if(e.ok)try{const t=path.join(aegisDir(),"clipboard");fs.mkdirSync(t,{recursive:!0});const r="image/jpeg"===e.mime?"jpg":"png",o=path.join(t,`pasted-${(new Date).toISOString().replace(/[:.]/g,"-")}.${r}`);fs.writeFileSync(o,e.data,{mode:384});const s=n.buf&&!/\s$/.test(n.buf)?" ":"";return n.insert(s+o),void G(`Pasted image → ${o}`)}catch(e){return void G(`Could not save the pasted image: ${e&&e.message||e}`)}const t=readClipboardText({env:process.env});if(t.ok&&t.text)return n.insert(t.text),void G(`Pasted ${t.text.length} character${1===t.text.length?"":"s"} from the clipboard`);G(t.ok?"Clipboard is empty — nothing to paste":`Cannot read the clipboard here (${t.error}) — use your terminal's own paste shortcut instead`)})()}},ie=async t=>{const r=String(t||"").trim();if("?"===r)return s={type:"shortcuts"},void B();(!1===await(async(e,t)=>{try{return await((e,t)=>{const n=[];let r,o,i=!1;return e.then((e=>{i=!0,r=e}),(e=>{i=!0,o=e})),(async()=>{for(;!i;){if(await Promise.resolve(),!l||s&&"confirm"===s.type){await new Promise((e=>setTimeout(e,60)));continue}const e=await nextKeyTimeout(120);if(null!==e)if(e.name===KEY.ESC||e.name===KEY.CTRL_C){const e=t&&t();e&&e.abort()}else Z(e)||n.push(e)}if(requeueKeys(n),o)throw o;return r})()})(e(),(()=>u))}catch(e){return j({role:"note",text:`Error: ${e&&e.message||String(e)}`},{follow:!1}),void B()}})((async()=>{if(r.startsWith("/")){const t=(()=>{const t=e.makeCommandContext();return Object.assign(t,{push:(e,t)=>{j(e,t),B()},note:e=>{j({role:"note",text:e}),B()},panel:e=>{j({role:"panel",lines:e||[]}),B()},render:()=>B(),openOverlay:e=>{if(e&&"resume"===e.type){const t=Array.isArray(e.items)?e.items:[];return s={...e,all:t,query:"string"==typeof e.query?e.query:"",items:sessionSearch.rankSessions("string"==typeof e.query?e.query:"",t),sel:0},void B()}s=e,B()},closeOverlay:()=>{s=null,showCursor(),B()},askInput:e=>(e=>new Promise((t=>{$={title:e,buf:""},B(),(async()=>{for(;;){const e=await nextKey();if(!$)return void t(null);if(e.name===KEY.ESC||e.name===KEY.CTRL_C||e.name===KEY.CTRL_D)return $=null,B(),void t(null);if(e.name===KEY.ENTER){const e=$.buf;return $=null,B(),void t(e)}e.name===KEY.BACKSPACE?$.buf=[...$.buf].slice(0,-1).join(""):"char"===e.name?$.buf+=e.ch:"paste"===e.name&&($.buf+=String(e.text).replace(/\n/g," ")),B()}})()})))(e),withWorking:e=>(async e=>{const t=u;l=!0,c=0,d=Date.now(),f=VERBS[m%VERBS.length],u=new AbortController,p=setInterval((()=>{c++,N(!0),c%3==0&&B()}),100),p.unref&&p.unref(),N(!0);try{return await e(u.signal)}finally{l=!1,clearInterval(p),p=null,u=t,N(!1),B()}})(e),runPrompt:async e=>{await J(e)},state:()=>e.buildState(),setInput:e=>{n.buf=String(null==e?"":e),n.end(),B()},exit:()=>e.requestExit(),openStream:e=>{x=e||null,O=Date.now(),B()},closeStream:e=>{e&&x!==e||(x=null),B()},showThemePicker:()=>{e.showThemePicker&&e.showThemePicker(),B()}}),t})();return e.dispatchLine(r,t)}return await J(r),!0}))||e.wantsExit())&&await ue()};let ae=!1,le=null;const ue=()=>{ae||(ae=!0,le&&le(0))},ce=()=>{hideCursor(),paint([]);try{process.stdout.write("[0m")}catch{}try{A&&writeTitle("",process.stdout)}catch{}try{process.stdin.setRawMode(!1)}catch{}disableBracketedPaste(),disableMouseTracking(),leaveAltScreen()};let pe=!1;const de=()=>{if(!pe){pe=!0;try{ce()}catch{}}};process.once("exit",de);const fe=e.stdin||process.stdin;markSessionStart(),attachKeyStream(fe),enableBracketedPaste(),enableMouseTracking(),enterAltScreen(),clearScreen(),hideCursor(),N(!1);const me=()=>B();"win32"!==process.platform?process.on("SIGWINCH",me):process.stdout.on("resize",me);const he=()=>{l&&u?u.abort():ue()};process.on("SIGINT",he);const ge=e=>{ce();try{process.stderr.write(`\nAEGIS Code hit an unexpected error. Your transcript is saved; rerun to continue.\n${e&&e.stack||e}\n`)}catch{}process.exit(1)};process.on("uncaughtException",ge),process.on("unhandledRejection",ge),B();try{return await new Promise((e=>{le=e,(async()=>{for(;!ae;){const e=await nextKey();if(ae)break;if(e===STREAM_END||!e){ue();break}try{await se(e)}catch(e){j({role:"note",text:`Error: ${e&&e.message||String(e)}`},{follow:!1}),B()}}})()}))}finally{ae=!0,process.off("SIGINT",he),"win32"!==process.platform?process.off("SIGWINCH",me):process.stdout.off("resize",me),process.off("uncaughtException",ge),process.off("unhandledRejection",ge),process.off("exit",de),de(),resetKeyStream()}}module.exports={SUGGESTIONS:SUGGESTIONS,TITLE_SPIN:TITLE_SPIN,FRAME_MS:33,toolLabel:toolLabel,resolveToolDone:resolveToolDone,summarizeTurnTools:summarizeTurnTools,finalizeTurnText:finalizeTurnText,historyPairs:historyPairs,overrideAnthropicByokWithPro:overrideAnthropicByokWithPro,paletteQuery:paletteQuery,headerLine:headerLine,separatorLine:separatorLine,effortLine:effortLine,spinnerLine:spinnerLine,statusLine:statusLine,shortcutsGrid:shortcutsGrid,confirmLines:confirmLines,APPROVAL_CHOICES:APPROVAL_CHOICES,APPROVAL_DECISIONS:APPROVAL_DECISIONS,roundsLines:roundsLines,autoContinuePlan:autoContinuePlan,autoContinueLimit:autoContinueLimit,AUTO_CONTINUE_LIMIT:AUTO_CONTINUE_LIMIT,rowLines:rowLines,transcriptLines:transcriptLines,inputPreviewText:inputPreviewText,inputRowCells:inputRowCells,inputScroll:inputScroll,inputStart:inputStart,inputLine:inputLine,runSession:runSession};
|
|
3
|
+
"use strict";const{getSize:getSize,span:span,padLine:padLine,paint:paint,w:w,wrapBlock:wrapBlock,hideCursor:hideCursor,showCursor:showCursor,moveTo:moveTo,clearScreen:clearScreen,enterAltScreen:enterAltScreen,leaveAltScreen:leaveAltScreen,enableBracketedPaste:enableBracketedPaste,disableBracketedPaste:disableBracketedPaste,enableMouseTracking:enableMouseTracking,disableMouseTracking:disableMouseTracking,selectionRange:selectionRange,selectionText:selectionText,applySelection:applySelection}=require("./screen.js"),{KEY:KEY,STREAM_END:STREAM_END,attachKeyStream:attachKeyStream,nextKey:nextKey,nextKeyTimeout:nextKeyTimeout,requeueKeys:requeueKeys,resetKeyStream:resetKeyStream,markSessionStart:markSessionStart,isKeyStreamSuspended:isKeyStreamSuspended}=require("./events.js"),{GLYPH:GLYPH,VERBS:VERBS,DONE_VERBS:DONE_VERBS,BOLD:BOLD,BOLD_OFF:BOLD_OFF,themeOf:themeOf,RGB:RGB}=require("./theme.js"),{LineEditor:LineEditor}=require("./input.js"),{renderMarkdown:renderMarkdown}=require("./markdown.js"),overlays=require("./overlays.js"),models=require("./models.js"),{resolveShared:resolveShared}=require("./sharedpaths.js"),{validateApiKey:validateApiKey}=require(resolveShared(require("node:path").join("client","credentials.js"))),sessionSearch=require(resolveShared(require("node:path").join("client","session-search.js"))),claudePro=require(resolveShared(require("node:path").join("desktop","lib","local","claude-pro.js"))),fuzzy=require("./fuzzy.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,fmtElapsed:fmtElapsed,fmtUsageSplit:fmtUsageSplit,displayTokens:displayTokens,pathName:pathName,feeBillable:feeBillable}=require("./format.js"),{editPreview:editPreview}=require("./diff.js"),{renderDiffBlock:renderDiffBlock,defaultOpen:defaultOpen}=require("./diffview.js"),{copyToClipboard:copyToClipboard,describeCopy:describeCopy,readClipboardText:readClipboardText,readClipboardImage:readClipboardImage}=require("./clipboard.js"),{transcriptToMarkdown:transcriptToMarkdown}=require("./export.js"),fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir,loadConfig:loadConfig}=require("./config.js"),{effortRung:effortRung}=require("./engine.js"),{usageBuckets:usageBuckets,estimateTokensFromCells:estimateTokensFromCells}=require("./tokens.js"),{pingTurn:pingTurn}=require("./ping.js"),SUGGESTIONS=["edit <filepath> to...","refactor <filepath>","how do I log an error?","write a test for <filepath>","create a util logging.py that..."],{TITLE_SPIN:TITLE_SPIN,titleText:titleText,topicFrom:topicFrom,adoptTopic:adoptTopic,titleEnabled:titleEnabled,writeTitle:writeTitle}=require("./title.js"),{GENERIC_TITLE:GENERIC_TITLE,isGenericTitle:isGenericTitle}=require("./naming.js"),FRAME_MS=33;function isShellTool(e){return"exec"===e||"Bash"===e}function isAgentTool(e){return"task"===e||"Task"===e}function toolLabel(e,t){const n=isShellTool(e)?"shell command":isAgentTool(e)?"subagent":`${String(e).toLowerCase()} command`;return t>1?n+"s":n}function resolveToolDone(e,t){let n=-1;if(void 0!==t.id)for(let r=e.length-1;r>=0;r--){const o=e[r];if("tool"===o.role&&"run"===o.phase&&o.id===t.id){n=r;break}}if(-1===n)for(let r=e.length-1;r>=0;r--){const o=e[r];if("tool"===o.role&&"run"===o.phase&&o.name===t.name&&o.agent===t.agent){n=r;break}}if(-1===n)return null;const r=e[n],o=e.filter((e,r)=>"tool"===e.role&&e.name===t.name&&e.agent===t.agent&&r<=n).length;return r.phase="done",r.elapsed=t.elapsed,r.ok=t.ok,r.label=`Ran ${o} ${r.agent?`${r.agent} ▸ `:""}${toolLabel(t.name,o)}`,r}const MUTATING_FILES=new Set(["Edit","Write","MultiEdit","NotebookEdit","editFile","writeFile"]);function summarizeTurnTools(e,{maxNames:t=3}={}){const n=[],r=[];let o=0;for(const t of e||[]){if(!t)continue;!1===t.ok&&(o+=1);const e=t.args;if(!e||"object"!=typeof e)continue;const s=MUTATING_FILES.has(t.name)?e.file_path||e.path||e.notebook_path:null;"string"==typeof s&&s&&!n.includes(s)&&n.push(s);const i=e.command;if("string"==typeof i&&i.trim()){const e=pathName(i.trim().split(/\s+/)[0]);e&&!r.includes(e)&&r.push(e)}}return{tools:(e||[]).length,failed:o,files:n,names:n.slice(0,t).map(e=>pathName(e)),more:Math.max(0,n.length-t),commands:r}}function finalizeTurnText(e,{aborted:t,error:n,reasoned:r}={}){let o=String(null==e?"":e);if(n&&!t&&"stopped"!==n){const e=`(backend error: ${n})`;o=o.trim()?`${o.trimEnd()}\n\n${e}`:e}return t&&(o=o.trim()?`${o.trimEnd()} (stopped)`:"(stopped)"),o.trim()||(o=r?"(no answer — the model used its whole budget on hidden reasoning before writing one; retry, or raise the budget with /effort)":"(no response)"),o}function historyPairs(e){return e.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.text}))}const PRO_ALIAS_KEYWORDS=Object.freeze(["opus","haiku","sonnet","fable"]);function overrideAnthropicByokWithPro(e,t={}){if(!e||"byok"!==e.cls)return{row:e,message:null};const n=String(e.id||""),r=n.indexOf(":");if(r<0||"anthropic"!==n.slice(0,r).trim().toLowerCase())return{row:e,message:null};if(!t.needsKey)return{row:e,message:null};if(!t.proLoggedIn)return{row:e,message:null};if(!0!==t.proEnabled)return{row:e,message:null};const o=n.slice(r+1).toLowerCase(),s=Array.isArray(t.proModels)&&t.proModels.length?t.proModels:[{id:"default",label:"Default",note:""}],i=PRO_ALIAS_KEYWORDS.find(e=>o.includes(e))||"default",a=s.find(e=>e.id===i)||s[0];return{row:{id:a.id,label:a.label,note:a.note,cls:"pro"},message:`${n} has no Anthropic console key on this machine, but Claude Code Pro is signed in — using the subscription instead (claude --model ${a.id}). Add a real console key any time with /byok-key anthropic <key> to run this row directly.`}}function paletteQuery(e){const t=String(e||"").trim();return t.includes(" ")?t.split(/\s+/)[0]:t}function headerLine(e,t,n){const r=themeOf(n),o=` AEGIS Code v${e} `,s=Math.max(0,t-[...o].length-2),i=Math.floor(s/2);return[span(r.coral,`╭${"─".repeat(i)}${o}${"─".repeat(s-i)}╮`)]}const separatorLine=(e,t)=>[span(themeOf(t).dim,"─".repeat(e))];function effortLine(e,t){const n=themeOf(e),r=`● ${effortRung(e.effort)} · /effort`,o=" ".repeat(Math.max(0,t-[...r].length-4));return[span(n.gray,o+r)]}const SPINNER_TINT=RGB(235,159,127);function spinnerLine(e,t){const n=themeOf(t),r=Math.max(1,Math.round((e.elapsedMs||0)/1e3)),o=[...e.verb||VERBS[0]],s=Math.floor((e.frame||0)/2)%3,i=o.map((e,t)=>span((t+s)%3==0?n.coral:SPINNER_TINT,e)),a=t&&t.thinking?span(n.gray,` (${r}s · thinking)`):span(n.gray,` (${r}s · ↓${e.streamedFloor?"≥":""}${fmtTokens(e.streamed||0)} tokens)`),l=GLYPH.spin[(e.frame||0)%GLYPH.spin.length];return[span(n.coral,l),...i,span(n.white,"… "),a]}function statusLine(e,t,n){const r=themeOf(n);let o;return o=e.inputPrompt?[span(r.gray,"enter to confirm · esc to cancel")]:e.working?[span(r.gray,` ${GLYPH.bullet} esc to interrupt`)]:e.streamJob?[span(r.gray,`${GLYPH.bullet} esc to stop`)]:e.keyNotice?[span(r.gray,` ${GLYPH.bullet} no AEGIS key: ${e.keyNotice} ${GLYPH.bullet} /key register to retry`)]:e.yolo?[span(r.gray,`${GLYPH.bullet} automode on ${GLYPH.bullet} ${autoContinueLimit()} rounds then it asks ${GLYPH.bullet} ? for shortcuts ${GLYPH.bullet} ${GLYPH.rightarrow} for manual mode`)]:[span(r.gray,`${GLYPH.pause} manual mode on ${GLYPH.bullet} ? for shortcuts ${GLYPH.bullet} ${GLYPH.rightarrow} for auto mode`)],padLine(o,t)}function shortcutsGrid(e,t){const n=themeOf(t),r=(e,t,r,o)=>[span(""," "),span(n.white,e),span(n.gray," "+t),span(""," "),span(n.white,r),span(n.gray," "+o)];return[r("/","for commands","?","for shortcuts"),r("ctrl + c","to quit","ctrl + o","for permissions"),r("alt + p","to switch model","alt + t","to toggle thinking"),r("shift + ↑/↓","pins as it moves","shift + enter","runs the row"),r("esc","to interrupt a turn","ctrl + l","to clear the screen"),r("ctrl + t","to show tokens","ctrl + r","to resume a session"),r("↑ / ↓","for history","tab","to complete a command")]}const APPROVE_ONCE="once",APPROVE_SESSION="session",DENY_TOKEN="deny",APPROVAL_CHOICES=["Yes","Yes, allow for this session","No"],APPROVAL_DECISIONS=["once","session","deny"];function confirmLines(e,t,n){const r=themeOf(n),o=[];o.push([span(r.gray,"─".repeat(Math.min(Math.max(10,t-4),80)))]),o.push([span(r.white,`${isShellTool(e.name)?"shell":e.name} command`)]),o.push([span("","")]);const s=isShellTool(e.name)?String(e.args&&e.args.command||""):String(e.args&&(e.args.file_path||e.args.pattern)||"");for(const e of wrapBlock(s,Math.max(8,t-4)))o.push([span(r.gray,e)]);o.push([span("","")]),o.push([span(r.white,"Do you want to proceed?")]);const i=e.name||"this tool";return APPROVAL_CHOICES.forEach((t,n)=>{const s=1===n?`Yes, and allow ${i} for this session`:t;o.push(((t,n)=>{const o=e.sel===t;return[o?span(r.lavender,GLYPH.cursor):span(""," "),span(r.gray,` ${t+1}. `),span(o?r.lavender:r.white,n)]})(n,s))}),o.push([span("","")]),o.push([span(r.gray,"Esc to cancel")]),o}const AUTO_CONTINUE_LIMIT=3;function autoContinueLimit(e=process.env){const t=Number.parseInt(e&&e.AEGIS_AUTO_CONTINUE_MAX,10);return Number.isFinite(t)&&t>0?t:AUTO_CONTINUE_LIMIT}function autoContinuePlan({on:e=!1,used:t=0,limit:n=autoContinueLimit()}={}){const r=Number.isFinite(n)&&n>0?Math.floor(n):AUTO_CONTINUE_LIMIT,o=Number.isFinite(t)&&t>0?Math.floor(t):0;return e?o>=r?{auto:!1,used:0,cap:r}:{auto:!0,used:o+1,cap:r}:{auto:!1,used:o,cap:r}}function roundsLines(e,t,n){const r=themeOf(n),o=[];o.push([span(r.gray,"─".repeat(Math.min(Math.max(10,t-4),80)))]),o.push([span(r.white,`${e.spent}-round tool limit reached`)]),o.push([span("","")]);for(const e of wrapBlock("The turn is still working — it ended its last round on a tool call instead of an answer.",Math.max(8,t-4)))o.push([span(r.gray,e)]);o.push([span("","")]);const s=(t,n)=>{const o=e.sel===t;return[o?span(r.lavender,GLYPH.cursor):span(""," "),span(r.gray,` ${t+1}. `),span(o?r.lavender:r.white,n)]};return o.push(s(0,`Yes, continue with ${e.size} more rounds`)),o.push(s(1,"No, stop here and answer with what I have")),o.push([span("","")]),o.push([span(r.gray,`extension ${e.extensions} of ${e.max} · Esc to stop`)]),o}function metaBits(e,t,{omitMs:n=!1}={}){const r=[];e.model&&r.push(span(t.blue,e.model));const o=fmtUsageSplit(e);if(o)r.push(span(t.white,o.output));else{const n=displayTokens(e);null!=n&&r.push(span(t.white,`${fmtTokens(n)} tokens`))}return null!=e.eur&&feeBillable()&&r.push(span(e.eur>0?t.coral:t.green,fmtEur(e.eur))),null==e.ms||n||r.push(span(t.gray,fmtElapsed(e.ms))),e.calls>1&&r.push(span(t.gray,`${e.calls} calls`)),r}function joinBits(e,t){const n=[];return e.forEach((e,r)=>{r&&n.push(span(t.dim,` ${GLYPH.bullet} `)),n.push(e)}),n}const DIR_MAX=40;function shortDir(e){let t=String(null==e?"":e).trim().replace(/\/+$/,"");if(!t)return"";const n=String(process.env.HOME||process.env.USERPROFILE||"").replace(/\/+$/,"");return n&&(t===n||t.startsWith(`${n}/`))&&(t=`~${t.slice(n.length)}`),t.length>40&&(t=`${GLYPH.ellipse}${t.slice(-39)}`),t}function rowLines(e,t,n,r=Date.now()){const o=themeOf(n),s=[];if("tool"===e.role){const i=String(e.label||"").replace(/(?:…|\.\.\.)+$/,""),a=e.cwd?` · ${shortDir(e.cwd)}`:"";if("run"===e.phase){const t=e.start?Math.max(1,Math.round((r-e.start)/1e3)):0;s.push([span(o.gray,`${i}${GLYPH.ellipse} · ${t}s${a}`)])}else s.push([span(o.gray,`${i}${a}`)]);if(e.diff){for(const r of renderDiffBlock(e.diff,n,t,{open:!!e.diffOpen}))s.push([span("",r)]);return s}const l="string"==typeof e.args?e.args:e.args&&"object"==typeof e.args?e.args.command??e.args.file_path??e.args.description??Object.values(e.args).find(e=>"string"==typeof e)??"":"";return l&&s.push([span(o.gray,` ${GLYPH.hook} $ ${String(l)}`)]),s}if("note"===e.role)return s.push([span(o.gray,`· ${e.text}`)]),s;if("tip"===e.role){for(const n of wrapBlock(String(e.text),t))s.push([span(o.gray,n)]);return s}if("done"===e.role){const t=[span(o.gray,GLYPH.bloom),span(o.gray,` ${e.text}`)];if(e.meta){const n=metaBits(e.meta,o,{omitMs:!0});n.length&&t.push(span(o.dim," "),...joinBits(n,o))}return s.push(t),s}if("summary"===e.role){const t=e.counts||{};if(!t.tools)return s;const n=[span(o.dim,GLYPH.hook),span(""," ")],r=[span(o.white,String(t.tools)),span(o.gray," "+(1===t.tools?"command":"commands"))];if(t.files&&t.files.length&&(r.push(span(o.gray,` ${GLYPH.bullet} `)),r.push(span(o.white,String(t.files.length)),span(o.gray," "+(1===t.files.length?"file changed":"files changed")))),t.failed&&(r.push(span(o.gray,` ${GLYPH.bullet} `)),r.push(span(o.coral,`${t.failed} failed`))),t.names&&t.names.length){const e=t.more?` +${t.more}`:"";r.push(span(o.dim,` ${t.names.join(", ")}${e}`))}return n.push(...r),s.push(n),s}if("meta"===e.role){const t=metaBits(e.meta||{},o);return t.length&&s.push([span(o.dim,`${GLYPH.hook} `),...joinBits(t,o)]),s}if("panel"===e.role){for(const n of e.lines||[])s.push(padLine(n,t));return s.push([span("","")]),s}if("error"===e.role)return s.push([span(o.red,`✗ ${e.text}`)]),s;if("user"===e.role)return wrapBlock(String(e.text),Math.max(8,t-2)).forEach((e,t)=>{0===t?s.push([span(o.gray,GLYPH.cursor),span(""," "),span(o.white,e)]):s.push([span(""," "),span(o.white,e)])}),s;const i="assistant"===e.role?renderMarkdown(String(null==e.text?"":e.text),t,n):wrapBlock(String(null==e.text?"":e.text),t).map(e=>[span(o.white,e)]),a=i.length?i:[[span("","")]];for(let e=0;e<a.length;e++){const t=a[e].slice();0===e&&t.unshift(span(o.white,GLYPH.block),span(""," ")),s.push(t)}return s}function transcriptLines(e,t,n,r=Date.now(),o=null){const{cols:s,rows:i}=t,a=Math.max(1,i-6),l=[],u=[];for(const t of e){const e=o||null,i="assistant"===t.role&&t.streaming||"tool"===t.role&&"run"===t.phase;if(e&&!i){const o=e.get(t);if(o&&o.text===t.text&&o.cols===s&&o.diffOpen===t.diffOpen){for(const e of o.segment)l.push(e),u.push(t);continue}const i=rowLines(t,s,n,r);e.set(t,{text:t.text,cols:s,diffOpen:t.diffOpen,segment:i});for(const e of i)l.push(e),u.push(t);continue}for(const e of rowLines(t,s,n,r))l.push(e),u.push(t)}let c=t.scroll||0,p=null==t.anchorEnd?null:t.anchorEnd;const d=l.length,f=Math.max(0,d-a);let m;c>f&&(c=f),0===c?(p=null,m=d):(null===p&&(p=Math.max(0,d-c)),m=Math.min(p,d)),d<=a&&(c=0,p=null,m=d);const h=Math.max(0,m-a);return{lines:l.slice(h,m),owners:u.slice(h,m),scroll:c,anchorEnd:p}}function inputPreviewText(e){const t=e.indexOf("\n");if(-1===t)return e;const n=e.split("\n").length-1;return`${e.slice(0,t)} … (+${n} line${1===n?"":"s"})`}const inputRowCells=e=>Math.max(1,e-3),bufCells=e=>[...e].reduce((e,t)=>e+w(t),0);function cursorCells(e,t){const n=[...e];let r=0;for(let e=0;e<Math.min(t,n.length);e++)r+=w(n[e]);return r}function inputScroll(e,t,n){const r=inputRowCells(n),o=bufCells(e);if(o<=r)return 0;const s=r-1;return Math.max(0,Math.min(cursorCells(e,t)-s,o-s))}function inputStart(e,t){const n=[...e];let r=0;for(let e=0;e<n.length;e++){if(r>=t)return e;r+=w(n[e])}return n.length}function inputLine(e,t,n){const r=themeOf(n),o=[span(r.gray,GLYPH.cursor),span(""," ")];if(e.inputPrompt){o.push(span(r.white,`${e.inputPrompt.title}: `));for(const t of[...e.inputPrompt.buf])o.push(span(r.white,t));const n=Math.min(3+w(e.inputPrompt.title)+2+w(e.inputPrompt.buf),t);return{line:padLine(o,t),cursorCol:n}}if(e.working)return{line:padLine(o,t),cursorCol:3};const s=e.buf||"";if(!s.length){if(e.insertMode)return{line:padLine(o,t),cursorCol:3};const n=SUGGESTIONS[(e.suggestionIdx||0)%SUGGESTIONS.length];return o.push(span(r.white+BOLD,`Try "${n}"`),span(BOLD_OFF,"")),{line:padLine(o,t),cursorCol:3}}if(s.includes("\n")){const e=inputPreviewText(s);for(const t of[...e])o.push(span(r.white,t));return{line:padLine(o,t),cursorCol:Math.min(3+w(e),t)}}const i=inputScroll(s,e.cursor,t),a=inputStart(s,i);i>0&&o.push(span(r.dim,"…"));const l=[...s];for(let e=a;e<l.length;e++)o.push(span(r.white,l[e]));const u=l.slice(a,Math.min(e.cursor,l.length)).join(""),c=Math.min(3+(i>0?1:0)+w(u),t);return{line:padLine(o,t),cursorCol:c}}async function runSession(e){const t=e.ctx,n=new LineEditor,r=e.transcript,o=new WeakMap;let s=null;function i(t){const n=paletteQuery(null==t?s&&s.query||"":t);return fuzzy.fuzzyRankWithAliases(n,e.visibleCommands(),e=>e.name,e=>e.aliases||[])}let a=0,l=!1,u=null,c=0,p=null,d=0,f=VERBS[0],m=0,h=0,g=[],y=0,E=0,S=null;const v=new Map;let T=null,C=null,L=[],b=!1,k=0,P="",$=null,x=null,O=0,Y=null,I="",K="",R=!1,A=!0;try{A=titleEnabled(process.env,e.loadConfig?e.loadConfig():e.config||{})}catch{A=!0}let M=!1,_=0;const N=e=>{if(!A)return;const t=e?TITLE_SPIN[Math.floor(c/2)%TITLE_SPIN.length]:null;writeTitle(titleText({topic:I,frame:t}),process.stdout)},D=t=>{if("function"!=typeof e.nameConversation)return;let n;R=!0;try{n=Promise.resolve(e.nameConversation(t,{signal:u?u.signal:null}))}catch{return}n.then(e=>{const t=String(e||"").trim();t&&(K=t,I=t,N(!!l),B())}).catch(()=>{})},G=e=>{P=e,k=Date.now()+2500,setTimeout(()=>{Date.now()>=k&&B()},2600),B()},B=()=>{if(isKeyStreamSuspended())return;const i=getSize().cols,{lines:a,inputCol:u,rows:p,inputRow:m}=(()=>{const{cols:s,rows:i}=getSize(),a=[];a.push(headerLine(e.version,s,t));const u=Math.max(1,i-6),p=transcriptLines(r,{cols:s,rows:i,scroll:E,anchorEnd:S},t,Date.now(),o);E=p.scroll,S=p.anchorEnd,v.clear();for(let e=0;e<p.lines.length;e++)v.set(1+e,p.owners[e]);for(const e of p.lines)a.push(e);for(;a.length<u+1;)a.push([span("","")]);const m=themeOf(t);if(l)a.push(spinnerLine({verb:f,frame:c,elapsedMs:Date.now()-d,streamed:estimateTokensFromCells(W())+V,streamedFloor:V>0},t));else if(Date.now()<k)a.push([span(m.gray,` ${P}`)]);else if(x){const e=Math.max(1,Math.round((Date.now()-O)/1e3));a.push([span(m.gray,` ${x.label||"running"}… (${e}s · esc to stop)`)])}else a.push(effortLine(t,s));a.push(separatorLine(s,t));const h=inputLine({buf:n.buf,cursor:n.cursor,working:l,insertMode:b,suggestionIdx:y,inputPrompt:$},s,t);return a.push(h.line),a.push(separatorLine(s,t)),a.push(statusLine({working:l,inputPrompt:$,streamJob:x,yolo:e.isYolo&&e.isYolo(),keyNotice:e.keyNotice&&e.keyNotice()},s,t)),{lines:a,inputCol:h.cursorCol,rows:i,inputRow:i-2}})();s&&H(a,p,i),L=a,paint(T?applySelection(a,selectionRange(T.anchor,T.head),i):a),_=Date.now(),s?hideCursor():$||!l?(moveTo(m,u),showCursor()):hideCursor()},q=()=>{if(M)return;M=!0;const e=Math.max(0,33-(Date.now()-_));setTimeout(()=>{M=!1,B()},e)},H=(n,r,o)=>{if(!s)return;let i=null;if("palette"===s.type?i=overlays.renderPalette(e.visibleCommands(),{query:paletteQuery(s.query),sel:s.sel},o,r):"model"===s.type?i=overlays.renderModelPicker(s.items||[],s.sel||0,o,r,s.current,s.cls||t.modelClass,"function"==typeof e.classLabel?e.classLabel:null):"effort"===s.type?i=overlays.renderEffortPicker(s.sel||0,o,t.effort):"class"===s.type?i=overlays.renderClassPicker(s.items||[],s.sel||0,o,s.current||t.modelClass,"function"==typeof e.classLabel?e.classLabel:null):"provider"===s.type?i=overlays.renderProviderPicker(s.items||[],s.sel||0,o,s.current,s.hint):"resume"===s.type?i=overlays.renderResumeList(s.items||[],s.sel||0,o,r,s.query||""):"shortcuts"===s.type?i=shortcutsGrid(o,t):"confirm"===s.type?i=confirmLines(s,o,t):"rounds"===s.type?i=roundsLines(s,o,t):"panel"===s.type&&(i=s.lines||[]),!i)return;if("shortcuts"===s.type){const e=Math.max(2,r-i.length-1);for(let t=0;t<i.length;t++)n[e+t]=padLine(i[t],o);return void hideCursor()}const a=Math.max(2,Math.floor((r-i.length)/2));for(let e=0;e<i.length;e++)n[a+e]=padLine(i[e],o);hideCursor()},j=(e,t)=>(r.push(e),t&&!1===t.follow||(E=0,S=null),e),F=(e,t)=>{const n=t?r.indexOf(t):-1;return n<0?r.push(e):r.splice(n,0,e),e},U=e=>j({role:"note",text:e},{follow:!1});let z=0,V=0;const W=()=>z;let Q=Promise.resolve();const J=e=>{const t=Q.then(e,e);return Q=t.then(()=>{},()=>{}),t},X=async t=>{l=!0,c=0,d=Date.now(),z=0,V=0,h=0,g=[],f=VERBS[m%VERBS.length],I=K||adoptTopic(I,t),(e=>{K?isGenericTitle(K)&&D(e):R||D(e)})(t),u=new AbortController,p=setInterval(()=>{c++,N(!0),c%3==0&&B()},100),p.unref&&p.unref(),N(!0),j({role:"user",text:t});const n=j({role:"assistant",text:"",streaming:!0});let o=!1;const i={text:e=>{n.text+=e,z+=w(e),q()},reasoning:e=>{o=!0,z+=w(e)},thinkingTokens:e=>{o=!0,V+=e,q()},tool:e=>{if(e&&void 0!==e.id){const t=g.findIndex(t=>t&&void 0!==t.id&&t.id===e.id);t>=0?g[t]=e:g.push(e)}else g.push(e);if("run"===e.phase){const t=++h,r=e.agent?`${e.agent} ▸ `:"",o=editPreview(e.name,e.args,{cwd:e.cwd});F({role:"tool",phase:"run",name:e.name,args:e.args,agent:e.agent,id:e.id,label:`Running ${t} ${r}${toolLabel(e.name,t)}…`,start:Date.now(),diff:o,diffOpen:defaultOpen(o)},n)}else if(!resolveToolDone(r,e)){const t=++h,r=editPreview(e.name,e.args,{cwd:e.cwd});F({role:"tool",phase:"done",name:e.name,args:e.args,agent:e.agent,id:e.id,ok:e.ok,label:`Ran ${t} ${e.agent?`${e.agent} ▸ `:""}${toolLabel(e.name,t)}`,diff:r,diffOpen:defaultOpen(r)},n)}q()},approval:e=>(e=>new Promise(t=>{J(async()=>{s={type:"confirm",name:e.tool||e.name||"tool",args:e.args||{},sel:0,info:e},B();const n=e=>{s=null,B(),t(e)};for(;;){const e=await nextKey();if(e===STREAM_END||!e)return void n("deny");if(e.name===KEY.UP||e.name===KEY.DOWN||e.name===KEY.TAB){const t=e.name===KEY.UP?-1:1;s.sel=(s.sel+t+APPROVAL_CHOICES.length)%APPROVAL_CHOICES.length,B()}else{if(e.name===KEY.ENTER)return void n(APPROVAL_DECISIONS[s.sel]||"deny");if(e.name===KEY.ESC||e.name===KEY.CTRL_C)return void n("deny");if("char"===e.name){const t=String(e.ch).trim(),r=Number(t)-1;if(Number.isInteger(r)&&r>=0&&r<APPROVAL_DECISIONS.length)return void n(APPROVAL_DECISIONS[r])}}}})}))(e),rounds:t=>(t=>new Promise(n=>{const r=Boolean(e.isYolo&&e.isYolo()),o=autoContinuePlan({on:r,used:a});if(a=o.used,o.auto)return U(`auto: ${t.spent}-round limit reached — continuing automatically (${o.used}/${o.cap}, then it asks).`),B(),void n(!0);r&&(U(`auto: ${o.cap} automatic continuations used — asking you now (answering restarts the block).`),B()),J(async()=>{s={type:"rounds",spent:Number(t.spent)||0,extensions:Number(t.extensions)||1,max:Number(t.max)||8,size:Number(t.size)||Number(t.spent)||0,sel:1},B();const e=e=>{s=null,B(),n(e)};for(;;){const t=await nextKey();if(t===STREAM_END||!t)return void e(!1);if(t.name===KEY.UP||t.name===KEY.DOWN||t.name===KEY.TAB)s.sel=1-s.sel,B();else{if(t.name===KEY.ENTER)return void e(0===s.sel);if(t.name===KEY.ESC||t.name===KEY.CTRL_C)return void e(!1);if("char"===t.name){const n=String(t.ch).trim();if("1"===n)return void e(!0);if("2"===n)return void e(!1)}}}})}))(t)};let S=null;try{S=await e.ask(t,{history:historyPairs(r),presenter:i,signal:u.signal})}catch(e){S={error:e&&e.message||String(e)}}finally{n.streaming=!1,!String(n.text||"").trim()&&S&&"string"==typeof S.text&&S.text.trim()&&(n.text=S.text),l=!1,clearInterval(p),p=null,N(!1);const r=Math.max(1,Math.round((Date.now()-d)/1e3)),s=!(!u||!u.signal.aborted);n.text=finalizeTurnText(n.text,{aborted:s,error:S&&S.error,reasoned:o}),j({role:"done",text:`${h>0?DONE_VERBS[1]:DONE_VERBS[0]} for ${r}s`},{follow:!1}),S&&S.pooled_notice&&j({role:"note",text:S.pooled_notice},{follow:!1}),y=m+1,m++,u=null;try{const e=loadConfig(),t=pingTurn({stream:process.stdout,mode:e.ping,minSeconds:e.pingMinSeconds,elapsedMs:Date.now()-d,isTTY:!!process.stdout.isTTY,aborted:s});t&&j({role:"note",text:t},{follow:!1})}catch{}e.recordTurn(S);let i=null;try{const t=await e.refreshSpend();i=t?t.lastCost:null}catch{}e.persistTurn&&e.persistTurn(t,S,s?"stopped":S&&S.error?"error":"done",i);const a=S&&S.usage,c=e.tokensFor?e.tokensFor(a):null,f=a?usageBuckets(a):null;j({role:"meta",meta:{model:S&&S.model,tokens:c,input:f?f.input:null,output:f?f.output:null,eur:i,ms:S&&S.ms,calls:S&&S.calls||1}},{follow:!1});const w=summarizeTurnTools(g);w.tools>0&&j({role:"summary",counts:w},{follow:0===E}),B()}},Z=e=>{let r=null;if(e.name===KEY.PAGE_UP)r=5;else if(e.name===KEY.PAGE_DOWN)r=-5;else if("wheel"===e.name)r="up"===e.dir?3:-3;else{if("click"===e.name||"drag"===e.name||"release"===e.name)return!(e=>{const t={col:e.col-1,row:e.row-1};if("click"===e.name)return C=t,!1;if("drag"===e.name)return T?T.head=t:T={anchor:C||t,head:t},C=null,!0;const n=C;C=null;const r=T?selectionRange(T.anchor,T.head):null,o=!(!r||r.startRow===r.endRow&&r.startCol===r.endCol);if(T=null,!o)return(e=>{const t=v.get(e);return!(!t||!t.diff||(t.diffOpen=!t.diffOpen,0))})((n||t).row);const s=selectionText(L,r);if(!s)return!0;const i=copyToClipboard(s,{stdout:process.stdout,env:process.env}),a=s.split("\n").length;return P=describeCopy(i,`Marked ${a} line${1===a?"":"s"}`),k=Date.now()+2500,setTimeout(()=>{Date.now()>=k&&B()},2600),!0})(e)||(q(),!0);"char"!==e.name||!t.vim||b||n.buf||("j"===e.ch?r=1:"k"===e.ch&&(r=-1))}return null!==r&&(E=Math.max(0,E+r),S=null,q(),!0)},ee=()=>{if(!s||"resume"!==s.type)return;const e=Array.isArray(s.all)?s.all:[];s.items=sessionSearch.rankSessions(s.query||"",e),s.sel=0,B()},te=()=>s?"palette"===s.type?fuzzy.fuzzyRankWithAliases(paletteQuery(s.query),e.visibleCommands(),e=>e.name,e=>e.aliases||[]).length:"model"===s.type||"resume"===s.type||"class"===s.type||"provider"===s.type?(s.items||[]).length:"effort"===s.type?overlays.EFFORT_VALUES.length:0:0,ne=async n=>{if(n){{const t=models.modelKeyPlan(n,{hasStored:!!e.hasProviderKey&&!!e.hasProviderKey("anthropic")}),{row:r,message:o}=overrideAnthropicByokWithPro(n,{needsKey:!(!t||!t.needed),proLoggedIn:models.claudeProLoggedIn(),proEnabled:(()=>{try{return!0===loadConfig().proEnabled}catch{return!1}})(),proModels:claudePro.PRO_MODELS});n=r,o&&U(o)}if(n.cls&&"aegis"!==n.cls&&t.modelClass!==n.cls){const e="string"==typeof t.modelClass;if(await ie(`/class ${n.cls}`),e&&t.modelClass!==n.cls)return void U(`${n.id} runs on the ${n.cls} class, and this session is on ${t.modelClass} — run /class ${n.cls}${"pro"===n.cls?" on":""}, then pick it again.`)}t.model=n.id,e.updateConfig({model:n.id,currentModelId:n.id,modelClass:t.modelClass}),U(`model: ${n.id}${"byok"===n.cls?" (byok)":"pro"===n.cls?" (Claude Code Pro)":""}`),await(async t=>{const n=models.modelKeyQueue(t,{accountConfigured:!!e.accountConfigured&&!!e.accountConfigured(),hasStoredFor:t=>!!e.hasProviderKey&&!!e.hasProviderKey(t)});if(!n.length)return;let r=null;try{r=e.makeCommandContext()}catch{r=null}if(!r||"function"!=typeof r.readSecret){const e=n.map(e=>`${e.env}: ${e.why}`).join(" · ");return void U(`${t.id} has no key: ${e}. Set the ones above and pick it again.`)}for(const e of n){const n="account"===e.role?"AEGIS account key":"claude-pro"===e.role?"Claude Code OAuth token (`claude setup-token` mints one)":`${e.provider} key`,o=String(await r.readSecret(`${n} → ${e.env} (kept off screen, Enter to skip): `)||"").trim();if(!o){U(`no key given — ${e.env} is still unset, so ${t.id} will fail until it is.`);continue}const s="account"===e.role?"AEGIS":"claude-pro"===e.role?"Claude Code OAuth":e.provider||"that provider",i=validateApiKey(o,{label:s});if(!i.ok){U(`not saved — ${i.message}. ${e.env} is still unset.`);continue}const a=models.storeModelKey(t,i.key,{env:e.env});a.ok?U(a.changed?a.foreign?`${e.env} saved to ${a.file} (0600) — read only by the Claude Code Pro transport, never exported.`:`${e.env} saved to ${a.file} (0600) — both hosts read that file; nothing to export.`:`${e.env} was already set in ${a.file}.`):U(`could not save the key: ${a.error||"unknown error"}`)}})(n)}},re=async e=>{e&&e.class&&await ie(`/class ${e.class}`)},oe=n=>{const r=overlays.EFFORT_VALUES[n||0];s=null,t.effort=r||"high",e.updateConfig({effort:t.effort}),U(`effort: ${t.effort}`),B()},se=async o=>{if(o)if(s)await(async t=>{const n=s.type;if(t.name===KEY.ESC||t.name===KEY.CTRL_C)return s=null,void B();if("shortcuts"===n||"panel"===n)return s=null,void B();if(t.name===KEY.TAB&&"palette"===n){const e=i()[s.sel||0];return void(e&&(s.query=e.name,s.sel=0,B()))}if(t.name===KEY.TAB&&("model"===n||"effort"===n||"class"===n||"provider"===n)){const e="model"===n||"class"===n||"provider"===n?(s.items||[]).length:overlays.EFFORT_VALUES.length;return void(e&&(s.sel=((s.sel||0)+1)%e,B()))}if(t.name===KEY.ENTER){if("palette"===n){const e=i()[s.sel||0],t=String(s.query||"").trim().split(/\s+/).slice(1).join(" ");return s=null,B(),void(e&&await ie(t?`/${e.name} ${t}`:`/${e.name}`))}if("model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ne(e),void B()}if("effort"===n)return void oe(s.sel||0);if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await re(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await ie(`/${t} ${e.id}`))}if("resume"===n){const t=(s.items||[])[s.sel||0];return s=null,B(),void(t&&e.resumeSession&&await e.resumeSession(t))}return s=null,void B()}if(t.name===KEY.SHIFT_UP||t.name===KEY.SHIFT_DOWN){const e=t.name===KEY.SHIFT_UP?-1:1,r=Math.max(0,te()-1);if(s.sel=Math.min(r,Math.max(0,(s.sel||0)+e)),"model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ne(e),void B()}if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await re(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await ie(`/${t} ${e.id}`))}return"effort"===n?void oe(s.sel||0):void B()}if(t.name===KEY.SHIFT_ENTER){if("palette"===n){const e=i()[s.sel||0];return s=null,B(),void(e&&await ie(`/${e.name}`))}if("model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ne(e),void B()}if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await re(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await ie(`/${t} ${e.id}`))}return"effort"===n?void oe(s.sel||0):void 0}if(t.name===KEY.UP||t.name===KEY.DOWN){const e=(s.items||[]).length||te(),n=t.name===KEY.UP?-1:1;return s.sel=Math.min(Math.max(0,e-1),Math.max(0,(s.sel||0)+n)),void B()}if("char"===t.name){if("palette"===n)return s.query=(s.query||"")+t.ch,s.sel=0,void B();if("resume"===n)return s.query=(s.query||"")+t.ch,void ee();if("model"===n){const e=parseInt(t.ch,10),n=s.items||[];return void(Number.isFinite(e)&&e>=1&&e<=n.length&&(s.sel=e-1,B()))}if("effort"===n||"class"===n||"provider"===n){const e=parseInt(t.ch,10),n=te();return void(Number.isFinite(e)&&e>=1&&e<=n&&(s.sel=e-1,B()))}}if(t.name===KEY.BACKSPACE&&"resume"===n)return s.query=String(s.query||"").slice(0,-1),void ee();t.name===KEY.BACKSPACE&&"palette"===n&&(s.query=String(s.query||"").slice(0,-1),B())})(o);else{if("char"===o.name&&!n.buf){if("/"===o.ch)return s={type:"palette",query:"",sel:0},void B();if("?"===o.ch)return s={type:"shortcuts"},void B()}if(!t.vim||b||n.buf||"char"!==o.name){if(t.vim&&b&&o.name===KEY.ESC)return b=!1,n.cursor>0&&n.cursor--,void B()}else{const e=o.ch;if("i"===e||"a"===e||"o"===e||"s"===e||"S"===e)return"s"===e&&n.substChar(),"S"===e&&n.substLine(),"a"===e&&n.right(),b=!0,void B();if("h"===e)return n.left(),void B();if("l"===e)return n.right(),void B();if("0"===e)return n.home(),void B();if("$"===e)return n.end(),void B();if("x"===e)return n.delete(),void B();if("D"===e)return n.killToEnd(),void B();if("A"===e)return n.end(),b=!0,void B();if(Z(o))return}if(o.name===KEY.ENTER){const e=n.submit();return Y=null,b=!1,e?void await ie(e):void B()}if(o.name!==KEY.CTRL_V)if(o.name!==KEY.CTRL_B){if("paste"===o.name)return t.vim&&(b=!0),n.insert(String(o.text)),void B();if("char"===o.name)return t.vim&&!b||n.insert(o.ch),void B();if(o.name===KEY.BACKSPACE)return n.backspace(),void B();if(o.name===KEY.DELETE)return n.delete(),void B();if(o.name===KEY.LEFT||o.name===KEY.CTRL_LEFT)return o.name===KEY.CTRL_LEFT?n.wordBack():n.left(),void B();if(o.name!==KEY.RIGHT||n.buf){if(o.name===KEY.RIGHT||o.name===KEY.CTRL_RIGHT)return n.right(),void B();if(o.name===KEY.HOME||o.name===KEY.CTRL_A)return n.home(),void B();if(o.name===KEY.END||o.name===KEY.CTRL_E)return n.end(),void B();if(o.name===KEY.UP)return n.historyUp(),void B();if(o.name===KEY.DOWN)return n.historyDown(),void B();if(o.name===KEY.TAB)return(()=>{const t=n.buf;if(!t.startsWith("/")||t.includes(" "))return!1;const r=t.slice(1),o=e.visibleCommands().flatMap(e=>[e.name,...e.aliases||[]]).filter(e=>e.startsWith(r)).sort();return!!o.length&&(Y&&Y.q===r||(Y={q:r,i:-1}),Y.i=(Y.i+1)%o.length,n.buf="/"+o[Y.i],n.end(),!0)})()||(P=n.buf?"Tab completes commands":"Use alt+t to toggle thinking",k=Date.now()+2500,setTimeout(()=>{Date.now()>=k&&B()},2600)),void B();if(o.name===KEY.CTRL_U)return n.buf="",n.cursor=0,void B();if(o.name===KEY.CTRL_K)return n.killToEnd(),void B();if(o.name===KEY.CTRL_W)return n.wordBack(),void B();if(o.name===KEY.CTRL_L)return clearScreen(),void B();if(o.name===KEY.CTRL_T)return U(e.tokenSummary?e.tokenSummary():"no token usage yet this session"),void B();if(o.name!==KEY.CTRL_R)if(o.name!==KEY.CTRL_O)if("click"!==o.name&&"drag"!==o.name&&"release"!==o.name)if(o.name!==KEY.PAGE_UP&&o.name!==KEY.PAGE_DOWN&&"wheel"!==o.name)if("alt"!==o.name||"p"!==o.ch){if("alt"===o.name&&"t"===o.ch){const n=!(!0===t.thinking);return t.thinking=n,e.updateConfig({thinking:n}),U("Thinking blocks: "+(n?"expanded":"collapsed")),void B()}if(o.name!==KEY.ESC)return o.name===KEY.CTRL_C?n.buf?(n.buf="",n.cursor=0,void B()):void await ue():void(o.name!==KEY.CTRL_D||n.buf||await ue());n.buf&&(n.buf="",n.cursor=0,B())}else await ie("/model");else Z(o);else Z(o);else await ie("/permissions");else await ie("/resume")}else await ie(e.isYolo&&e.isYolo()?"/automode off":"/automode on")}else(()=>{if(!r.length)return void G("Nothing to copy yet");const e=copyToClipboard(transcriptToMarkdown(r),{stdout:process.stdout,env:process.env});G(describeCopy(e,"Copied the conversation"))})();else(()=>{const e=readClipboardImage({env:process.env});if(e.ok)try{const t=path.join(aegisDir(),"clipboard");fs.mkdirSync(t,{recursive:!0});const r="image/jpeg"===e.mime?"jpg":"png",o=path.join(t,`pasted-${(new Date).toISOString().replace(/[:.]/g,"-")}.${r}`);fs.writeFileSync(o,e.data,{mode:384});const s=n.buf&&!/\s$/.test(n.buf)?" ":"";return n.insert(s+o),void G(`Pasted image → ${o}`)}catch(e){return void G(`Could not save the pasted image: ${e&&e.message||e}`)}const t=readClipboardText({env:process.env});if(t.ok&&t.text)return n.insert(t.text),void G(`Pasted ${t.text.length} character${1===t.text.length?"":"s"} from the clipboard`);G(t.ok?"Clipboard is empty — nothing to paste":`Cannot read the clipboard here (${t.error}) — use your terminal's own paste shortcut instead`)})()}},ie=async t=>{const r=String(t||"").trim();if("?"===r)return s={type:"shortcuts"},void B();(!1===await(async e=>{try{return await((e,t)=>{const n=[];let r,o,i=!1;return e.then(e=>{i=!0,r=e},e=>{i=!0,o=e}),(async()=>{for(;!i;){if(await Promise.resolve(),!l||s&&"confirm"===s.type){await new Promise(e=>setTimeout(e,60));continue}const e=await nextKeyTimeout(120);if(null!==e)if(e.name===KEY.ESC||e.name===KEY.CTRL_C){const e=t&&t();e&&e.abort()}else Z(e)||n.push(e)}if(requeueKeys(n),o)throw o;return r})()})(e(),()=>u)}catch(e){return j({role:"note",text:`Error: ${e&&e.message||String(e)}`},{follow:!1}),void B()}})(async()=>{if(r.startsWith("/")){const t=(()=>{const t=e.makeCommandContext();return Object.assign(t,{push:(e,t)=>{j(e,t),B()},note:e=>{j({role:"note",text:e}),B()},panel:e=>{j({role:"panel",lines:e||[]}),B()},render:()=>B(),openOverlay:e=>{if(e&&"resume"===e.type){const t=Array.isArray(e.items)?e.items:[];return s={...e,all:t,query:"string"==typeof e.query?e.query:"",items:sessionSearch.rankSessions("string"==typeof e.query?e.query:"",t),sel:0},void B()}s=e,B()},closeOverlay:()=>{s=null,showCursor(),B()},askInput:e=>(e=>new Promise(t=>{$={title:e,buf:""},B(),(async()=>{for(;;){const e=await nextKey();if(!$)return void t(null);if(e.name===KEY.ESC||e.name===KEY.CTRL_C||e.name===KEY.CTRL_D)return $=null,B(),void t(null);if(e.name===KEY.ENTER){const e=$.buf;return $=null,B(),void t(e)}e.name===KEY.BACKSPACE?$.buf=[...$.buf].slice(0,-1).join(""):"char"===e.name?$.buf+=e.ch:"paste"===e.name&&($.buf+=String(e.text).replace(/\n/g," ")),B()}})()}))(e),withWorking:e=>(async e=>{const t=u;l=!0,c=0,d=Date.now(),f=VERBS[m%VERBS.length],u=new AbortController,p=setInterval(()=>{c++,N(!0),c%3==0&&B()},100),p.unref&&p.unref(),N(!0);try{return await e(u.signal)}finally{l=!1,clearInterval(p),p=null,u=t,N(!1),B()}})(e),runPrompt:async e=>{await X(e)},state:()=>e.buildState(),setInput:e=>{n.buf=String(null==e?"":e),n.end(),B()},exit:()=>e.requestExit(),openStream:e=>{x=e||null,O=Date.now(),B()},closeStream:e=>{e&&x!==e||(x=null),B()},showThemePicker:()=>{e.showThemePicker&&e.showThemePicker(),B()}}),t})();return e.dispatchLine(r,t)}return await X(r),!0})||e.wantsExit())&&await ue()};let ae=!1,le=null;const ue=()=>{ae||(ae=!0,le&&le(0))},ce=()=>{hideCursor(),paint([]);try{process.stdout.write("[0m")}catch{}try{A&&writeTitle("",process.stdout)}catch{}try{process.stdin.setRawMode(!1)}catch{}disableBracketedPaste(),disableMouseTracking(),leaveAltScreen()};let pe=!1;const de=()=>{if(!pe){pe=!0;try{ce()}catch{}}};process.once("exit",de);const fe=e.stdin||process.stdin;markSessionStart(),attachKeyStream(fe),enableBracketedPaste(),enableMouseTracking(),enterAltScreen(),clearScreen(),hideCursor(),N(!1);const me=()=>B();"win32"!==process.platform?process.on("SIGWINCH",me):process.stdout.on("resize",me);const he=()=>{l&&u?u.abort():ue()};process.on("SIGINT",he);const ge=e=>{ce();try{process.stderr.write(`\nAEGIS Code hit an unexpected error. Your transcript is saved; rerun to continue.\n${e&&e.stack||e}\n`)}catch{}process.exit(1)};process.on("uncaughtException",ge),process.on("unhandledRejection",ge),B();try{return await new Promise(e=>{le=e,(async()=>{for(;!ae;){const e=await nextKey();if(ae)break;if(e===STREAM_END||!e){ue();break}try{await se(e)}catch(e){j({role:"note",text:`Error: ${e&&e.message||String(e)}`},{follow:!1}),B()}}})()})}finally{ae=!0,process.off("SIGINT",he),"win32"!==process.platform?process.off("SIGWINCH",me):process.stdout.off("resize",me),process.off("uncaughtException",ge),process.off("unhandledRejection",ge),process.off("exit",de),de(),resetKeyStream()}}module.exports={SUGGESTIONS:SUGGESTIONS,TITLE_SPIN:TITLE_SPIN,FRAME_MS:33,toolLabel:toolLabel,resolveToolDone:resolveToolDone,summarizeTurnTools:summarizeTurnTools,finalizeTurnText:finalizeTurnText,historyPairs:historyPairs,overrideAnthropicByokWithPro:overrideAnthropicByokWithPro,paletteQuery:paletteQuery,headerLine:headerLine,separatorLine:separatorLine,effortLine:effortLine,spinnerLine:spinnerLine,statusLine:statusLine,shortcutsGrid:shortcutsGrid,confirmLines:confirmLines,APPROVAL_CHOICES:APPROVAL_CHOICES,APPROVAL_DECISIONS:APPROVAL_DECISIONS,roundsLines:roundsLines,autoContinuePlan:autoContinuePlan,autoContinueLimit:autoContinueLimit,AUTO_CONTINUE_LIMIT:AUTO_CONTINUE_LIMIT,rowLines:rowLines,transcriptLines:transcriptLines,inputPreviewText:inputPreviewText,inputRowCells:inputRowCells,inputScroll:inputScroll,inputStart:inputStart,inputLine:inputLine,runSession:runSession};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{ensurePrivateDir:ensurePrivateDir,writePrivateFile:writePrivateFile}=require("./securefs.js"),CHECKPOINT_LIMIT=8;function checkpointsPath(t){return path.join(aegisDir(),"checkpoints",`${t}.jsonl`)}function snapshotCheckpoint(t,e){try{ensurePrivateDir(path.dirname(checkpointsPath(t)));const r={ts:(new Date).toISOString(),depth:e.length,words:e.reduce((
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{ensurePrivateDir:ensurePrivateDir,writePrivateFile:writePrivateFile}=require("./securefs.js"),CHECKPOINT_LIMIT=8;function checkpointsPath(t){return path.join(aegisDir(),"checkpoints",`${t}.jsonl`)}function snapshotCheckpoint(t,e){try{ensurePrivateDir(path.dirname(checkpointsPath(t)));const r={ts:(new Date).toISOString(),depth:e.length,words:e.reduce((t,e)=>t+(e.text||"").split(/\s+/).length,0),transcript:e},n=checkpointsPath(t),i=[...fs.existsSync(n)?fs.readFileSync(n,"utf8").split("\n").filter(Boolean):[],JSON.stringify(r)],s=i.slice(Math.max(0,i.length-8));return writePrivateFile(n,s.join("\n")+"\n"),i.length-1}catch{return-1}}function listCheckpoints(t){try{return fs.readFileSync(checkpointsPath(t),"utf8").split("\n").filter(Boolean).map((t,e)=>{try{const r=JSON.parse(t);return{idx:e,ts:r.ts,depth:r.depth||0,words:r.words||0}}catch{return null}}).filter(Boolean).reverse()}catch{return[]}}function loadCheckpoint(t,e){try{const r=fs.readFileSync(checkpointsPath(t),"utf8").split("\n").filter(Boolean),n=JSON.parse(r[e]);return n&&Array.isArray(n.transcript)?n.transcript:null}catch{return null}}module.exports={CHECKPOINT_LIMIT:8,checkpointsPath:checkpointsPath,snapshotCheckpoint:snapshotCheckpoint,listCheckpoints:listCheckpoints,loadCheckpoint:loadCheckpoint};
|
|
@@ -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{spawnSync:spawnSync}=require("node:child_process"),fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{writePrivateFile:writePrivateFile}=require("./securefs.js"),ESC="",realPlatform=()=>process.platform;function clipboardCandidates(e,{platform:t=realPlatform(),env:r=process.env}={}){const n="linux"===t,o="darwin"===t,i="win32"===t,a=!!(r||{}).WAYLAND_DISPLAY;return"write"===e?[o&&{name:"pbcopy",cmd:"pbcopy",args:[],env:"any"},i&&{name:"clip",cmd:"clip",args:[],env:"any"},...n?a?[{name:"wl-copy",cmd:"wl-copy",args:[],env:"wayland"},{name:"xclip",cmd:"xclip",args:["-selection","clipboard"],env:"x11"},{name:"xsel",cmd:"xsel",args:["--clipboard","--input"],env:"x11"}]:[{name:"xclip",cmd:"xclip",args:["-selection","clipboard"],env:"x11"},{name:"xsel",cmd:"xsel",args:["--clipboard","--input"],env:"x11"},{name:"wl-copy",cmd:"wl-copy",args:[],env:"wayland"}]:[]].filter(Boolean):"text"===e?[o&&{name:"pbpaste",cmd:"pbpaste",args:[],env:"any"},i&&{name:"powershell",cmd:"powershell",args:["-NoProfile","-Command","Get-Clipboard"],env:"any",winNewline:!0},...n?[{name:"wl-paste",cmd:"wl-paste",args:["--no-newline"],env:"wayland"},{name:"xclip",cmd:"xclip",args:["-selection","clipboard","-o"],env:"x11"},{name:"xsel",cmd:"xsel",args:["--clipboard","--output"],env:"x11"}]:[]].filter(Boolean):[o&&{name:"pngpaste",cmd:"pngpaste",args:["-"],env:"any"},...n?[{name:"wl-paste",cmd:"wl-paste",args:["--type","image/png"],env:"wayland",mime:"image/png"},{name:"wl-paste",cmd:"wl-paste",args:["--type","image/jpeg"],env:"wayland",mime:"image/jpeg"},{name:"xclip",cmd:"xclip",args:["-selection","clipboard","-t","image/png","-o"],env:"x11",mime:"image/png"}]:[]].filter(Boolean)}function dirIsTrusted(e,{platform:t=realPlatform()}={}){try{const r=fs.statSync(e);return!(!r.isDirectory()||"win32"!==t&&(18&r.mode||"function"==typeof process.getuid&&0!==r.uid&&r.uid!==process.getuid()))}catch{return!1}}const WIN_EXTS=["",".exe",".cmd",".bat",".com"];function joinFor(e,t,r){return r&&(/\\/.test(e)||/^[A-Za-z]:/.test(e))?path.win32.join(e,t):path.join(e,t)}function resolveTrustedTool(e,{platform:t=realPlatform(),env:r=process.env}={}){const n=r||{},o="0"!==n.AEGISCODE_TRUST_PATH,i="win32"===t,a=i?path.win32:path,s=String((null!=n.PATH?n.PATH:process.env.PATH)||"").split(i?";":path.delimiter),c=o||i;for(const r of s){const n=String(r).trim().replace(/^"|"$/g,"");if(n&&(i||a.isAbsolute(n))&&(!c||dirIsTrusted(n,{platform:t})))for(const r of i?WIN_EXTS:[""]){const o=joinFor(n,e+r,i);let a,s;try{a=fs.realpathSync(o)}catch{continue}try{s=fs.statSync(a)}catch{continue}if(s.isFile()){if(!i){if(!(73&s.mode))continue;if(c){if(18&s.mode)continue;if("function"==typeof process.getuid&&0!==s.uid&&s.uid!==process.getuid())continue;if(!dirIsTrusted(path.dirname(a),{platform:t}))continue}}return a}}}return null}const base64=e=>Buffer.from(String(e),"utf8").toString("base64"),OSC52_MAX=1e5;function osc52Sequence(e,t=process.env){const r
|
|
3
|
+
"use strict";const{spawnSync:spawnSync}=require("node:child_process"),fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{writePrivateFile:writePrivateFile}=require("./securefs.js"),ESC="",realPlatform=()=>process.platform;function clipboardCandidates(e,{platform:t=realPlatform(),env:r=process.env}={}){const n="linux"===t,o="darwin"===t,i="win32"===t,a=!!(r||{}).WAYLAND_DISPLAY;return"write"===e?[o&&{name:"pbcopy",cmd:"pbcopy",args:[],env:"any"},i&&{name:"clip",cmd:"clip",args:[],env:"any"},...n?a?[{name:"wl-copy",cmd:"wl-copy",args:[],env:"wayland"},{name:"xclip",cmd:"xclip",args:["-selection","clipboard"],env:"x11"},{name:"xsel",cmd:"xsel",args:["--clipboard","--input"],env:"x11"}]:[{name:"xclip",cmd:"xclip",args:["-selection","clipboard"],env:"x11"},{name:"xsel",cmd:"xsel",args:["--clipboard","--input"],env:"x11"},{name:"wl-copy",cmd:"wl-copy",args:[],env:"wayland"}]:[]].filter(Boolean):"text"===e?[o&&{name:"pbpaste",cmd:"pbpaste",args:[],env:"any"},i&&{name:"powershell",cmd:"powershell",args:["-NoProfile","-Command","Get-Clipboard"],env:"any",winNewline:!0},...n?[{name:"wl-paste",cmd:"wl-paste",args:["--no-newline"],env:"wayland"},{name:"xclip",cmd:"xclip",args:["-selection","clipboard","-o"],env:"x11"},{name:"xsel",cmd:"xsel",args:["--clipboard","--output"],env:"x11"}]:[]].filter(Boolean):[o&&{name:"pngpaste",cmd:"pngpaste",args:["-"],env:"any"},...n?[{name:"wl-paste",cmd:"wl-paste",args:["--type","image/png"],env:"wayland",mime:"image/png"},{name:"wl-paste",cmd:"wl-paste",args:["--type","image/jpeg"],env:"wayland",mime:"image/jpeg"},{name:"xclip",cmd:"xclip",args:["-selection","clipboard","-t","image/png","-o"],env:"x11",mime:"image/png"}]:[]].filter(Boolean)}function dirIsTrusted(e,{platform:t=realPlatform()}={}){try{const r=fs.statSync(e);return!(!r.isDirectory()||"win32"!==t&&(18&r.mode||"function"==typeof process.getuid&&0!==r.uid&&r.uid!==process.getuid()))}catch{return!1}}const WIN_EXTS=["",".exe",".cmd",".bat",".com"];function joinFor(e,t,r){return r&&(/\\/.test(e)||/^[A-Za-z]:/.test(e))?path.win32.join(e,t):path.join(e,t)}function resolveTrustedTool(e,{platform:t=realPlatform(),env:r=process.env}={}){const n=r||{},o="0"!==n.AEGISCODE_TRUST_PATH,i="win32"===t,a=i?path.win32:path,s=String((null!=n.PATH?n.PATH:process.env.PATH)||"").split(i?";":path.delimiter),c=o||i;for(const r of s){const n=String(r).trim().replace(/^"|"$/g,"");if(n&&(i||a.isAbsolute(n))&&(!c||dirIsTrusted(n,{platform:t})))for(const r of i?WIN_EXTS:[""]){const o=joinFor(n,e+r,i);let a,s;try{a=fs.realpathSync(o)}catch{continue}try{s=fs.statSync(a)}catch{continue}if(s.isFile()){if(!i){if(!(73&s.mode))continue;if(c){if(18&s.mode)continue;if("function"==typeof process.getuid&&0!==s.uid&&s.uid!==process.getuid())continue;if(!dirIsTrusted(path.dirname(a),{platform:t}))continue}}return a}}}return null}const base64=e=>Buffer.from(String(e),"utf8").toString("base64"),OSC52_MAX=1e5;function osc52Sequence(e,t=process.env){const r=`]52;c;${base64(e)}`,n=t||{};return n.TMUX?`Ptmux;${r.split("").join("")}\\`:n.STY?`P${r}\\`:r}function writeOsc52(e,{stdout:t=process.stdout,env:r=process.env}={}){const n=r||{};if("1"===n.AEGISCODE_NO_OSC52)return!1;if(!t||!t.isTTY||"function"!=typeof t.write)return!1;const o=String(e);if(!o||o.length>1e5)return!1;try{return t.write(osc52Sequence(o,n)),!0}catch{return!1}}function copyToClipboard(e,t={}){const{stdout:r=process.stdout,env:n=process.env,platform:o=realPlatform(),spawn:i=spawnSync}=t,a=n||{};if("1"!==a.AEGISCODE_NO_CLIPBOARD){for(const t of clipboardCandidates("write",{platform:o,env:a})){const r=resolveTrustedTool(t.cmd,{platform:o,env:a});if(!r)continue;const n=i(r,t.args,{input:String(e),encoding:"utf8",timeout:4e3,windowsHide:!0});if(!n.error&&0===n.status)return{ok:!0,via:`tool:${t.name}`}}if(writeOsc52(e,{stdout:r,env:a}))return{ok:!0,via:"osc52:"+(a.TMUX?"tmux":a.STY?"screen":"terminal")}}try{const t=path.join(aegisDir(),"clipboard.txt");return writePrivateFile(t,String(e),{atomic:!1}),{ok:!0,via:"file",path:t}}catch{return{ok:!1,via:"none"}}}function describeCopy(e,t="Copied"){if(!e||!e.ok)return"Clipboard unavailable; nothing copied.";if("file"===e.via)return`${t} — no clipboard tool on this host; the text is in ${e.path}`;const[r,n]=String(e.via).split(":");return"osc52"===r?"terminal"===n?`${t} to the clipboard via the terminal.`:`${t} to the clipboard (through ${n}).`:`${t} to the clipboard (${n}).`}const PNG_MAGIC=Buffer.from([137,80,78,71,13,10,26,10]),JPEG_MAGIC=Buffer.from([255,216,255]);function sniffImage(e){return!e||e.length<8?null:e.subarray(0,8).equals(PNG_MAGIC)?"image/png":e.subarray(0,3).equals(JPEG_MAGIC)?"image/jpeg":null}function readClipboardText(e={}){const{env:t=process.env,platform:r=realPlatform(),spawn:n=spawnSync}=e,o=t||{};if("1"===o.AEGISCODE_NO_CLIPBOARD)return{ok:!1,via:"none",error:"clipboard disabled"};for(const e of clipboardCandidates("text",{platform:r,env:o})){const t=resolveTrustedTool(e.cmd,{platform:r,env:o});if(!t)continue;const i=n(t,e.args,{encoding:"utf8",timeout:4e3,maxBuffer:16777216,windowsHide:!0});if(!i.error&&0===i.status&&null!=i.stdout)return{ok:!0,text:e.winNewline?String(i.stdout).replace(/\r\n/g,"\n").replace(/\n$/,""):String(i.stdout),via:`tool:${e.name}`}}return{ok:!1,via:"none",error:"no clipboard reader available"}}function readClipboardImage(e={}){const{env:t=process.env,platform:r=realPlatform(),spawn:n=spawnSync}=e,o=t||{};if("1"===o.AEGISCODE_NO_CLIPBOARD)return{ok:!1,via:"none",error:"clipboard disabled"};for(const e of clipboardCandidates("image",{platform:r,env:o})){const t=resolveTrustedTool(e.cmd,{platform:r,env:o});if(!t)continue;const i=n(t,e.args,{timeout:5e3,maxBuffer:67108864,windowsHide:!0});if(i.error||0!==i.status||!i.stdout)continue;const a=Buffer.isBuffer(i.stdout)?i.stdout:Buffer.from(String(i.stdout),"utf8"),s=sniffImage(a);if(s)return{ok:!0,data:a,mime:s,via:`tool:${e.name}`}}return{ok:!1,via:"none",error:"no image on the clipboard"}}function clipboardCapabilities({platform:e=realPlatform(),env:t=process.env}={}){const r=r=>clipboardCandidates(r,{platform:e,env:t}).some(r=>!!resolveTrustedTool(r.cmd,{platform:e,env:t}));return{canWrite:r("write"),canReadText:r("text"),canReadImage:r("image")}}module.exports={copyToClipboard:copyToClipboard,describeCopy:describeCopy,readClipboardText:readClipboardText,readClipboardImage:readClipboardImage,sniffImage:sniffImage,clipboardCandidates:clipboardCandidates,clipboardCapabilities:clipboardCapabilities,osc52Sequence:osc52Sequence,writeOsc52:writeOsc52,resolveTrustedTool:resolveTrustedTool,dirIsTrusted:dirIsTrusted};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{historyPath:historyPath,appendHistoryEntries:appendHistoryEntries,readHistoryEntries:readHistoryEntries,readSessionTranscript:readSessionTranscript}=require("./history.js"),{estimateTokens:estimateTokens}=require("./tokens.js"),SOURCE="aegiscode-cli",SYNC_FILE="sync-state.json",DEFAULT_LIMIT=50;function syncStatePath(){return path.join(aegisDir(),SYNC_FILE)}function loadState(){try{const t=JSON.parse(fs.readFileSync(syncStatePath(),"utf8"));if(t&&"object"==typeof t)return{sessions:t.sessions&&"object"==typeof t.sessions?t.sessions:{},lastPushAt:t.lastPushAt||null,lastPullAt:t.lastPullAt||null,importedRemoteAt:t.importedRemoteAt||{},importedRemoteCount:t.importedRemoteCount||{},quota:t.quota&&"object"==typeof t.quota?t.quota:null}}catch{}return{sessions:{},lastPushAt:null,lastPullAt:null,importedRemoteAt:{},importedRemoteCount:{},quota:null}}function readQuota(t){if(!t||"object"!=typeof t)return null;const e=null!=t.tokensUsed?t.tokensUsed:t.tokens_used,s=null!=t.tokenLimit?t.tokenLimit:t.token_limit;if(null==e||null==s)return null;const n=Number(e),o=Number(s);return Number.isFinite(n)&&Number.isFinite(o)?{used:n,limit:o}:null}function recordQuota(t,e,s){const n=Number(e),o=Number(s);return!t||!Number.isFinite(n)||!Number.isFinite(o)||o<=0?null:(t.quota={used:n,limit:o,over:n>=o,at:Date.now()},t.quota)}function saveState(t){try{fs.mkdirSync(aegisDir(),{recursive:!0});const e=syncStatePath()+".tmp";return fs.writeFileSync(e,JSON.stringify(t,null,2)+"\n"),fs.renameSync(e,syncStatePath()),!0}catch(t){return process.env.AEGIS_HIST_DEBUG&&console.error("[cloudsync] write failed:",t),!1}}function localSessions({limit:t=
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{historyPath:historyPath,appendHistoryEntries:appendHistoryEntries,readHistoryEntries:readHistoryEntries,readSessionTranscript:readSessionTranscript}=require("./history.js"),{estimateTokens:estimateTokens}=require("./tokens.js"),SOURCE="aegiscode-cli",SYNC_FILE="sync-state.json",DEFAULT_LIMIT=50;function syncStatePath(){return path.join(aegisDir(),SYNC_FILE)}function loadState(){try{const t=JSON.parse(fs.readFileSync(syncStatePath(),"utf8"));if(t&&"object"==typeof t)return{sessions:t.sessions&&"object"==typeof t.sessions?t.sessions:{},lastPushAt:t.lastPushAt||null,lastPullAt:t.lastPullAt||null,importedRemoteAt:t.importedRemoteAt||{},importedRemoteCount:t.importedRemoteCount||{},quota:t.quota&&"object"==typeof t.quota?t.quota:null}}catch{}return{sessions:{},lastPushAt:null,lastPullAt:null,importedRemoteAt:{},importedRemoteCount:{},quota:null}}function readQuota(t){if(!t||"object"!=typeof t)return null;const e=null!=t.tokensUsed?t.tokensUsed:t.tokens_used,s=null!=t.tokenLimit?t.tokenLimit:t.token_limit;if(null==e||null==s)return null;const n=Number(e),o=Number(s);return Number.isFinite(n)&&Number.isFinite(o)?{used:n,limit:o}:null}function recordQuota(t,e,s){const n=Number(e),o=Number(s);return!t||!Number.isFinite(n)||!Number.isFinite(o)||o<=0?null:(t.quota={used:n,limit:o,over:n>=o,at:Date.now()},t.quota)}function saveState(t){try{fs.mkdirSync(aegisDir(),{recursive:!0});const e=syncStatePath()+".tmp";return fs.writeFileSync(e,JSON.stringify(t,null,2)+"\n"),fs.renameSync(e,syncStatePath()),!0}catch(t){return process.env.AEGIS_HIST_DEBUG&&console.error("[cloudsync] write failed:",t),!1}}function localSessions({limit:t=50}={}){const e=new Map;for(const t of readHistoryEntries()){if(!t||!t.sessionId)continue;const s=e.get(t.sessionId)||{id:t.sessionId,cwd:t.cwd||"",firstPrompt:"",updatedAt:"",exchanges:0};s.exchanges+=1,!s.firstPrompt&&t.prompt&&(s.firstPrompt=String(t.prompt)),String(t.ts||"")>String(s.updatedAt||"")&&(s.updatedAt=t.ts||""),e.set(t.sessionId,s)}return[...e.values()].sort((t,e)=>String(t.updatedAt)<String(e.updatedAt)?1:-1).slice(0,Math.max(1,t))}function titleFor(t){return String(t&&t.firstPrompt||"").replace(/\s+/g," ").trim().slice(0,80)}function buildTranscript(t,e={}){const s=(e.transcript||readSessionTranscript(t.id)).filter(t=>t&&("user"===t.role||"assistant"===t.role)).map(t=>({role:t.role,content:String(null==t.text?"":t.text)}));return{session_id:t.id,title:null!=e.title?e.title:titleFor(t),messages:s,source:e.source||SOURCE}}function isPending(t,e){const s=e.sessions[t.id];return!s||!s.syncedAt||String(t.updatedAt||"")>String(s.localUpdatedAt||"")}function listPending(t={}){const e=t.state||loadState(),s=localSessions({...t,limit:Number.MAX_SAFE_INTEGER}).filter(t=>isPending(t,e)).reverse();return t.limit?s.slice(0,t.limit):s}function markSynced(t,e,s={}){const n=t.sessions[e]||{};return t.sessions[e]={...n,syncedAt:Date.now(),localUpdatedAt:s.localUpdatedAt||n.localUpdatedAt||"",remoteUpdatedAt:s.remoteUpdatedAt||n.remoteUpdatedAt||null,lastError:null},t.sessions[e]}function markFailed(t,e,s){const n=t.sessions[e]||{};return t.sessions[e]={...n,lastError:s,failedAt:Date.now()},t.sessions[e]}function entriesFromRemote(t,e,s=0){const n=[],o=Array.isArray(t.messages)?t.messages:[],i=s>0&&s<=o.length?o.slice(s):o;let r=null;const a=(s,o)=>{null==s&&null==o||n.push({ts:t.updated_at||e,sessionId:t.session_id,cwd:"",prompt:null==s?"":String(s),reply:null==o?"":String(o),status:"done",imported:!0,importedFrom:String(t.source||"cloud"),tokens:{input:estimateTokens(String(s||"")),output:estimateTokens(String(o||"")),cacheRead:0,cacheWrite:0,real:!1}})};for(const t of i){const e=t&&t.role,s=t&&(null!=t.content?t.content:t.text);"user"===e?(null!=r&&a(r,null),r=null==s?"":s):"assistant"!==e&&"system"!==e||(a(r,s),r=null)}return null!=r&&a(r,null),n}function describeError(t){const e=t&&(t.status||t.response&&t.response.status),s=t&&t.message||String(t);if(402===e){const n=t&&t.data||{},o=null!=n.tokensUsed?n.tokensUsed:n.sessionsUsed,i=null!=n.tokenLimit?n.tokenLimit:n.freeSessionLimit;return{kind:"quota",status:e,message:s,used:null!=o?Number(o):null,limit:null!=i?Number(i):null,hint:"the plan’s synced-token ceiling is reached — everything already stored stays readable, only NEW writes pause: /cloud memory shows the quota, /cloud memory off stops syncing"}}return 401===e?{kind:"auth",status:e,message:s,hint:"the memory token was refused — run /key <api_key> to re-exchange it"}:{kind:"error",status:e||null,message:s,hint:null}}async function push(t,e={}){const s=e.state||loadState(),n=e.limit||50,o=e.sessionIds?e.sessionIds.map(t=>localSessions({limit:Number.MAX_SAFE_INTEGER,state:s}).find(e=>e.id===t)).filter(Boolean):listPending({...e,limit:n,state:s}),i=[],r=[],a=[];for(const n of o){const o=buildTranscript(n,{});if(o.messages.length)try{const r=await t.conversationSyncPush(o),a=r&&(r.session_id||r.id)||n.id;markSynced(s,n.id,{localUpdatedAt:n.updatedAt,remoteUpdatedAt:r&&r.updated_at||(new Date).toISOString()});const l=readQuota(r);i.push({id:n.id,remoteId:a,messages:o.messages.length,title:o.title,quota:l}),l&&recordQuota(s,l.used,l.limit),"function"==typeof e.onProgress&&e.onProgress({phase:"push",id:n.id})}catch(t){const e=describeError(t);if(markFailed(s,n.id,e.message),r.push({id:n.id,...e}),"quota"!==e.kind||recordQuota(s,e.used,e.limit)||(s.quota={used:null,limit:null,over:!0,at:Date.now()}),"quota"===e.kind||"auth"===e.kind)break}else a.push({id:n.id,reason:"no messages"})}return i.length&&(s.lastPushAt=Date.now()),saveState(s),{pushed:i,failed:r,skipped:a,pending:listPending({state:s}).length}}async function pull(t,e={}){const s=e.state||loadState(),n=!1!==e.import;let o;try{o=await t.conversationSyncPull()}catch(t){return{ok:!1,sessions:[],imported:0,failed:[describeError(t)]}}const i=o&&o.sessions||[],r=[],a=(new Date).toISOString(),l=[];for(const t of i){const e=t&&t.session_id;if(!e)continue;const o=s.importedRemoteAt[e],i=Array.isArray(t.messages)?t.messages.length:0,u=Number((s.importedRemoteCount||{})[e]||0),d=!o||o!==t.updated_at||i!==u;if(n&&d){const n=entriesFromRemote(t,a,i>=u?u:0);n.length&&l.push(...n),s.importedRemoteAt[e]=t.updated_at||a,s.importedRemoteCount={...s.importedRemoteCount||{},[e]:i}}markSynced(s,e,{localUpdatedAt:t.updated_at||a,remoteUpdatedAt:t.updated_at||a}),r.push({id:e,title:t.title||"",messages:(t.messages||[]).length,source:t.source||"",updatedAt:t.updated_at||null,imported:n&&d})}const u=l.length?appendHistoryEntries(l):0;return s.lastPullAt=Date.now(),saveState(s),{ok:!0,sessions:r,remote:i.length,imported:u,failed:[]}}async function syncNow(t,e={}){const s=e.state||loadState(),n={ok:!0,push:null,pull:null};try{n.push=await push(t,{...e,state:s})}catch(t){n.ok=!1,n.push={pushed:[],failed:[describeError(t)],skipped:[]}}try{n.pull=await pull(t,{...e,state:s}),n.pull&&!1===n.pull.ok&&(n.ok=!1)}catch(t){n.ok=!1,n.pull={ok:!1,sessions:[],imported:0,failed:[describeError(t)]}}return n}function status(){const t=loadState(),e=localSessions({limit:Number.MAX_SAFE_INTEGER}),s=e.filter(e=>isPending(e,t)),n=e.filter(e=>t.sessions[e.id]&&t.sessions[e.id].lastError).map(e=>({id:e.id,error:t.sessions[e.id].lastError})),o=t.quota||null,i=Boolean(o&&o.over);return{local:e.length,pending:s.length,synced:e.length-s.length,lastPushAt:t.lastPushAt,lastPullAt:t.lastPullAt,importedRemote:Object.keys(t.importedRemoteAt||{}).length,errors:n,quota:o,overQuota:i,paused:i&&s.length>0,path:syncStatePath(),historyPath:historyPath()}}module.exports={SOURCE:SOURCE,syncStatePath:syncStatePath,loadState:loadState,saveState:saveState,localSessions:localSessions,titleFor:titleFor,buildTranscript:buildTranscript,isPending:isPending,listPending:listPending,markSynced:markSynced,markFailed:markFailed,entriesFromRemote:entriesFromRemote,describeError:describeError,recordQuota:recordQuota,readQuota:readQuota,push:push,pull:pull,syncNow:syncNow,status:status};
|