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 MAX_FILE_BYTES=33554432,MAX_TEXT_BYTES=524288,MAX_IMAGE_BYTES=5242880,MAX_ATTACHMENTS=8,IMAGE_TOKEN_COST=850,PNG_SIG=Buffer.from([137,80,78,71,13,10,26,10]),JPEG_SIG=Buffer.from([255,216,255]),GIF87=Buffer.from("GIF87a","ascii"),GIF89=Buffer.from("GIF89a","ascii"),PDF_SIG=Buffer.from("%PDF-","ascii"),BMP_SIG=Buffer.from("BM","ascii");function startsWith(t,e){return!(!Buffer.isBuffer(t)||t.length<e.length)&&0===t.compare(e,0,e.length,0,e.length)}function isWebp(t){return Buffer.isBuffer(t)&&t.length>=12&&"RIFF"===t.toString("ascii",0,4)&&"WEBP"===t.toString("ascii",8,12)}function looksLikeText(t,e=8192){if(!Buffer.isBuffer(t)||0===t.length)return!1;const i=t.subarray(0,Math.min(t.length,e));if(i.includes(0))return!1;const n=new TextDecoder("utf-8",{fatal:!0});try{n.decode(i)}catch{return!1}return!0}function sniff(t){return startsWith(t,PNG_SIG)?{kind:"image",mime:"image/png",ext:"png"}:startsWith(t,JPEG_SIG)?{kind:"image",mime:"image/jpeg",ext:"jpg"}:startsWith(t,GIF87)||startsWith(t,GIF89)?{kind:"image",mime:"image/gif",ext:"gif"}:isWebp(t)?{kind:"image",mime:"image/webp",ext:"webp"}:startsWith(t,PDF_SIG)?{kind:"pdf",mime:"application/pdf",ext:"pdf"}:startsWith(t,BMP_SIG)&&t.length>14?{kind:"image",mime:"image/bmp",ext:"bmp"}:looksLikeText(t)?{kind:"text",mime:"text/plain",ext:"txt"}:{kind:"binary",mime:"application/octet-stream",ext:""}}function isVisionMime(t){return"image/png"===t||"image/jpeg"===t||"image/webp"===t||"image/gif"===t}function toDataUrl(t,e){return Buffer.isBuffer(t)?`data:${e||"application/octet-stream"};base64,${t.toString("base64")}`:null}function imagePart(t,e){const i=toDataUrl(t,e);return i?{type:"image_url",image_url:{url:i}}:null}function flattenContent(t){if(null==t)return"";if("string"==typeof t)return t;if(!Array.isArray(t))return String(t);const e=[];for(const i of t)i&&"object"==typeof i&&("string"==typeof i.text?e.push(i.text):"image_url"===i.type&&e.push("[image]"));return e.join("\n")}function imageCount(t){if(!Array.isArray(t))return 0;let e=0;for(const i of t)i&&"image_url"===i.type&&(e+=1);return e}function effectiveMime(t){if(t&&"string"==typeof t.mime&&t.mime)return t.mime;const e=t&&"string"==typeof t.dataUrl?t.dataUrl:"",i=/^data:([^;,]+)[;,]/.exec(e);return i?i[1].toLowerCase():""}function buildContent(t,e){const i=Array.isArray(e)?e.filter(Boolean):[];if(!i.length)return"string"==typeof t?t:"";const n=[],r="string"==typeof t?t:"";r.trim()&&n.push({type:"text",text:r});for(const t of i)if("image"===t.kind&&t.dataUrl&&isVisionMime(effectiveMime(t)))n.push({type:"image_url",image_url:{url:t.dataUrl}});else if("image"===t.kind){const e=effectiveMime(t)||"unknown image type",i=t.path?`[attached image, not inline (${e} is not a vision format): ${t.path}]\nThe file is not attached inline; use a tool to inspect it.`:`[attached image, not inline (${e} is not a vision format)]`;n.push({type:"text",text:i})}else"text"===t.kind&&"string"==typeof t.text?n.push({type:"text",text:`--- ${t.name} ---\n${t.text}`}):"pdf"===t.kind?n.push({type:"text",text:`[attached PDF: ${t.path}]\nUse a tool to read this file.`}):t.path&&n.push({type:"text",text:`[attached file: ${t.path}]`});return 1===n.length&&"text"===n[0].type?n[0].text:n.length?n:r}function pathLines(t){return(Array.isArray(t)?t:[]).map(
|
|
3
|
+
"use strict";const MAX_FILE_BYTES=33554432,MAX_TEXT_BYTES=524288,MAX_IMAGE_BYTES=5242880,MAX_ATTACHMENTS=8,IMAGE_TOKEN_COST=850,PNG_SIG=Buffer.from([137,80,78,71,13,10,26,10]),JPEG_SIG=Buffer.from([255,216,255]),GIF87=Buffer.from("GIF87a","ascii"),GIF89=Buffer.from("GIF89a","ascii"),PDF_SIG=Buffer.from("%PDF-","ascii"),BMP_SIG=Buffer.from("BM","ascii");function startsWith(t,e){return!(!Buffer.isBuffer(t)||t.length<e.length)&&0===t.compare(e,0,e.length,0,e.length)}function isWebp(t){return Buffer.isBuffer(t)&&t.length>=12&&"RIFF"===t.toString("ascii",0,4)&&"WEBP"===t.toString("ascii",8,12)}function looksLikeText(t,e=8192){if(!Buffer.isBuffer(t)||0===t.length)return!1;const i=t.subarray(0,Math.min(t.length,e));if(i.includes(0))return!1;const n=new TextDecoder("utf-8",{fatal:!0});try{n.decode(i)}catch{return!1}return!0}function sniff(t){return startsWith(t,PNG_SIG)?{kind:"image",mime:"image/png",ext:"png"}:startsWith(t,JPEG_SIG)?{kind:"image",mime:"image/jpeg",ext:"jpg"}:startsWith(t,GIF87)||startsWith(t,GIF89)?{kind:"image",mime:"image/gif",ext:"gif"}:isWebp(t)?{kind:"image",mime:"image/webp",ext:"webp"}:startsWith(t,PDF_SIG)?{kind:"pdf",mime:"application/pdf",ext:"pdf"}:startsWith(t,BMP_SIG)&&t.length>14?{kind:"image",mime:"image/bmp",ext:"bmp"}:looksLikeText(t)?{kind:"text",mime:"text/plain",ext:"txt"}:{kind:"binary",mime:"application/octet-stream",ext:""}}function isVisionMime(t){return"image/png"===t||"image/jpeg"===t||"image/webp"===t||"image/gif"===t}function toDataUrl(t,e){return Buffer.isBuffer(t)?`data:${e||"application/octet-stream"};base64,${t.toString("base64")}`:null}function imagePart(t,e){const i=toDataUrl(t,e);return i?{type:"image_url",image_url:{url:i}}:null}function flattenContent(t){if(null==t)return"";if("string"==typeof t)return t;if(!Array.isArray(t))return String(t);const e=[];for(const i of t)i&&"object"==typeof i&&("string"==typeof i.text?e.push(i.text):"image_url"===i.type&&e.push("[image]"));return e.join("\n")}function imageCount(t){if(!Array.isArray(t))return 0;let e=0;for(const i of t)i&&"image_url"===i.type&&(e+=1);return e}function effectiveMime(t){if(t&&"string"==typeof t.mime&&t.mime)return t.mime;const e=t&&"string"==typeof t.dataUrl?t.dataUrl:"",i=/^data:([^;,]+)[;,]/.exec(e);return i?i[1].toLowerCase():""}function buildContent(t,e){const i=Array.isArray(e)?e.filter(Boolean):[];if(!i.length)return"string"==typeof t?t:"";const n=[],r="string"==typeof t?t:"";r.trim()&&n.push({type:"text",text:r});for(const t of i)if("image"===t.kind&&t.dataUrl&&isVisionMime(effectiveMime(t)))n.push({type:"image_url",image_url:{url:t.dataUrl}});else if("image"===t.kind){const e=effectiveMime(t)||"unknown image type",i=t.path?`[attached image, not inline (${e} is not a vision format): ${t.path}]\nThe file is not attached inline; use a tool to inspect it.`:`[attached image, not inline (${e} is not a vision format)]`;n.push({type:"text",text:i})}else"text"===t.kind&&"string"==typeof t.text?n.push({type:"text",text:`--- ${t.name} ---\n${t.text}`}):"pdf"===t.kind?n.push({type:"text",text:`[attached PDF: ${t.path}]\nUse a tool to read this file.`}):t.path&&n.push({type:"text",text:`[attached file: ${t.path}]`});return 1===n.length&&"text"===n[0].type?n[0].text:n.length?n:r}function pathLines(t){return(Array.isArray(t)?t:[]).map(t=>t&&t.path?/[\s"']/.test(t.path)?`"${t.path}"`:t.path:"").filter(Boolean).join("\n")}function describe(t){return t&&"object"==typeof t?`${String(t.name||t.path||"file")} · ${humanBytes(Number(t.size)||0)}`:""}function humanBytes(t){const e=Number(t)||0;return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1048576).toFixed(1)} MB`}module.exports={MAX_FILE_BYTES:33554432,MAX_TEXT_BYTES:524288,MAX_IMAGE_BYTES:5242880,MAX_ATTACHMENTS:8,IMAGE_TOKEN_COST:850,sniff:sniff,looksLikeText:looksLikeText,isVisionMime:isVisionMime,toDataUrl:toDataUrl,imagePart:imagePart,flattenContent:flattenContent,imageCount:imageCount,buildContent:buildContent,pathLines:pathLines,describe:describe,humanBytes:humanBytes};
|
|
@@ -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 queue=require("./queue.js"),gitScope=require("./git-scope.js"),DEFAULT_ROUNDS=40,MAX_ROUND_STOPS=3,WRITE_TOOLS=new Set(["writeFile","editFile"]),DEFAULT_AUTO_CONTINUES=3;function autoContinueLimit(e=process.env){const t=Number.parseInt(e&&e.AEGIS_AUTO_CONTINUE_MAX,10);return Number.isFinite(t)&&t>0?t:3}const AUTO_ROUNDS_OFF=new Set(["0","false","off","no"]);function autoRoundsDefault(e=process.env){const t=e&&e.AEGIS_AUTO_ROUNDS;if(null==t)return!0;const o=String(t).trim().toLowerCase();return!o||!AUTO_ROUNDS_OFF.has(o)}function autoContinuePlan({on:e=!1,used:t=0,limit:o=3}={}){const n=Number.isFinite(o)&&o>0?Math.floor(o):3,r=Number.isFinite(t)&&t>0?Math.floor(t):0;return e?r>=n?{auto:!1,used:0,cap:n}:{auto:!0,used:r+1,cap:n}:{auto:!1,used:r,cap:n}}function writtenPath(e){const t=e&&e.args||{},o=t.file_path||t.path;return o?String(o):""}const DEFAULT_MODEL="nexus-brain",MODEL_CLASSES=Object.freeze(["aegis","byok","local","pro"]),AEGIS_MODEL_RE=/^(?:nexus|aegis)-brain(?:-(?:smart|neo))?$/,AEGIS_MODEL_IDS=Object.freeze(["nexus-brain","aegis-brain"]);function isAegisModel(e){return AEGIS_MODEL_RE.test(String(null==e?"":e).trim())}function normalizeClass(e){return String(null==e?"":e).trim().toLowerCase()||"aegis"}function looksLikeByokModel(e){const t=String(null==e?"":e).trim(),o=t.indexOf(":");return o>0&&o<t.length-1}function modelRefusal(e,t){const o=String(null==e?"":e).trim(),n=normalizeClass(t);if(!MODEL_CLASSES.includes(n))return`"${t}" is not a model class the queue serves (${MODEL_CLASSES.join("/")})`;if("aegis"===n)return!o||isAegisModel(o)?"":`the autonomous queue's Aegis Cloud class runs pooled-brain models only (${DEFAULT_MODEL}, ${AEGIS_MODEL_IDS.join("/")} aliases); "${o}" is not one`;if("byok"===n)return o?looksLikeByokModel(o)?"":`"${o}" is not a byok model id — it must be "<provider>:<model>" (pick one from /models)`:'a byok task needs a model, as "<provider>:<model>" (pick one from /models)';if("pro"===n){if(!o)return"";let e;try{e=require("./claude-pro.js").PRO_MODELS}catch{return"a pro task's model cannot be checked right now — queue it with no --model to let the claude CLI pick"}const t=(Array.isArray(e)?e:[]).map((e=>String(e&&e.id).trim()));return t.includes(o.toLowerCase())?"":`the autonomous queue's Pro class runs the subscription through the claude CLI, which accepts only its own model aliases (${t.join("/")}); "${o}" is not one`}return o?"":"a local task needs a model — the tag of whatever is pulled into the local daemon"}const AUTONOMOUS_REQUEST_RE=/\bautonomously\b|\bon your own\b|\bwithout asking\b|\bend[- ]to[- ]end\b|\bno (?:more )?questions\b|\bfully autonomous\b|\bqueue it\b/i;function isAutonomousRequest(e){return AUTONOMOUS_REQUEST_RE.test(String(e||""))}function maxRounds(e=process.env,t){const o=Number.parseInt(t,10);if(Number.isFinite(o)&&o>0)return o;const n=Number.parseInt(e&&e.AEGIS_AUTONOMOUS_MAX_ROUNDS||"",10);return Number.isFinite(n)&&n>0?n:DEFAULT_ROUNDS}function withRoundHorizon(e,t,o){const n="AEGIS_AUTONOMOUS_MAX_ROUNDS",r=[];for(const e of[t,process.env])e&&-1===r.indexOf(e)&&r.push(e);const s=r.map((e=>({target:e,had:Object.prototype.hasOwnProperty.call(e,n),prev:e[n]})));try{for(const t of r)t[n]=String(e)}catch{}const i=()=>{for(const e of s)try{e.had?e.target[n]=e.prev:delete e.target[n]}catch{}};let a;try{a=o()}catch(e){throw i(),e}return a&&"function"==typeof a.then?a.then((e=>(i(),e)),(e=>{throw i(),e})):(i(),a)}function resolveModel({model:e,env:t,cls:o}={}){const n=String(e||"").trim();if("aegis"!==normalizeClass(o))return n;if(n)return n;const r=t||process.env,s=String(r.AEGIS_AUTONOMOUS_MODEL||r.AEGIS_MODEL||"").trim();return isAegisModel(s)?s:DEFAULT_MODEL}function ignoredEnvModel({model:e,env:t,cls:o}={}){if("aegis"!==normalizeClass(o))return"";if(String(e||"").trim())return"";const n=t||process.env,r=String(n.AEGIS_AUTONOMOUS_MODEL||n.AEGIS_MODEL||"").trim();return!r||isAegisModel(r)?"":`${String(n.AEGIS_AUTONOMOUS_MODEL||"").trim()?"AEGIS_AUTONOMOUS_MODEL":"AEGIS_MODEL"}="${r}" is not an Aegis Cloud model — running on ${DEFAULT_MODEL} instead`}function resolveFanout(e={},t=process.env){const o=e||{};if(!0===o.autonomous||!1===o.singlePass)return!0;const n=t||process.env;return/^(1|true|yes|on)$/i.test(String(n.AEGIS_AUTONOMOUS_FANOUT||"").trim())}function resolveEffort({effort:e,env:t,fanout:o}={}){const n=t||process.env;return String(e||n.AEGIS_AUTONOMOUS_EFFORT||"").trim()||(o?"high":"medium")}function autonomousDirective(e=DEFAULT_ROUNDS){return["# Autonomous mode",`You are running autonomously, not in a conversation: there is no user to answer a question or approve a plan. You have up to ${e} tool rounds this turn; use as many as the task needs.`,"Work the task end to end:","1. Plan in one line, then start acting in the same turn — never end a turn on a plan.","2. Read only what you need to make the change (no fishing through the repo).","2b. If this demand has been made before, establish whether it was met: check recalled memory, the queue file, PLAN.md, and git history for the earlier attempt. When it was fixed and the problem is back, state how it was fixed then and why it regressed, and fix that cause — a blind re-fix is a regression, not a resolution.","3. Make the change with Write/Edit/Bash, then VERIFY it: re-read the result and run the relevant test/command.","4. If verification fails, fix it and verify again — loop until it passes or you are genuinely blocked.",'5. Do not ask for permission, do not hand the work back, do not stop at "let me check…".',"6. Finish with a short report: what changed (file paths), the command you ran to verify, its result, and any remaining blocker."].join("\n")}function digestLine(e,t){const o=String(e.task||"").replace(/\s+/g," ").trim().slice(0,120),n=Boolean(t&&t.ok&&t.stoppedOnRounds)?"⏸":t&&t.ok?"✓":"✗",r=t&&Array.isArray(t.files)&&t.files.slice(0,6)||[],s=r.length?` — touched: ${r.join(", ")}${t.files.length>r.length?", …":""}`:"",i=!t||t.ok?"":` — ${String(t&&t.error||"failed").slice(0,120)}`;return`- #${e.id} ${n} ${o}${s}${i}`}function appendDigest(e,t,{keep:o=6}={}){return String(e||"").split("\n").filter(Boolean).concat(t).slice(-o).join("\n")}function taskPrompt(e,{carry:t="",rounds:o=DEFAULT_ROUNDS}={}){const n=[autonomousDirective(o)];return t&&n.push("# Earlier tasks in this run\nWork already done by this queue — do not redo it, build on it:\n"+t),n.push("# Task\n"+String(e.task||"").trim()),n.join("\n\n")}function assistantText(e){if(!e||"object"!=typeof e)return"";const t=Array.isArray(e.choices)?e.choices[0]:null,o=t&&t.message?t.message.content:e.content;return"string"==typeof o?o:Array.isArray(o)?o.map((e=>"string"==typeof e?e:e&&"string"==typeof e.text?e.text:"")).join(""):""}function errorText(e){return e?"string"==typeof e?e:String(e.message||e.error||e):"unknown error"}function createQueueWorker({engine:e,env:t=process.env,log:o=(()=>{}),git:n=gitScope,now:r=Date.now,canFanOut:s=(()=>!0)}={}){if(!e||"function"!=typeof e.chat)throw new Error("autonomous: a local engine with chat() is required");const i=e=>{try{o(e)}catch{}},a=()=>{try{return!1!==s()}catch{return!1}};async function u(o,{carry:s="",commit:u}={}){const c=o.cwd||process.cwd(),d=normalizeClass(o.class),h=modelRefusal(o.model,d);if(h){const e={ok:!1,error:h,model:o.model,class:d,ms:0};return i({type:"finish",taskId:o.id,ok:!1,result:e}),e}const p=resolveModel({model:o.model,env:t,cls:d}),f=ignoredEnvModel({model:o.model,env:t,cls:d});f&&i({type:"note",taskId:o.id,note:f});const g="aegis"===d&&resolveFanout(o,t),k=g&&a();g&&!k&&i({type:"note",taskId:o.id,note:"fan-out needs Pro (the cloud drain that keeps running after you close the laptop) — this task ran as a single pass"});const O=resolveEffort({effort:o.effort,env:t,fanout:k}),S=maxRounds(t,o.maxRounds);let y=null,E=0;const A=new Set,_=e=>{if(e&&"object"==typeof e)if(e.approval)y=e.approval;else if(e.tool){if("done"===e.tool.phase&&(E+=1,WRITE_TOOLS.has(e.tool.name)&&!1!==e.tool.ok)){const t=writtenPath(e.tool);t&&A.add(t)}i({type:"tool",taskId:o.id,tool:e.tool})}else"string"==typeof e.delta?i({type:"delta",taskId:o.id,text:e.delta}):"string"==typeof e.reasoning&&i({type:"reasoning",taskId:o.id,text:e.reasoning})},v=void 0===u?Boolean(o.commit):Boolean(u),M=v?l((()=>n.gitStatusSnapshot(c)),null):null;i({type:"start",taskId:o.id,model:p,class:d,cwd:c,rounds:S,fanout:k,effort:O});const w=r();let D;try{const n=await withRoundHorizon(S,t,(()=>e.chat({class:d,model:p,prompt:taskPrompt(o,{carry:s,rounds:S}),autonomous:k,singlePass:!k,effort:O,workers:k&&o.workers||void 0,env:{cwd:c},maxRounds:S,sessionId:m(o.id),stream:!0},_)));D={ok:!0,output:assistantText(n),usage:n&&n.usage||null,stoppedOnRounds:Boolean(n&&n.stoppedOnRounds),rounds:E||void 0},y&&(D.ok=!1,D.error=`tool approval was requested for "${y.tool||y.name||"a tool"}" with no one to answer it — construct the queue engine with approvals disabled (getConfirmMode: () => false)`)}catch(e){D={ok:!1,error:errorText(e)}}return D.ms=Math.max(0,r()-w),v&&(D.commit=l((()=>n.scopedCommit(c,{message:commitMessage(o),before:M,written:[...A]})),{ok:!1,error:"git-scope unavailable"}),D.files=function(e,t){return!e||e.error?[]:Array.isArray(e.paths)?e.paths:[...t]}(D.commit,A)),i({type:"finish",taskId:o.id,ok:D.ok,result:D}),D}function l(e,t){try{return e()}catch{return t}}async function c({commit:e,max:o=0,stopOnError:n=!1,carry:r=""}={}){const s=queue.acquireLock(t);if(!s.ok)return i({type:"locked",holder:s.holder}),{ok:!1,locked:!0,holder:s.holder,ran:[],carry:r};const a=[];try{for(;!(o>0&&a.length>=o);){const o=queue.loadQueue(t),s=queue.recoverStale(o);s.length&&(queue.saveQueue(t,o),i({type:"recovered",ids:s}));const u=queue.pending(o)[0];if(!u)break;const l=await d(u,{commit:e,carry:r});if(r=l.carry,a.push(l),!l.ok&&n)break}}finally{queue.releaseLock(t)}return{ok:!0,ran:a,carry:r}}async function d(e,{commit:o,carry:n=""}={}){const s=queue.loadQueue(t),i=queue.markRunning(s,e.id,{now:r()});if(!i)return{ok:!1,error:`unknown task #${e.id}`,carry:n};const a=Number(i.roundStops)||0;queue.saveQueue(t,s);const l=await u(i,{carry:n,commit:o}),c=Boolean(l.ok&&l.stoppedOnRounds),d=c?a+1:0,m=c&&d>3,h=m?{...l,ok:!1,error:`stopped at its tool-round horizon ${d} times in a row without finishing — raise AEGIS_AUTONOMOUS_MAX_ROUNDS or split the task into smaller ones`}:l,p=m?"error":c?"pending":h.ok?"done":"error",f=queue.loadQueue(t);queue.settle(f,i.id,{status:p,result:{ok:h.ok,output:h.output||"",usage:h.usage||null,ms:h.ms,commit:h.commit||null,files:h.files||[]},error:h.ok?null:h.error,now:r()});const g=queue.findTask(f,i.id);return g&&(g.roundStops=d),queue.saveQueue(t,f),queue.appendRun(t,{id:i.id,task:i.task,cwd:i.cwd,model:resolveModel({model:i.model,env:t}),status:"pending"===p?"stopped":p,at:new Date(r()).toISOString(),ms:h.ms,usage:h.usage||null,files:h.files||[],error:h.ok?null:h.error}),{...h,id:i.id,carry:appendDigest(n,digestLine(i,h))}}const m=e=>`queue-${e}`;return{runTask:u,runOne:d,proceed:c,reconcile:async function({cwd:e=process.cwd(),auto:o=!1,commit:n,max:r=0,stopOnError:s=!1}={}){const a=queue.reconcilePlan(e,{write:!0});if(!a.ok)return{ok:!1,error:a.reason};if(a.healed&&a.healed.changed&&i({type:"healed",phases:a.healed.added}),null==a.next)return{ok:!0,exhausted:!0};const u=`Work Phase ${a.next} from PLAN.md`,l=queue.loadQueue(t).find((t=>t.cwd===e&&String(t.task).startsWith(u)&&"done"!==t.status));if(l){if(i({type:"already-queued",phase:a.next,id:l.id,status:l.status}),!o)return{ok:!0,phase:a.next,id:l.id,existing:!0}}else{const o=queue.addTask(t,{task:`${u} ("${a.title}") at ${e}. Read the full "## Phase ${a.next}" section in PLAN.md at the repo root for the spec, exit criteria and constraints, and implement it exactly as scoped there. Keep the repo's checks green (\`npm run check\`, plus that package's tests). When every exit criterion is met, mark the "## Phase ${a.next}" heading with ✅ in PLAN.md and update its line in the top Status checklist.`,cwd:e,source:"reconcile",model:resolveModel({env:t})});i({type:"queued",phase:a.next,id:o.id,title:a.title})}if(!o)return{ok:!0,phase:a.next,title:a.title};const d=await c({commit:n,max:r,stopOnError:s});return{ok:!0,phase:a.next,title:a.title,...d}},cancel:function(t){if(null==t)return{ok:!1,error:"cancel needs a task id"};if("function"!=typeof e.cancel)return{ok:!1,error:"this engine cannot cancel a turn"};const o=e.cancel(m(t));return{ok:Boolean(o&&o.ok),sessionId:m(t)}},sessionIdFor:m,resolveModel:e=>resolveModel({...e,env:t})}}function commitMessage(e){const t=String(e.task||"queued task").split("\n")[0].replace(/\s+/g," ").trim();return`autonomous: ${t.slice(0,66)}${t.length>66?"…":""}`}module.exports={DEFAULT_MODEL:DEFAULT_MODEL,DEFAULT_ROUNDS:DEFAULT_ROUNDS,MAX_ROUND_STOPS:3,MODEL_CLASSES:MODEL_CLASSES,AEGIS_MODEL_IDS:AEGIS_MODEL_IDS,isAegisModel:isAegisModel,normalizeClass:normalizeClass,looksLikeByokModel:looksLikeByokModel,modelRefusal:modelRefusal,WRITE_TOOLS:WRITE_TOOLS,writtenPath:writtenPath,isAutonomousRequest:isAutonomousRequest,maxRounds:maxRounds,withRoundHorizon:withRoundHorizon,DEFAULT_AUTO_CONTINUES:3,autoContinueLimit:autoContinueLimit,autoRoundsDefault:autoRoundsDefault,autoContinuePlan:autoContinuePlan,resolveModel:resolveModel,ignoredEnvModel:ignoredEnvModel,resolveEffort:resolveEffort,resolveFanout:resolveFanout,autonomousDirective:autonomousDirective,taskPrompt:taskPrompt,appendDigest:appendDigest,digestLine:digestLine,assistantText:assistantText,errorText:errorText,commitMessage:commitMessage,createQueueWorker:createQueueWorker};
|
|
3
|
+
"use strict";const queue=require("./queue.js"),gitScope=require("./git-scope.js"),DEFAULT_ROUNDS=40,MAX_ROUND_STOPS=3,WRITE_TOOLS=new Set(["writeFile","editFile"]),DEFAULT_AUTO_CONTINUES=3;function autoContinueLimit(e=process.env){const t=Number.parseInt(e&&e.AEGIS_AUTO_CONTINUE_MAX,10);return Number.isFinite(t)&&t>0?t:3}const AUTO_ROUNDS_OFF=new Set(["0","false","off","no"]);function autoRoundsDefault(e=process.env){const t=e&&e.AEGIS_AUTO_ROUNDS;if(null==t)return!0;const o=String(t).trim().toLowerCase();return!o||!AUTO_ROUNDS_OFF.has(o)}function autoContinuePlan({on:e=!1,used:t=0,limit:o=3}={}){const n=Number.isFinite(o)&&o>0?Math.floor(o):3,r=Number.isFinite(t)&&t>0?Math.floor(t):0;return e?r>=n?{auto:!1,used:0,cap:n}:{auto:!0,used:r+1,cap:n}:{auto:!1,used:r,cap:n}}function writtenPath(e){const t=e&&e.args||{},o=t.file_path||t.path;return o?String(o):""}const DEFAULT_MODEL="nexus-brain",MODEL_CLASSES=Object.freeze(["aegis","byok","local","pro"]),AEGIS_MODEL_RE=/^(?:nexus|aegis)-brain(?:-(?:smart|neo))?$/,AEGIS_MODEL_IDS=Object.freeze(["nexus-brain","aegis-brain"]);function isAegisModel(e){return AEGIS_MODEL_RE.test(String(null==e?"":e).trim())}function normalizeClass(e){return String(null==e?"":e).trim().toLowerCase()||"aegis"}function looksLikeByokModel(e){const t=String(null==e?"":e).trim(),o=t.indexOf(":");return o>0&&o<t.length-1}function modelRefusal(e,t){const o=String(null==e?"":e).trim(),n=normalizeClass(t);if(!MODEL_CLASSES.includes(n))return`"${t}" is not a model class the queue serves (${MODEL_CLASSES.join("/")})`;if("aegis"===n)return!o||isAegisModel(o)?"":`the autonomous queue's Aegis Cloud class runs pooled-brain models only (nexus-brain, ${AEGIS_MODEL_IDS.join("/")} aliases); "${o}" is not one`;if("byok"===n)return o?looksLikeByokModel(o)?"":`"${o}" is not a byok model id — it must be "<provider>:<model>" (pick one from /models)`:'a byok task needs a model, as "<provider>:<model>" (pick one from /models)';if("pro"===n){if(!o)return"";let e;try{e=require("./claude-pro.js").PRO_MODELS}catch{return"a pro task's model cannot be checked right now — queue it with no --model to let the claude CLI pick"}const t=(Array.isArray(e)?e:[]).map(e=>String(e&&e.id).trim());return t.includes(o.toLowerCase())?"":`the autonomous queue's Pro class runs the subscription through the claude CLI, which accepts only its own model aliases (${t.join("/")}); "${o}" is not one`}return o?"":"a local task needs a model — the tag of whatever is pulled into the local daemon"}const AUTONOMOUS_REQUEST_RE=/\bautonomously\b|\bon your own\b|\bwithout asking\b|\bend[- ]to[- ]end\b|\bno (?:more )?questions\b|\bfully autonomous\b|\bqueue it\b/i;function isAutonomousRequest(e){return AUTONOMOUS_REQUEST_RE.test(String(e||""))}function maxRounds(e=process.env,t){const o=Number.parseInt(t,10);if(Number.isFinite(o)&&o>0)return o;const n=Number.parseInt(e&&e.AEGIS_AUTONOMOUS_MAX_ROUNDS||"",10);return Number.isFinite(n)&&n>0?n:40}function withRoundHorizon(e,t,o){const n="AEGIS_AUTONOMOUS_MAX_ROUNDS",r=[];for(const e of[t,process.env])e&&-1===r.indexOf(e)&&r.push(e);const s=r.map(e=>({target:e,had:Object.prototype.hasOwnProperty.call(e,n),prev:e[n]}));try{for(const t of r)t[n]=String(e)}catch{}const i=()=>{for(const e of s)try{e.had?e.target[n]=e.prev:delete e.target[n]}catch{}};let a;try{a=o()}catch(e){throw i(),e}return a&&"function"==typeof a.then?a.then(e=>(i(),e),e=>{throw i(),e}):(i(),a)}function resolveModel({model:e,env:t,cls:o}={}){const n=String(e||"").trim();if("aegis"!==normalizeClass(o))return n;if(n)return n;const r=t||process.env,s=String(r.AEGIS_AUTONOMOUS_MODEL||r.AEGIS_MODEL||"").trim();return isAegisModel(s)?s:"nexus-brain"}function ignoredEnvModel({model:e,env:t,cls:o}={}){if("aegis"!==normalizeClass(o))return"";if(String(e||"").trim())return"";const n=t||process.env,r=String(n.AEGIS_AUTONOMOUS_MODEL||n.AEGIS_MODEL||"").trim();return!r||isAegisModel(r)?"":`${String(n.AEGIS_AUTONOMOUS_MODEL||"").trim()?"AEGIS_AUTONOMOUS_MODEL":"AEGIS_MODEL"}="${r}" is not an Aegis Cloud model — running on nexus-brain instead`}function resolveFanout(e={},t=process.env){const o=e||{};if(!0===o.autonomous||!1===o.singlePass)return!0;const n=t||process.env;return/^(1|true|yes|on)$/i.test(String(n.AEGIS_AUTONOMOUS_FANOUT||"").trim())}function resolveEffort({effort:e,env:t,fanout:o}={}){const n=t||process.env;return String(e||n.AEGIS_AUTONOMOUS_EFFORT||"").trim()||(o?"high":"medium")}function autonomousDirective(e=40){return["# Autonomous mode",`You are running autonomously, not in a conversation: there is no user to answer a question or approve a plan. You have up to ${e} tool rounds this turn; use as many as the task needs.`,"Work the task end to end:","1. Plan in one line, then start acting in the same turn — never end a turn on a plan.","2. Read only what you need to make the change (no fishing through the repo).","2b. If this demand has been made before, establish whether it was met: check recalled memory, the queue file, PLAN.md, and git history for the earlier attempt. When it was fixed and the problem is back, state how it was fixed then and why it regressed, and fix that cause — a blind re-fix is a regression, not a resolution.","3. Make the change with Write/Edit/Bash, then VERIFY it: re-read the result and run the relevant test/command.","4. If verification fails, fix it and verify again — loop until it passes or you are genuinely blocked.",'5. Do not ask for permission, do not hand the work back, do not stop at "let me check…".',"6. Finish with a short report: what changed (file paths), the command you ran to verify, its result, and any remaining blocker."].join("\n")}function digestLine(e,t){const o=String(e.task||"").replace(/\s+/g," ").trim().slice(0,120),n=Boolean(t&&t.ok&&t.stoppedOnRounds)?"⏸":t&&t.ok?"✓":"✗",r=t&&Array.isArray(t.files)&&t.files.slice(0,6)||[],s=r.length?` — touched: ${r.join(", ")}${t.files.length>r.length?", …":""}`:"",i=!t||t.ok?"":` — ${String(t&&t.error||"failed").slice(0,120)}`;return`- #${e.id} ${n} ${o}${s}${i}`}function appendDigest(e,t,{keep:o=6}={}){return String(e||"").split("\n").filter(Boolean).concat(t).slice(-o).join("\n")}function taskPrompt(e,{carry:t="",rounds:o=40}={}){const n=[autonomousDirective(o)];return t&&n.push("# Earlier tasks in this run\nWork already done by this queue — do not redo it, build on it:\n"+t),n.push("# Task\n"+String(e.task||"").trim()),n.join("\n\n")}function assistantText(e){if(!e||"object"!=typeof e)return"";const t=Array.isArray(e.choices)?e.choices[0]:null,o=t&&t.message?t.message.content:e.content;return"string"==typeof o?o:Array.isArray(o)?o.map(e=>"string"==typeof e?e:e&&"string"==typeof e.text?e.text:"").join(""):""}function errorText(e){return e?"string"==typeof e?e:String(e.message||e.error||e):"unknown error"}function createQueueWorker({engine:e,env:t=process.env,log:o=()=>{},git:n=gitScope,now:r=Date.now,canFanOut:s=()=>!0}={}){if(!e||"function"!=typeof e.chat)throw new Error("autonomous: a local engine with chat() is required");const i=e=>{try{o(e)}catch{}};async function a(o,{carry:a="",commit:l}={}){const c=o.cwd||process.cwd(),m=normalizeClass(o.class),h=modelRefusal(o.model,m);if(h){const e={ok:!1,error:h,model:o.model,class:m,ms:0};return i({type:"finish",taskId:o.id,ok:!1,result:e}),e}const p=resolveModel({model:o.model,env:t,cls:m}),f=ignoredEnvModel({model:o.model,env:t,cls:m});f&&i({type:"note",taskId:o.id,note:f});const g="aegis"===m&&resolveFanout(o,t),k=g&&(()=>{try{return!1!==s()}catch{return!1}})();g&&!k&&i({type:"note",taskId:o.id,note:"fan-out needs Pro (the cloud drain that keeps running after you close the laptop) — this task ran as a single pass"});const S=resolveEffort({effort:o.effort,env:t,fanout:k}),O=maxRounds(t,o.maxRounds);let y=null,E=0;const A=new Set,v=e=>{if(e&&"object"==typeof e)if(e.approval)y=e.approval;else if(e.tool){if("done"===e.tool.phase&&(E+=1,WRITE_TOOLS.has(e.tool.name)&&!1!==e.tool.ok)){const t=writtenPath(e.tool);t&&A.add(t)}i({type:"tool",taskId:o.id,tool:e.tool})}else"string"==typeof e.delta?i({type:"delta",taskId:o.id,text:e.delta}):"string"==typeof e.reasoning&&i({type:"reasoning",taskId:o.id,text:e.reasoning})},_=void 0===l?Boolean(o.commit):Boolean(l),w=_?u(()=>n.gitStatusSnapshot(c),null):null;i({type:"start",taskId:o.id,model:p,class:m,cwd:c,rounds:O,fanout:k,effort:S});const M=r();let b;try{const n=await withRoundHorizon(O,t,()=>e.chat({class:m,model:p,prompt:taskPrompt(o,{carry:a,rounds:O}),autonomous:k,singlePass:!k,effort:S,workers:k&&o.workers||void 0,env:{cwd:c},maxRounds:O,sessionId:d(o.id),stream:!0},v));b={ok:!0,output:assistantText(n),usage:n&&n.usage||null,stoppedOnRounds:Boolean(n&&n.stoppedOnRounds),rounds:E||void 0},y&&(b.ok=!1,b.error=`tool approval was requested for "${y.tool||y.name||"a tool"}" with no one to answer it — construct the queue engine with approvals disabled (getConfirmMode: () => false)`)}catch(e){b={ok:!1,error:errorText(e)}}return b.ms=Math.max(0,r()-M),_&&(b.commit=u(()=>n.scopedCommit(c,{message:commitMessage(o),before:w,written:[...A]}),{ok:!1,error:"git-scope unavailable"}),b.files=function(e,t){return!e||e.error?[]:Array.isArray(e.paths)?e.paths:[...t]}(b.commit,A)),i({type:"finish",taskId:o.id,ok:b.ok,result:b}),b}function u(e,t){try{return e()}catch{return t}}async function l({commit:e,max:o=0,stopOnError:n=!1,carry:r=""}={}){const s=queue.acquireLock(t);if(!s.ok)return i({type:"locked",holder:s.holder}),{ok:!1,locked:!0,holder:s.holder,ran:[],carry:r};let a=null;try{a=setInterval(()=>queue.heartbeatLock(t),queue.LOCK_BEAT_MS),"function"==typeof a.unref&&a.unref()}catch{a=null}s.stoleFrom&&i({type:"reclaimed",holder:s.stoleFrom});const u=[];try{for(;!(o>0&&u.length>=o);){const o=queue.loadQueue(t),s=queue.recoverStale(o);s.length&&(queue.saveQueue(t,o),i({type:"recovered",ids:s}));const a=queue.pending(o)[0];if(!a)break;const l=await c(a,{commit:e,carry:r});if(r=l.carry,u.push(l),!l.ok&&n)break}}finally{a&&clearInterval(a),queue.releaseLock(t)}return{ok:!0,ran:u,carry:r}}async function c(e,{commit:o,carry:n=""}={}){const s=queue.loadQueue(t),i=queue.markRunning(s,e.id,{now:r()});if(!i)return{ok:!1,error:`unknown task #${e.id}`,carry:n};const u=Number(i.roundStops)||0;queue.saveQueue(t,s);const l=await a(i,{carry:n,commit:o}),c=Boolean(l.ok&&l.stoppedOnRounds),d=c?u+1:0,m=c&&d>3,h=m?{...l,ok:!1,error:`stopped at its tool-round horizon ${d} times in a row without finishing — raise AEGIS_AUTONOMOUS_MAX_ROUNDS or split the task into smaller ones`}:l,p=m?"error":c?"pending":h.ok?"done":"error",f=queue.loadQueue(t);queue.settle(f,i.id,{status:p,result:{ok:h.ok,output:h.output||"",usage:h.usage||null,ms:h.ms,commit:h.commit||null,files:h.files||[]},error:h.ok?null:h.error,now:r()});const g=queue.findTask(f,i.id);return g&&(g.roundStops=d),queue.saveQueue(t,f),queue.appendRun(t,{id:i.id,task:i.task,cwd:i.cwd,model:resolveModel({model:i.model,env:t}),status:"pending"===p?"stopped":p,at:new Date(r()).toISOString(),ms:h.ms,usage:h.usage||null,files:h.files||[],error:h.ok?null:h.error}),{...h,id:i.id,carry:appendDigest(n,digestLine(i,h))}}const d=e=>`queue-${e}`;return{runTask:a,runOne:c,proceed:l,reconcile:async function({cwd:e=process.cwd(),auto:o=!1,commit:n,max:r=0,stopOnError:s=!1}={}){const a=queue.reconcilePlan(e,{write:!0});if(!a.ok)return{ok:!1,error:a.reason};if(a.healed&&a.healed.changed&&i({type:"healed",phases:a.healed.added}),null==a.next)return{ok:!0,exhausted:!0};const u=`Work Phase ${a.next} from PLAN.md`,c=queue.loadQueue(t).find(t=>t.cwd===e&&String(t.task).startsWith(u)&&"done"!==t.status);if(c){if(i({type:"already-queued",phase:a.next,id:c.id,status:c.status}),!o)return{ok:!0,phase:a.next,id:c.id,existing:!0}}else{const o=queue.addTask(t,{task:`${u} ("${a.title}") at ${e}. Read the full "## Phase ${a.next}" section in PLAN.md at the repo root for the spec, exit criteria and constraints, and implement it exactly as scoped there. Keep the repo's checks green (\`npm run check\`, plus that package's tests). When every exit criterion is met, mark the "## Phase ${a.next}" heading with ✅ in PLAN.md and update its line in the top Status checklist.`,cwd:e,source:"reconcile",model:resolveModel({env:t})});i({type:"queued",phase:a.next,id:o.id,title:a.title})}if(!o)return{ok:!0,phase:a.next,title:a.title};const d=await l({commit:n,max:r,stopOnError:s});return{ok:!0,phase:a.next,title:a.title,...d}},cancel:function(t){if(null==t)return{ok:!1,error:"cancel needs a task id"};if("function"!=typeof e.cancel)return{ok:!1,error:"this engine cannot cancel a turn"};const o=e.cancel(d(t));return{ok:Boolean(o&&o.ok),sessionId:d(t)}},sessionIdFor:d,resolveModel:e=>resolveModel({...e,env:t})}}function commitMessage(e){const t=String(e.task||"queued task").split("\n")[0].replace(/\s+/g," ").trim();return`autonomous: ${t.slice(0,66)}${t.length>66?"…":""}`}module.exports={DEFAULT_MODEL:"nexus-brain",DEFAULT_ROUNDS:40,MAX_ROUND_STOPS:3,MODEL_CLASSES:MODEL_CLASSES,AEGIS_MODEL_IDS:AEGIS_MODEL_IDS,isAegisModel:isAegisModel,normalizeClass:normalizeClass,looksLikeByokModel:looksLikeByokModel,modelRefusal:modelRefusal,WRITE_TOOLS:WRITE_TOOLS,writtenPath:writtenPath,isAutonomousRequest:isAutonomousRequest,maxRounds:maxRounds,withRoundHorizon:withRoundHorizon,DEFAULT_AUTO_CONTINUES:3,autoContinueLimit:autoContinueLimit,autoRoundsDefault:autoRoundsDefault,autoContinuePlan:autoContinuePlan,resolveModel:resolveModel,ignoredEnvModel:ignoredEnvModel,resolveEffort:resolveEffort,resolveFanout:resolveFanout,autonomousDirective:autonomousDirective,taskPrompt:taskPrompt,appendDigest:appendDigest,digestLine:digestLine,assistantText:assistantText,errorText:errorText,commitMessage:commitMessage,createQueueWorker:createQueueWorker};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path");let envFileLib=null;try{envFileLib=require("../../../client/env-file.js")}catch{try{envFileLib=require("../../vendor/env-file.js")}catch{envFileLib=null}}function claudeConfigDir(e){const n=e||process.env,t=n&&n.CLAUDE_CONFIG_DIR;return t&&String(t).trim()?String(t).trim():path.join(os.homedir(),".claude")}function claudeOAuthToken(e){return envFileLib?envFileLib.resolveForeignSecret("CLAUDE_CODE_OAUTH_TOKEN",{env:e}):""}const SHADOWING_ENV_VARS=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN"]);function isAnthropicConsoleKey(e){return"string"==typeof e&&/^sk-ant-[A-Za-z0-9_-]{8,}$/.test(e.trim())}function childEnvPlan(e,n,t){const s={...e||{}},o=[],i=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null,r=!(!t||!t.hasSubscription);if(i)for(const e of SHADOWING_ENV_VARS){const n=s[e];if("string"!=typeof n)continue;let t=null;if(i(n)?r&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(t="not-a-console-key"):t="too-short",!t)continue;delete s[e];const a=n.trim().length;a>0&&o.push({name:e,length:a,reason:t})}return n&&(s.CLAUDE_CODE_OAUTH_TOKEN=n),{env:s,dropped:o}}function envDroppedLine(e){const n=Array.isArray(e)?e:[];if(!n.length)return null;const t=n.filter((e=>e&&"not-a-console-key"===e.reason)),s=n.filter((e=>!e||"not-a-console-key"!==e.reason)),o=[];if(s.length){const e=s.map((e=>`${e.name} (${e.length} character${1===e.length?"":"s"})`)).join(", ");o.push(`${e}: too short to be a credential, and the CLI would have spent it instead of your subscription`)}if(t.length){const e=t.map((e=>`${e.name} (${e.length} characters)`)).join(", ");o.push(`${e}: not an Anthropic console key (\`sk-ant-\`), and the CLI would have spent it instead of your subscription`)}return`aegis: not passed to the claude child — ${o.join("; ")}`}function shadowingValue(e,n){const t=e||{},s=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null;if(!s)return null;const o=!(!n||!n.hasSubscription);for(const e of SHADOWING_ENV_VARS){const n=t[e];if("string"!=typeof n)continue;let i=null;if(s(n)?o&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(i="not-a-console-key"):i="too-short",i)return{name:e,length:n.trim().length,reason:i}}return null}function claudeProStatus(e){const n=e||{},t=n.env||process.env,s=path.join(n.dir||claudeConfigDir(t),".credentials.json"),o={claude:n.claudeVersion||null,file:s,exists:!1,kind:null,subscription:null,expiresAt:0,loggedIn:!1};let i;try{i=JSON.parse(fs.readFileSync(s,"utf8")),o.exists=!0}catch{i=null}const r=i&&i.claudeAiOauth;r&&(r.accessToken||r.refreshToken)?(o.kind="oauth",o.subscription=r.subscriptionType||null,o.expiresAt=Number(r.refreshTokenExpiresAt)||0,o.loggedIn=!0):i&&"string"==typeof i.token&&i.token?(o.kind="apikey",o.loggedIn=!0):claudeOAuthToken(t)&&(o.kind="env-token",o.loggedIn=!0),o.subscriptionPresent=o.loggedIn&&"apikey"!==o.kind,o.shadowed=shadowingValue(t,{hasSubscription:o.subscriptionPresent});const a=childEnvPlan(t,null,{hasSubscription:o.subscriptionPresent});return o.credentialPresent=o.loggedIn||"string"==typeof a.env.ANTHROPIC_API_KEY||"string"==typeof a.env.ANTHROPIC_AUTH_TOKEN||"string"==typeof a.env.CLAUDE_CODE_OAUTH_TOKEN,o}const PRO_MODELS=Object.freeze([{id:"default",label:"Default (recommended)",note:"the CLI picks for the subscription"},{id:"sonnet",label:"Sonnet",note:"alias the CLI resolves · latest Sonnet"},{id:"opus",label:"Opus",note:"alias the CLI resolves · latest Opus"},{id:"opusplan",label:"Opus Plan",note:"alias the CLI resolves · plan with Opus, act on Sonnet"},{id:"haiku",label:"Haiku",note:"alias the CLI resolves · latest Haiku"},{id:"fable",label:"Fable",note:"alias the CLI resolves · needs usage credits"},{id:"claude-sonnet-5-5",label:"Claude Sonnet 5.5",note:"full name · Anthropic"},{id:"claude-sonnet-4-6",label:"Claude Sonnet 4.6",note:"full name · Anthropic"},{id:"claude-sonnet-4-5-20250929",label:"Claude Sonnet 4.5",note:"full name · Anthropic · dated snapshot"},{id:"claude-opus-5",label:"Claude Opus 5",note:"full name · Anthropic"},{id:"claude-opus-4-7",label:"Claude Opus 4.7",note:"full name · Anthropic"},{id:"claude-opus-4-6",label:"Claude Opus 4.6",note:"full name · Anthropic"},{id:"claude-opus-4-5-20251101",label:"Claude Opus 4.5",note:"full name · Anthropic · dated snapshot"}]);function turnArgs(e){const n=[],t=e||{};return t.system&&String(t.system).trim()&&n.push("--append-system-prompt",String(t.system)),n}function createStreamParser(e){const n=e||{},t=new Map;let s="",o="",i=0,r=null;const a=e=>[...t.values()].find((n=>"collecting"===n.phase&&n.index===e))||[...t.values()].find((e=>"collecting"===e.phase));return{line(e){let l;try{l=JSON.parse(e)}catch{return}if("control_request"===l.type&&l.request){const e=l.request;if("can_use_tool"!==e.subtype)return;return n.onAsk?void n.onAsk({requestId:l.request_id,toolName:e.tool_name,input:e.input||{},toolUseId:e.tool_use_id,displayName:e.display_name,description:e.description,suggestions:Array.isArray(e.permission_suggestions)?e.permission_suggestions:[]}):void(n.onAskUnavailable&&n.onAskUnavailable({requestId:l.request_id,request:e}))}if("stream_event"===l.type&&l.event){const e=l.event;if("content_block_start"===e.type&&e.content_block)"tool_use"===e.content_block.type&&t.set(e.content_block.id,{id:e.content_block.id,index:null==e.index?0:e.index,name:e.content_block.name,args:"",startedAt:Date.now(),phase:"collecting"});else if("content_block_delta"===e.type&&e.delta){if("text_delta"===e.delta.type){const t=(e.delta.text||"").replace(/\x00/g,"");s+=t,n.onText&&t&&n.onText(t)}else if("thinking_delta"===e.delta.type){const t=(e.delta.thinking||"").replace(/\x00/g,"");o+=t,n.onThinking&&t&&n.onThinking(t);const s=e.delta.estimated_tokens;"number"==typeof s&&s>0&&Number.isFinite(s)&&(i+=s,n.onThinkingProgress&&n.onThinkingProgress(s))}else if("input_json_delta"===e.delta.type){const n=a(null==e.index?0:e.index);n&&(n.args+=e.delta.partial_json||"")}}else if("content_block_stop"===e.type){const s=a(null==e.index?0:e.index);s&&(e=>{let s=e.args;try{s=e.args?JSON.parse(e.args):{}}catch{s={}}t.set(e.id,{...e,args:s,phase:"run"}),n.onTool&&n.onTool({id:e.id,name:e.name,args:s,phase:"run"})})(s)}}else if("user"===l.type&&l.message){const e=Array.isArray(l.message.content)?l.message.content:[];for(const s of e){if(!s||"tool_result"!==s.type||!s.tool_use_id)continue;const e=t.get(s.tool_use_id);if(!e)continue;const o=Math.max(0,Date.now()-(e.startedAt||Date.now()));n.onTool&&n.onTool({id:e.id,name:e.name,phase:"done",elapsed:o,error:!!s.is_error}),t.delete(s.tool_use_id)}}else"result"===l.type&&(r=l,n.onDone&&n.onDone({text:s||l.result||"",error:l.is_error?l.result||(Array.isArray(l.errors)?l.errors.find((e=>"string"==typeof e&&e.trim())):void 0)||"api error":void 0,usage:l.usage||null,costUsd:"number"==typeof l.total_cost_usd?l.total_cost_usd:void 0,durationMs:l.duration_ms,sessionId:l.session_id,thinking:o||"",thinkingTokens:i}))},get text(){return s},get thinking(){return o},get thinkingTokens(){return i},get resultLine(){return r}}}function loadSeam(e){const n=e||__dirname,t=[path.join(n,"..","..","..","one","src"),path.join(n,"..","..","vendor","one","src"),path.join(n,"..","..","..","..","one","src")],s=new Set(["aegisone","aegiscode"]),o=path.join(n,"..","..","..","..");try{const e=JSON.parse(fs.readFileSync(path.join(o,"package.json"),"utf8"));e&&s.has(e.name)&&t.push(path.join(o,"src"))}catch{}for(const e of t)try{const n=require(path.join(e,"child.js")),t=require(path.join(e,"permissions.js"));if("function"==typeof n.claudeArgv&&"function"==typeof t.resolvePosture)return{child:n,permissions:t}}catch{}throw new Error("aegis: the Claude child argv builder (one/src/child.js + one/src/permissions.js) is missing from this install — refusing to build a second argv, because a second argv is a second policy.")}function seamAvailable(e){try{return loadSeam(e),{ok:!0,error:null}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}}function proMessage(e,n,t){const s={content:e||""},o="string"==typeof n?n:"";return o&&(s.reasoning_content=o),"number"==typeof t&&t>0&&Number.isFinite(t)&&(s.thinking_tokens=t),s}function runClaudePro(e,n){const t=e||{},s=n||{},o=s.seam||loadSeam(s.dir),i=s.spawn||require("node:child_process").spawn;let r=void 0===t.permissionMode||null===t.permissionMode?null:String(t.permissionMode);if(null===r)try{const e=o.permissions.storedPermissionFacts();r=e&&"string"==typeof e.permissionMode?e.permissionMode:null}catch{}const a=o.permissions.resolvePosture({rules:t.rules,gate:t.gate,interactive:!1,childKind:o.permissions.CHILD_KINDS.HEADLESS,permissionMode:r,env:t.env||process.env}),l=o.child.claudeArgv({posture:a,prompt:t.prompt,model:t.model||void 0,resumeSessionId:t.resumeSessionId,sessionId:t.sessionId,addDir:t.addDir,askBridge:"function"==typeof t.onAsk,extra:[...turnArgs(t),"--include-partial-messages","--verbose"]});return new Promise((e=>{if(t.signal&&t.signal.aborted)return void e({choices:[{message:{content:""},finish_reason:"stop"}],stopped:!0});const n=t.env||process.env,o=claudeOAuthToken(n);let r=!1;try{r=!!claudeProStatus({env:n}).subscriptionPresent}catch{}const a=childEnvPlan(n,o,{hasSubscription:r}),c=a.env,d=envDroppedLine(a.dropped);if(d&&t.onDelta)try{t.onDelta({delta:"",note:d})}catch{}let u;try{u=i(s.executable||"claude",l.argv,{cwd:t.cwd||process.cwd(),stdio:[l.record.askBridge?"pipe":"ignore","pipe","pipe"],env:c})}catch(n){return void e({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not start the child (${n&&n.message||n})`,...a.dropped.length?{envDropped:a.dropped}:{}})}if(t.onSpawn)try{t.onSpawn(u,l.record)}catch{}let p=!1,h="",g="",m=null;const f=Number(t.idleTimeoutMs)||6e5,_=l.record.askBridge,v=e=>{if(!_||!u.stdin||u.stdin.destroyed)return!1;try{return u.stdin.write(`${JSON.stringify(e)}\n`),!0}catch{return!1}};_&&v({type:"user",message:{role:"user",content:[{type:"text",text:String(t.prompt||"")}]}});const y=(e,n,t)=>{v({type:"control_response",response:{subtype:"success",request_id:e,response:"session"===n||"once"===n||"always"===n?{behavior:"allow"}:{behavior:"deny",message:t||"AEGIS_USER_DENIED"}}})},k=n=>{if(!p){if(p=!0,m&&clearTimeout(m),t.signal&&t.signal.removeEventListener("abort",A),_&&u.stdin&&!u.stdin.destroyed)try{u.stdin.end()}catch{}e(a.dropped.length?{...n,envDropped:a.dropped}:n)}},A=()=>{try{u.kill("SIGTERM")}catch{}setTimeout((()=>{try{u.kill("SIGKILL")}catch{}}),1500)};t.signal&&t.signal.addEventListener("abort",A,{once:!0});const b=()=>{m&&clearTimeout(m),m=setTimeout((()=>{A(),k({choices:[{message:{content:""},finish_reason:"stop"}],error:`claude: the child went silent for ${Math.round(f/1e3)}s and was stopped`})}),f)};b();const S=createStreamParser({onText:e=>{b(),t.onDelta&&t.onDelta({delta:e})},onThinking:e=>{b(),t.onDelta&&t.onDelta({reasoning:e})},onThinkingProgress:e=>{b(),t.onDelta&&t.onDelta({thinkingTokens:e})},onTool:e=>{b(),t.onDelta&&t.onDelta({delta:"",tool:{name:e.name,args:e.args,ok:"done"===e.phase?!e.error:void 0,id:e.id,cwd:t.cwd,phase:e.phase}})},onAsk:e=>{b(),Promise.resolve().then((()=>t.onAsk(e))).then((n=>y(e.requestId,"session"===n||"once"===n||"always"===n?n:"deny","AEGIS_USER_DENIED")),(n=>{y(e.requestId,"deny",`AEGIS_USER_DENIED (${n&&n.message||String(n)})`)})).catch((()=>{}))},onAskUnavailable:e=>{y(e.requestId,"deny","AEGIS_NO_APPROVAL_CHANNEL")},onDone:e=>{e.error?k({choices:[{message:{content:e.text||""},finish_reason:"error"}],usage:e.usage||void 0,error:e.error,...l.record.resumeSessionId&&isStaleResumeError(e.error)?{resumeStale:!0,resumeSessionId:l.record.resumeSessionId}:{}}):k({choices:[{message:proMessage(e.text||"",e.thinking,e.thinkingTokens),finish_reason:"stop"}],usage:e.usage||void 0,costUsd:e.costUsd,durationMs:e.durationMs,sessionId:e.sessionId,childRecord:l.record})}});u.stdout.on("data",(e=>{b(),g+=e.toString("utf8");const n=g.split("\n");g=n.pop()||"";for(const e of n){const n=e.trim();n&&S.line(n)}})),_&&u.stdin&&u.stdin.on("error",(()=>{})),u.stderr.on("data",(e=>{b(),h.length<8192&&(h+=e.toString("utf8"))})),u.on("error",(e=>{k({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not run the child (${e&&e.message||e}). Install it with \`npm i -g @anthropic-ai/claude-code\`, then sign in with \`claude auth login\`.`})})),u.on("close",(e=>{g.trim()&&S.line(g.trim()),k({choices:[{message:proMessage(S.text,S.thinking,S.thinkingTokens),finish_reason:"stop"}],usage:S.resultLine&&S.resultLine.usage||void 0,childRecord:l.record,error:S.text||0===e?void 0:`claude: the child exited with status ${e}${h.trim()?` — ${h.trim().split("\n").slice(-3).join(" ")}`:""}`})}))}))}function isStaleResumeError(e){return!!e&&/no conversation found with session id/i.test(String(e))}function childLine(e,n){if(!e)return"";try{return loadSeam(n).child.childRecordLine(e)}catch{const n=e.skipFlag||"no permission flag";return`aegis: claude child [${e.kind}] ${n}`}}module.exports={claudeConfigDir:claudeConfigDir,claudeOAuthToken:claudeOAuthToken,claudeProStatus:claudeProStatus,childEnvPlan:childEnvPlan,envDroppedLine:envDroppedLine,shadowingValue:shadowingValue,SHADOWING_ENV_VARS:SHADOWING_ENV_VARS,PRO_MODELS:PRO_MODELS,turnArgs:turnArgs,createStreamParser:createStreamParser,loadSeam:loadSeam,seamAvailable:seamAvailable,childLine:childLine,isStaleResumeError:isStaleResumeError,runClaudePro:runClaudePro};
|
|
3
|
+
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path");let envFileLib=null;try{envFileLib=require("../../../client/env-file.js")}catch{try{envFileLib=require("../../vendor/env-file.js")}catch{envFileLib=null}}function claudeConfigDir(e){const n=e||process.env,t=n&&n.CLAUDE_CONFIG_DIR;return t&&String(t).trim()?String(t).trim():path.join(os.homedir(),".claude")}function claudeOAuthToken(e){return envFileLib?envFileLib.resolveForeignSecret("CLAUDE_CODE_OAUTH_TOKEN",{env:e}):""}const SHADOWING_ENV_VARS=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN"]);function isAnthropicConsoleKey(e){return"string"==typeof e&&/^sk-ant-[A-Za-z0-9_-]{8,}$/.test(e.trim())}function childEnvPlan(e,n,t){const s={...e||{}},o=[],i=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null,r=!(!t||!t.hasSubscription);if(i)for(const e of SHADOWING_ENV_VARS){const n=s[e];if("string"!=typeof n)continue;let t=null;if(i(n)?r&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(t="not-a-console-key"):t="too-short",!t)continue;delete s[e];const a=n.trim().length;a>0&&o.push({name:e,length:a,reason:t})}return n&&(s.CLAUDE_CODE_OAUTH_TOKEN=n),{env:s,dropped:o}}function envDroppedLine(e){const n=Array.isArray(e)?e:[];if(!n.length)return null;const t=n.filter(e=>e&&"not-a-console-key"===e.reason),s=n.filter(e=>!e||"not-a-console-key"!==e.reason),o=[];if(s.length){const e=s.map(e=>`${e.name} (${e.length} character${1===e.length?"":"s"})`).join(", ");o.push(`${e}: too short to be a credential, and the CLI would have spent it instead of your subscription`)}if(t.length){const e=t.map(e=>`${e.name} (${e.length} characters)`).join(", ");o.push(`${e}: not an Anthropic console key (\`sk-ant-\`), and the CLI would have spent it instead of your subscription`)}return`aegis: not passed to the claude child — ${o.join("; ")}`}function shadowingValue(e,n){const t=e||{},s=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null;if(!s)return null;const o=!(!n||!n.hasSubscription);for(const e of SHADOWING_ENV_VARS){const n=t[e];if("string"!=typeof n)continue;let i=null;if(s(n)?o&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(i="not-a-console-key"):i="too-short",i)return{name:e,length:n.trim().length,reason:i}}return null}function claudeProStatus(e){const n=e||{},t=n.env||process.env,s=path.join(n.dir||claudeConfigDir(t),".credentials.json"),o={claude:n.claudeVersion||null,file:s,exists:!1,kind:null,subscription:null,expiresAt:0,loggedIn:!1};let i;try{i=JSON.parse(fs.readFileSync(s,"utf8")),o.exists=!0}catch{i=null}const r=i&&i.claudeAiOauth;r&&(r.accessToken||r.refreshToken)?(o.kind="oauth",o.subscription=r.subscriptionType||null,o.expiresAt=Number(r.refreshTokenExpiresAt)||0,o.loggedIn=!0):i&&"string"==typeof i.token&&i.token?(o.kind="apikey",o.loggedIn=!0):claudeOAuthToken(t)&&(o.kind="env-token",o.loggedIn=!0),o.subscriptionPresent=o.loggedIn&&"apikey"!==o.kind,o.shadowed=shadowingValue(t,{hasSubscription:o.subscriptionPresent});const a=childEnvPlan(t,null,{hasSubscription:o.subscriptionPresent});return o.credentialPresent=o.loggedIn||"string"==typeof a.env.ANTHROPIC_API_KEY||"string"==typeof a.env.ANTHROPIC_AUTH_TOKEN||"string"==typeof a.env.CLAUDE_CODE_OAUTH_TOKEN,o}const PRO_MODELS=Object.freeze([{id:"default",label:"Default (recommended)",note:"the CLI picks for the subscription"},{id:"sonnet",label:"Sonnet",note:"alias the CLI resolves · latest Sonnet"},{id:"opus",label:"Opus",note:"alias the CLI resolves · latest Opus"},{id:"opusplan",label:"Opus Plan",note:"alias the CLI resolves · plan with Opus, act on Sonnet"},{id:"haiku",label:"Haiku",note:"alias the CLI resolves · latest Haiku"},{id:"fable",label:"Fable",note:"alias the CLI resolves · needs usage credits"},{id:"claude-sonnet-5-5",label:"Claude Sonnet 5.5",note:"full name · Anthropic"},{id:"claude-sonnet-4-6",label:"Claude Sonnet 4.6",note:"full name · Anthropic"},{id:"claude-sonnet-4-5-20250929",label:"Claude Sonnet 4.5",note:"full name · Anthropic · dated snapshot"},{id:"claude-opus-5",label:"Claude Opus 5",note:"full name · Anthropic"},{id:"claude-opus-4-7",label:"Claude Opus 4.7",note:"full name · Anthropic"},{id:"claude-opus-4-6",label:"Claude Opus 4.6",note:"full name · Anthropic"},{id:"claude-opus-4-5-20251101",label:"Claude Opus 4.5",note:"full name · Anthropic · dated snapshot"}]);function turnArgs(e){const n=[],t=e||{};return t.system&&String(t.system).trim()&&n.push("--append-system-prompt",String(t.system)),n}function createStreamParser(e){const n=e||{},t=new Map;let s="",o="",i=0,r=null;const a=e=>[...t.values()].find(n=>"collecting"===n.phase&&n.index===e)||[...t.values()].find(e=>"collecting"===e.phase);return{line(e){let l;try{l=JSON.parse(e)}catch{return}if("control_request"===l.type&&l.request){const e=l.request;if("can_use_tool"!==e.subtype)return;return n.onAsk?void n.onAsk({requestId:l.request_id,toolName:e.tool_name,input:e.input||{},toolUseId:e.tool_use_id,displayName:e.display_name,description:e.description,suggestions:Array.isArray(e.permission_suggestions)?e.permission_suggestions:[]}):void(n.onAskUnavailable&&n.onAskUnavailable({requestId:l.request_id,request:e}))}if("stream_event"===l.type&&l.event){const e=l.event;if("content_block_start"===e.type&&e.content_block)"tool_use"===e.content_block.type&&t.set(e.content_block.id,{id:e.content_block.id,index:null==e.index?0:e.index,name:e.content_block.name,args:"",startedAt:Date.now(),phase:"collecting"});else if("content_block_delta"===e.type&&e.delta){if("text_delta"===e.delta.type){const t=(e.delta.text||"").replace(/\x00/g,"");s+=t,n.onText&&t&&n.onText(t)}else if("thinking_delta"===e.delta.type){const t=(e.delta.thinking||"").replace(/\x00/g,"");o+=t,n.onThinking&&t&&n.onThinking(t);const s=e.delta.estimated_tokens;"number"==typeof s&&s>0&&Number.isFinite(s)&&(i+=s,n.onThinkingProgress&&n.onThinkingProgress(s))}else if("input_json_delta"===e.delta.type){const n=a(null==e.index?0:e.index);n&&(n.args+=e.delta.partial_json||"")}}else if("content_block_stop"===e.type){const s=a(null==e.index?0:e.index);s&&(e=>{let s=e.args;try{s=e.args?JSON.parse(e.args):{}}catch{s={}}t.set(e.id,{...e,args:s,phase:"run"}),n.onTool&&n.onTool({id:e.id,name:e.name,args:s,phase:"run"})})(s)}}else if("user"===l.type&&l.message){const e=Array.isArray(l.message.content)?l.message.content:[];for(const s of e){if(!s||"tool_result"!==s.type||!s.tool_use_id)continue;const e=t.get(s.tool_use_id);if(!e)continue;const o=Math.max(0,Date.now()-(e.startedAt||Date.now()));n.onTool&&n.onTool({id:e.id,name:e.name,phase:"done",elapsed:o,error:!!s.is_error}),t.delete(s.tool_use_id)}}else"result"===l.type&&(r=l,n.onDone&&n.onDone({text:s||l.result||"",error:l.is_error?l.result||(Array.isArray(l.errors)?l.errors.find(e=>"string"==typeof e&&e.trim()):void 0)||"api error":void 0,usage:l.usage||null,costUsd:"number"==typeof l.total_cost_usd?l.total_cost_usd:void 0,durationMs:l.duration_ms,sessionId:l.session_id,thinking:o||"",thinkingTokens:i}))},get text(){return s},get thinking(){return o},get thinkingTokens(){return i},get resultLine(){return r}}}function loadSeam(e){const n=e||__dirname,t=[path.join(n,"..","..","..","one","src"),path.join(n,"..","..","vendor","one","src"),path.join(n,"..","..","..","..","one","src")],s=new Set(["aegisone","aegiscode"]),o=path.join(n,"..","..","..","..");try{const e=JSON.parse(fs.readFileSync(path.join(o,"package.json"),"utf8"));e&&s.has(e.name)&&t.push(path.join(o,"src"))}catch{}for(const e of t)try{const n=require(path.join(e,"child.js")),t=require(path.join(e,"permissions.js"));if("function"==typeof n.claudeArgv&&"function"==typeof t.resolvePosture)return{child:n,permissions:t}}catch{}throw new Error("aegis: the Claude child argv builder (one/src/child.js + one/src/permissions.js) is missing from this install — refusing to build a second argv, because a second argv is a second policy.")}function seamAvailable(e){try{return loadSeam(e),{ok:!0,error:null}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}}function proMessage(e,n,t){const s={content:e||""},o="string"==typeof n?n:"";return o&&(s.reasoning_content=o),"number"==typeof t&&t>0&&Number.isFinite(t)&&(s.thinking_tokens=t),s}function runClaudePro(e,n){const t=e||{},s=n||{},o=s.seam||loadSeam(s.dir),i=s.spawn||require("node:child_process").spawn;let r=void 0===t.permissionMode||null===t.permissionMode?null:String(t.permissionMode);if(null===r)try{const e=o.permissions.storedPermissionFacts();r=e&&"string"==typeof e.permissionMode?e.permissionMode:null}catch{}const a=o.permissions.resolvePosture({rules:t.rules,gate:t.gate,interactive:!1,childKind:o.permissions.CHILD_KINDS.HEADLESS,permissionMode:r,env:t.env||process.env}),l=o.child.claudeArgv({posture:a,prompt:t.prompt,model:t.model||void 0,resumeSessionId:t.resumeSessionId,sessionId:t.sessionId,addDir:t.addDir,askBridge:"function"==typeof t.onAsk,extra:[...turnArgs(t),"--include-partial-messages","--verbose"]});return new Promise(e=>{if(t.signal&&t.signal.aborted)return void e({choices:[{message:{content:""},finish_reason:"stop"}],stopped:!0});const n=t.env||process.env,o=claudeOAuthToken(n);let r=!1;try{r=!!claudeProStatus({env:n}).subscriptionPresent}catch{}const a=childEnvPlan(n,o,{hasSubscription:r}),c=a.env,d=envDroppedLine(a.dropped);if(d&&t.onDelta)try{t.onDelta({delta:"",note:d})}catch{}let u;try{u=i(s.executable||"claude",l.argv,{cwd:t.cwd||process.cwd(),stdio:[l.record.askBridge?"pipe":"ignore","pipe","pipe"],env:c})}catch(n){return void e({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not start the child (${n&&n.message||n})`,...a.dropped.length?{envDropped:a.dropped}:{}})}if(t.onSpawn)try{t.onSpawn(u,l.record)}catch{}let p=!1,h="",g="",m=null;const f=Number(t.idleTimeoutMs)||6e5,_=l.record.askBridge,v=e=>{if(!_||!u.stdin||u.stdin.destroyed)return!1;try{return u.stdin.write(`${JSON.stringify(e)}\n`),!0}catch{return!1}};_&&v({type:"user",message:{role:"user",content:[{type:"text",text:String(t.prompt||"")}]}});const y=(e,n,t)=>{v({type:"control_response",response:{subtype:"success",request_id:e,response:"session"===n||"once"===n||"always"===n?{behavior:"allow"}:{behavior:"deny",message:t||"AEGIS_USER_DENIED"}}})},k=n=>{if(!p){if(p=!0,m&&clearTimeout(m),t.signal&&t.signal.removeEventListener("abort",A),_&&u.stdin&&!u.stdin.destroyed)try{u.stdin.end()}catch{}e(a.dropped.length?{...n,envDropped:a.dropped}:n)}},A=()=>{try{u.kill("SIGTERM")}catch{}setTimeout(()=>{try{u.kill("SIGKILL")}catch{}},1500)};t.signal&&t.signal.addEventListener("abort",A,{once:!0});const b=()=>{m&&clearTimeout(m),m=setTimeout(()=>{A(),k({choices:[{message:{content:""},finish_reason:"stop"}],error:`claude: the child went silent for ${Math.round(f/1e3)}s and was stopped`})},f)};b();const S=createStreamParser({onText:e=>{b(),t.onDelta&&t.onDelta({delta:e})},onThinking:e=>{b(),t.onDelta&&t.onDelta({reasoning:e})},onThinkingProgress:e=>{b(),t.onDelta&&t.onDelta({thinkingTokens:e})},onTool:e=>{b(),t.onDelta&&t.onDelta({delta:"",tool:{name:e.name,args:e.args,ok:"done"===e.phase?!e.error:void 0,id:e.id,cwd:t.cwd,phase:e.phase}})},onAsk:e=>{b(),Promise.resolve().then(()=>t.onAsk(e)).then(n=>y(e.requestId,"session"===n||"once"===n||"always"===n?n:"deny","AEGIS_USER_DENIED"),n=>{y(e.requestId,"deny",`AEGIS_USER_DENIED (${n&&n.message||String(n)})`)}).catch(()=>{})},onAskUnavailable:e=>{y(e.requestId,"deny","AEGIS_NO_APPROVAL_CHANNEL")},onDone:e=>{e.error?k({choices:[{message:{content:e.text||""},finish_reason:"error"}],usage:e.usage||void 0,error:e.error,...l.record.resumeSessionId&&isStaleResumeError(e.error)?{resumeStale:!0,resumeSessionId:l.record.resumeSessionId}:{}}):k({choices:[{message:proMessage(e.text||"",e.thinking,e.thinkingTokens),finish_reason:"stop"}],usage:e.usage||void 0,costUsd:e.costUsd,durationMs:e.durationMs,sessionId:e.sessionId,childRecord:l.record})}});u.stdout.on("data",e=>{b(),g+=e.toString("utf8");const n=g.split("\n");g=n.pop()||"";for(const e of n){const n=e.trim();n&&S.line(n)}}),_&&u.stdin&&u.stdin.on("error",()=>{}),u.stderr.on("data",e=>{b(),h.length<8192&&(h+=e.toString("utf8"))}),u.on("error",e=>{k({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not run the child (${e&&e.message||e}). Install it with \`npm i -g @anthropic-ai/claude-code\`, then sign in with \`claude auth login\`.`})}),u.on("close",e=>{g.trim()&&S.line(g.trim()),k({choices:[{message:proMessage(S.text,S.thinking,S.thinkingTokens),finish_reason:"stop"}],usage:S.resultLine&&S.resultLine.usage||void 0,childRecord:l.record,error:S.text||0===e?void 0:`claude: the child exited with status ${e}${h.trim()?` — ${h.trim().split("\n").slice(-3).join(" ")}`:""}`})})})}function isStaleResumeError(e){return!!e&&/no conversation found with session id/i.test(String(e))}function childLine(e,n){if(!e)return"";try{return loadSeam(n).child.childRecordLine(e)}catch{const n=e.skipFlag||"no permission flag";return`aegis: claude child [${e.kind}] ${n}`}}module.exports={claudeConfigDir:claudeConfigDir,claudeOAuthToken:claudeOAuthToken,claudeProStatus:claudeProStatus,childEnvPlan:childEnvPlan,envDroppedLine:envDroppedLine,shadowingValue:shadowingValue,SHADOWING_ENV_VARS:SHADOWING_ENV_VARS,PRO_MODELS:PRO_MODELS,turnArgs:turnArgs,createStreamParser:createStreamParser,loadSeam:loadSeam,seamAvailable:seamAvailable,childLine:childLine,isStaleResumeError:isStaleResumeError,runClaudePro:runClaudePro};
|
|
@@ -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 CHARS_PER_TOKEN=4,MESSAGE_OVERHEAD=4,IMAGE_COST=850;function estimateTokens(e){if(null==e)return 0;const t="string"==typeof e?e:String(e);return Math.max(0,Math.ceil(t.length/
|
|
3
|
+
"use strict";const CHARS_PER_TOKEN=4,MESSAGE_OVERHEAD=4,IMAGE_COST=850;function estimateTokens(e){if(null==e)return 0;const t="string"==typeof e?e:String(e);return Math.max(0,Math.ceil(t.length/4))}function messageTokens(e){if(!e)return 0;const t=null!=e.content?e.content:null!=e.text?e.text:"";if(Array.isArray(t)){let e=4;for(const s of t)s&&"object"==typeof s&&("string"==typeof s.text?e+=estimateTokens(s.text):("image_url"===s.type||s.image_url)&&(e+=850));return e}return 4+estimateTokens(t)}function trimContext({messages:e=[],system:t="",budgetTokens:s=8192,reserveTokens:n=0,fixedTokens:o=0}={}){const r=Math.max(0,s-n),i=[],a=Math.max(0,Number(o)||0);let m=a;t&&(m+=4+estimateTokens(t));for(let t=e.length-1;t>=0;t--){const s=messageTokens(e[t]);if(m+s>r&&i.length>0)break;i.unshift(e[t]),m+=s}return{messages:i,system:t,dropped:e.length-i.length,estimatedTokens:m,fixedTokens:a}}module.exports={CHARS_PER_TOKEN:4,MESSAGE_OVERHEAD:4,IMAGE_COST:850,estimateTokens:estimateTokens,messageTokens:messageTokens,trimContext:trimContext};
|
|
@@ -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{randomUUID:randomUUID}=require("node:crypto"),os=require("node:os"),fs=require("node:fs"),toolsModule=require("./tools.js"),attachmentsModule=require("./attachments.js"),{flattenContent:flattenContent}=attachmentsModule,promptModule=require("./prompt.js"),localTransport=require("./local.js"),{ShellSession:ShellSession}=require("./shell.js"),{planExec:planExec}=require("./exec-plan.js"),claudePro=require("./claude-pro.js"),{agentSystemPrompt:agentSystemPrompt,agentRoleLabel:agentRoleLabel}=require("./agents.js"),{beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,blocksDestructive:blocksDestructive}=require("./turn-guard.js"),repeatGuard=require("./repeat-guard.js"),verifyGuard=require("./verify-stop.js"),{acquireWorktreeLock:acquireWorktreeLock,releaseWorktreeLock:releaseWorktreeLock}=require("./worktree-lock.js"),covenant=require("./covenant.js");let envFile=null;try{envFile=require("../../../client/env-file.js")}catch{try{envFile=require("../../vendor/env-file.js")}catch{envFile=null}}let platformLib=null;try{platformLib=require("../../../client/platform.js")}catch{try{platformLib=require("../../vendor/platform.js")}catch{platformLib=null}}let credentialsLib=null;try{credentialsLib=require("../../../client/credentials.js")}catch{try{credentialsLib=require("../../vendor/credentials.js")}catch{credentialsLib=null}}const PRO_TOOL_MAP=Object.freeze({Write:"writeFile",Edit:"editFile",MultiEdit:"editFile",NotebookEdit:"editFile",Bash:"exec",BashOutput:"exec"}),PRO_PLAN_MODE_SAFE=Object.freeze(new Set(["Read","Glob","Grep"]));function proAskArgs(e,t){const o=e&&"object"==typeof e?e:{};return"exec"===t?"string"==typeof o.command?{command:o.command}:{}:"writeFile"===t?"string"==typeof o.file_path?{file_path:o.file_path,content:o.content}:{}:"editFile"===t?Array.isArray(o.edits)?{file_path:o.file_path,edits:o.edits}:"string"==typeof o.file_path?{file_path:o.file_path,old_string:o.old_string,new_string:o.new_string,replace_all:!0===o.replace_all}:{}:o}function normalizeToolArgs(e,t,o,r){const n=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof toolsModule.normalizeArgs&&toolsModule.normalizeArgs||null;return n?n(t,o,r):{ok:!0,args:o&&"object"==typeof o?o:{},error:null}}function detectVcs(e){if(!e)return null;try{const t=require("node:fs"),o=require("node:path");let r=o.resolve(String(e));for(let e=0;e<8;e+=1){if(t.existsSync(o.join(r,".git")))return"git";const e=o.dirname(r);if(e===r)break;r=e}return""}catch{return null}}function hostEnv(e={},t={},o=null){const r=e||{},n=t||{},s=(e,t)=>null!=n[e]?n[e]:t;let a=r.homedir,i=r.cwd;try{a||(a=os.homedir()),i||(i=process.cwd())}catch{}let l=r.shell,c=r.shellKind;try{if(!l||!c){const e=require("./shell.js").resolveSessionShell();l=l||e.cmd,c=c||e.kind}}catch{}let d=r.desktopdir;try{!d&&platformLib&&(d=platformLib.desktopDir())}catch{}let u=r.dataDir;try{!u&&credentialsLib&&(u=credentialsLib.aegisHome())}catch{}let f=r.locale,p=r.localeName;try{!f&&platformLib&&"function"==typeof platformLib.appLocale&&(f=platformLib.appLocale()),f&&!p&&platformLib&&"function"==typeof platformLib.languageName&&(p=platformLib.languageName(f))}catch{}return{platform:s("platform",r.platform||process.platform),arch:s("arch",r.arch||process.arch),homedir:s("homedir",a),desktopdir:s("desktopdir",d),dataDir:s("dataDir",u),locale:s("locale",f),localeName:s("localeName",p),languages:s("languages",r.languages),cwd:s("cwd",i),vcs:s("vcs",null!=r.vcs?r.vcs:detectVcs(i)),shell:s("shell",l),shellKind:s("shellKind",c),roots:s("roots",r.roots),appVersion:s("appVersion",r.appVersion),model:s("model",o&&o.model)}}function requireSharedBrain(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedByokCatalog(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedUserModels(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedCatalogClient(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelDiscovery(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelSync(){const e=[()=>require("../../../client/model-sync.js"),()=>require("../../vendor/model-sync.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelAutoSync(){const e=[()=>require("../../../client/model-autosync.js"),()=>require("../../vendor/model-autosync.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`${BYOK_NAMESPACE_PREFIX}${e}`}function splitByokModel(e){const t="string"==typeof e?e:"",o=t.indexOf(":");return o<0?{provider:"",model:t}:{provider:t.slice(0,o),model:t.slice(o+1)}}function providerKeyRecord(e){const t={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return t;try{const o=envFile.providerKeyFromEnv(e)||t;return{key:"string"==typeof o.key?o.key:"",env:"string"==typeof o.env?o.env:"",rejected:"string"==typeof o.rejected&&o.rejected?o.rejected:null}}catch{return t}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,t,o){const r=Number(t);return Number.isFinite(r)&&r>0?r:DEEPSEEK_REASONING_MODEL_RE.test(String(e||""))?EFFORT_TOKEN_BUDGET["low"===o||"medium"===o||"max"===o?o:"high"]:void 0}function nativeEffort(e,t,o){const r=String(t||"");if(EFFORT_INERT_RE.test(r))return;if(null===o)return;const n="low"===o||"medium"===o?o:"max"===o?"max":"high";for(const t of EFFORT_DIALECTS)if(t.provider===e&&t.re.test(r)){const e=Object.prototype.hasOwnProperty.call(t.map,n)?t.map[n]:t.extra&&Object.prototype.hasOwnProperty.call(t.extra,n)?t.extra[n]:void 0;if(void 0===e)return;return{field:t.field,level:e}}}function normalizeCatalog(e){return Array.isArray(e)?e.map((e=>"string"==typeof e?{id:e}:e)).filter((e=>e&&e.id)):[]}const{offerableCatalog:offerableCatalog}=requireSharedBrain(),{withByokAdditions:withByokAdditions,canonicalModelId:canonicalModelId,nexusFallbackModel:nexusFallbackModel}=requireSharedByokCatalog(),{withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders,load:loadUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel}=requireSharedUserModels(),{withCatalog:withCatalog}=requireSharedCatalogClient(),{discoverModels:discoverVendorModels,canDiscover:canDiscoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=requireSharedModelDiscovery(),modelSync=requireSharedModelSync(),{createModelAutoSync:createModelAutoSync}=requireSharedModelAutoSync();function parseArgs(e){if(null==e)return{};if("object"==typeof e)return e;try{const t=JSON.parse(String(e));return t&&"object"==typeof t?t:{}}catch{return{}}}function extractToolCalls(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map((e=>({id:e.id||"",name:e.name||"",args:parseArgs(e.args)}))).filter((e=>e.name));const t=e.choices&&e.choices[0]&&e.choices[0].message,o=t&&t.tool_calls||[];return Array.isArray(o)?o.map((e=>{const t=e&&e.function||{};return{id:e&&e.id||"",name:t.name||e&&e.name||"",args:parseArgs(t.arguments)}})).filter((e=>e.name)):[]}function proTurnPrompt(e){const t=Array.isArray(e.prompt)?flattenContent(e.prompt):e.prompt;if("string"==typeof t&&t.trim())return t;const o=Array.isArray(e.messages)?e.messages:[];for(let e=o.length-1;e>=0;e-=1){const t=o[e];if(!t||"user"!==t.role)continue;const r=flattenContent(t.content);if(r.trim())return r}return t}function assistantText(e){const t=e&&e.choices&&e.choices[0]&&e.choices[0].message;return t&&"string"==typeof t.content&&t.content||""}function finishReasonOf(e){const t=e&&e.choices&&e.choices[0];return t&&t.finish_reason||e&&e.stop_reason||""}function isTruncated(e){const t=finishReasonOf(e);return"length"===t||"max_tokens"===t}function reasoningTextOf(e){if(!e)return"";const t=e.choices&&e.choices[0],o=t&&t.message||{};if(Array.isArray(o.content)){const e=o.content.filter((e=>e&&("thinking"===e.type||"reasoning"===e.type))).map((e=>e.thinking||e.text||"")).join("");if(e)return e}const r=o.content&&"object"==typeof o.content?o.content.reasoning_content:"",n=[o.reasoning_content,o.reasoning,t&&t.reasoning_content,e.reasoning_content,e.reasoning,r];for(const e of n)if("string"==typeof e&&e)return e;return""}function reasoningTokensOf(e){if(!e)return 0;const t=e.choices&&e.choices[0],o=t&&t.message||{},r=e.usage||{},n=r.completion_tokens_details||r.output_tokens_details||{},s=[o.thinking_tokens,o.reasoning_tokens,t&&t.thinking_tokens,e.thinking_tokens,n.reasoning_tokens,n.thinking_tokens];for(const e of s)if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;return 0}function reasonedButSilent(e){return!assistantText(e)&&(""!==reasoningTextOf(e)||reasoningTokensOf(e)>0)}const REASONING_RETRY_FLOOR=32768;function retryBudgetFor(e,t){const o=doubledBudget(e.maxTokens);return t&&ladderRung(e.maxTokens)?Math.max(o,REASONING_RETRY_FLOOR):o}function ladderRung(e){const t=Number(e);return Number.isFinite(t)&&Object.values(EFFORT_TOKEN_BUDGET).includes(t)}function doubledBudget(e){const t=Number(e)||0;return t>0?2*t:8192}function statedCapOf(e){const t=e=>{const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?t(e.statedMaxTokens):t(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,t,o){if(t)return!1;if(!(o>0))return!1;const r=String(e||"");return!!r.trim()&&!/\?\s*$/.test(r.trim())&&MUTATION_INTENT_RE.test(r)}function emptyTurnError({cls:e,model:t,finishReason:o,reasoningChars:r,reasoningTokens:n,effort:s,recoveryRounds:a}){const i=Number(a)||0,l=Number(n)||0,c=new Error(`The model returned no answer after ${e}/${t} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${o||"none"}`+(s?`, effort: ${s}`:"")+(r?`, hidden reasoning: ${r} chars and no visible text`:l>0?`, ~${l} thinking tokens billed and no visible text`:"")+"). "+(r||l>0?"Every one of those calls spent its output on hidden reasoning instead of writing a word, so this is the model rather than the budget: pick a model that answers without a thinking pass, or ask for a smaller piece of work.":"No visible text came back from any of those calls. Send the request again, in smaller pieces, or from a different model."));return c.status=502,c}function createLocalEngine({aegis:e,settings:t,tools:o,promptBuilder:r,recallProvider:n,env:s,getConfirmMode:a,getPermissionMode:i,sandbox:l,localTransport:c=localTransport,fetchImpl:d,gitScope:u,permissionRules:f}){const p=new Map,m=o||toolsModule,h=r&&r.buildSystemPrompt||promptModule.buildSystemPrompt,y=f&&"function"==typeof f.rulesVerdict?f.rulesVerdict:null,g=f&&"function"==typeof f.alwaysAllow?f.alwaysAllow:null,k=f&&"function"==typeof f.subjectFor?f.subjectFor:null,v=require("./session-rounds.js"),b=()=>{if("function"==typeof a)return!1!==a();if(t&&"function"==typeof t.getConfirmMode){const e=t.getConfirmMode();return void 0===e||Boolean(e)}return!0},w=()=>"function"==typeof i?"plan"===i():!(!t||"function"!=typeof t.getPermissionMode)&&"plan"===t.getPermissionMode();function E(e,t){return`${e} was not executed — this session is in plan mode (read-only). Plan mode may read files, search, run read-only shell commands and deploy subagents to research, but may not create, edit or delete files, run a mutating command, or install packages`+(t?` (this command: ${t})`:"")+". Do NOT retry it or attempt the same effect by another route. Finish your research and present a plan in plain text; the user exits plan mode (`/permissions mode off`) before any edit can run."}const _=new Map,S=new Map,T=new Map,A=200,x=new Map,M=require("./pro-sessions.js"),O=new Map,N=new Map;function F(e,t){if("function"!=typeof k)return e;let o="";try{o=String(k(e,t||{})||"")}catch{o=""}return`${e}\0${o}`}function R(e,t,o){_.has(e)||_.set(e,new Set),_.get(e).add(F(t,o))}function D(e,t){const o=S.get(e);return Boolean(o&&o.has(t))}function I(e,t){S.has(e)||S.set(e,new Set),S.get(e).add(t)}function U(e){if(!e)return null;try{return{existed:!0,content:fs.readFileSync(e,"utf8")}}catch(e){return e&&"ENOENT"===e.code?{existed:!1,content:null}:null}}function L(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function C(e,t,o,r){return new Promise((n=>{if(o&&o.aborted)return void n("cancel");const s=randomUUID();let a=!1;const i=()=>l("cancel"),l=e=>{a||(a=!0,O.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),O.set(s,{resolve:l}),"function"==typeof t?t({delta:"",approval:{id:s,sessionId:e,tool:r.tool,args:r.args,diff:r.diff||null,canPersist:"function"==typeof g}}):l("cancel")}))}function P(e,t,o,r){return new Promise((n=>{if(o&&o.aborted)return void n(!1);const s=randomUUID();let a=!1;const i=()=>l(!1),l=e=>{a||(a=!0,N.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),N.set(s,{resolve:l}),"function"==typeof t?t({delta:"",rounds:{id:s,sessionId:e,spent:r.spent,extensions:r.extensions,max:r.max,size:r.size}}):l(!1)}))}async function $(e,t,o,r,n){const s=normalizeToolArgs(m,e,t,o||{});if(!s.ok)return{ok:!1,error:s.error};t=s.args;const a=o&&o.guard;if(a&&"exec"===e){const e=blocksDestructive(a,t&&t.command);if(!e.ok)return{ok:!1,error:e.reason}}const i=o&&o.repeat,l=i?repeatGuard.check(i,e,t):null;if(l&&"refuse"===l.action)return{ok:!1,error:l.error};const c=covenant.preActionAssert({tool:e,args:t||{}});if(!c.allowed){const o=covenant.bindRefusal({tool:e,args:t||{}},c);return{ok:!1,error:`refused by the ÆGIS covenant — ${c.clause} (${c.label}): ${c.reason}`,covenant:o}}const d="writeFile"===e||"editFile"===e,u=d?U(t&&t.file_path):null,f=await m.executeTool(e,t,o);a&&d&&f&&!1!==f.ok&&recordWrite(a,t&&t.file_path),i&&d&&f&&!1!==f.ok&&repeatGuard.recordWrite(i,t&&t.file_path);const p=o&&o.verify;if(p&&(verifyGuard.EXEC_TOOLS.has(e)&&f&&!1!==f.ok?verifyGuard.recordExec(p):d&&f&&!1!==f.ok&&verifyGuard.recordMutation(p,t&&t.file_path)),d&&u&&f&&!1!==f.ok){const o=U(t&&t.file_path);o&&function(e,t){if(!e)return;T.has(e)||T.set(e,[]);const o=T.get(e);o.push(t),o.length>A&&o.shift()}(r,{id:n||randomUUID(),tool:e,path:t&&t.file_path,before:u,after:o,at:Date.now()})}return l&&l.note?q(f,l.note):f}function q(e,t){if(!e||"object"!=typeof e)return{ok:!0,content:`${t}\n${null==e?"":e}`};if(!1===e.ok||!0===e.isError){const o=e.error||e.content||"";return{...e,error:`${t}\n${o}`,content:`${t}\n${o}`}}const o=null!=e.content?e.content:null!=e.output?e.output:"";return{...e,content:`${t}\n${o}`}}async function j(e,{toolCtx:t,rootSessionId:o,rootOnDelta:r,signal:n}){const{name:s}=e,a=normalizeToolArgs(m,s,e.args,t||{});if(!a.ok)return{ok:!1,error:a.error};const i=a.args;if(!m.MUTATING_TOOLS.has(s))return $(s,i,t,o,e.id);if(w()){if("exec"===s){const r=planExec(i&&i.command,{baseCwd:t&&t.cwd||void 0});return r.oneShot?$(s,i,t,o,e.id):{ok:!1,error:E(s,r.reason)}}return{ok:!1,error:E(s)}}if(!b())return $(s,i,t,o,e.id);if(function(e,t,o){const r=_.get(e);return Boolean(r&&r.has(F(t,o)))}(o,s,i))return $(s,i,t,o,e.id);if("function"==typeof y){let r;try{r=y(s,i)}catch(e){r={verdict:null,source:"error",error:e&&e.message||String(e)}}if(r&&"deny"===r.verdict)return I(o,s),{ok:!1,error:L(s),permissionRule:r.rule||null};if(r&&"allow"===r.verdict)return $(s,i,t,o,e.id)}if(D(o,s))return{ok:!1,error:L(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=m.previewMutation(s,i,t||{}),!l.ok))return{ok:!1,error:l.error};const c=await C(o,r,n,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return I(o,s),{ok:!1,error:L(s)};if("session"!==c&&"once"!==c&&"always"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};let d=null;if("always"===c){let e=null;if("function"==typeof g)try{e=g(s,i)}catch(t){e={ok:!1,reason:t&&t.message||String(t)}}else e={ok:!1,reason:"no durable store is wired on this host"};d=e&&e.ok?`[permission_rule] stored ${e.rule} — this command will not ask again`:`[permission_rule] nothing was stored — ${e&&e.reason||"unknown reason"}; this call was allowed once only`}if("session"===c&&R(o,s,i),l){const e=m.applyChecked(s,i,l,t||{});return e&&!1!==e.ok&&t&&t.guard&&recordWrite(t.guard,i&&i.file_path),d?q(e,d):e}const u=await $(s,i,t,o,e.id);return d?q(u,d):u}function B(e){return hostEnv(s||{},e&&e.env||{},e)}function K(e){const t=[],o=e=>String(e||"").replace(/[\\/]+$/,""),r=o(e),n=e=>{const n=o(e);n&&n!==r&&!t.includes(n)&&t.push(n)};let s=u;if(void 0===s)try{s=require("./git-scope.js")}catch{s=null}try{s&&"function"==typeof s.gitRoot&&n(s.gitRoot(e))}catch{}try{credentialsLib&&"function"==typeof credentialsLib.aegisHome&&n(credentialsLib.aegisHome())}catch{}return t}async function G(t,o){if("aegis"===t){const t=!o.singlePass&&(!!o.autonomous||void 0);return e.chatCompletion({prompt:o.prompt,system:o.system,messages:o.messages,model:o.model,mode:o.mode,maxTokens:o.statedMaxTokens,stream:!1!==o.stream,includeUsage:!0,onStream:o.onDelta,onReasoning:o.onReasoning,idleTimeoutMs:o.idleTimeoutMs,signal:o.signal,extra:{aegis_recall:!0,...o.recallDeep?{aegis_recall_deep:!0}:{},session:o.sessionId,...void 0===t?{}:{brain:t},...!1===t?{mode:"brain"}:{},...o.effort?{effort:o.effort}:{},...!0===t&&o.workers?{workers:o.workers}:{},...o.tools.length?{tools:o.tools}:{},...o.toolChoice?{tool_choice:o.toolChoice}:{}},agentKey:o.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===t){const{provider:t,model:r}=splitByokModel(o.model),n=canonicalModelId(t,r),s=nativeEffort(t,n,o.effort);try{return await e.byokChatCompletion({provider:t,model:n,providerKey:o.apiKey,baseURL:o.cfg&&o.cfg.baseURL,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,tools:o.tools,toolChoice:o.toolChoice,effort:s&&"effort"===s.field?s.level:void 0,reasoningEffort:s&&"reasoning_effort"===s.field?s.level:void 0,stream:!0,onStream:o.onDelta,signal:o.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===t){const e=o.cfg&&o.cfg.baseURL||c.DEFAULT_BASE,t=t=>c.chat({baseURL:e,model:o.model,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,signal:o.signal,onDelta:o.onDelta,...t&&o.tools.length?{tools:o.tools,toolChoice:o.toolChoice}:{}});try{return await t(!0)}catch(e){if(o.tools.length&&e&&400===e.status)return t(!1);throw e}}if("pro"===t){const e=o.sessionKey||o.rootSessionId||o.sessionId;let t=null;if(e&&(t=x.get(e)||null,!t)){try{t=M.get(e,s)||null}catch{}t&&x.set(e,t)}const r=K(o.cwd),n=e=>claudePro.runClaudePro({prompt:proTurnPrompt(o),model:o.model&&"default"!==o.model?o.model:void 0,system:o.system,cwd:o.cwd,addDir:r,resumeSessionId:e||void 0,gate:b(),onAsk:async e=>{if(!e||!e.requestId)return"deny";const t=o.rootSessionId,r=o.rootOnDelta,n=PRO_TOOL_MAP[String(e.toolName||"")]||null,s=n||String(e.toolName||"unknown"),a=proAskArgs(e.input||{},s),i=covenant.preActionAssert({tool:s,args:a});if(!i.allowed)return r&&r({delta:"",note:`aegis: refused by the ÆGIS covenant — ${i.clause} (${i.label}): ${i.reason}`}),"deny";if(w()){if("exec"===s){const e=planExec(a&&a.command,{baseCwd:o.cwd||void 0});return e.oneShot?"once":(r&&r({delta:"",note:E(s,e.reason)}),"deny")}if(n&&m.MUTATING_TOOLS.has(s))return r&&r({delta:"",note:E(s)}),"deny";if(!n&&!PRO_PLAN_MODE_SAFE.has(s))return r&&r({delta:"",note:E(s)}),"deny"}if(!b())return"once";if("function"==typeof y){let e;try{e=y(s,a)}catch{e=null}if(e&&"deny"===e.verdict)return r&&r({delta:"",note:L(s)}),"deny";if(e&&"allow"===e.verdict)return"once"}if(D(t,s))return r&&r({delta:"",note:L(s)}),"deny";const l=await C(t,r,o.signal,{tool:s,args:a,diff:null});if("deny"===l)return I(t,s),"deny";if("session"!==l&&"once"!==l&&"always"!==l)return"deny";if("session"===l&&R(t,s,a),"always"===l&&"function"==typeof g)try{g(s,a)}catch{}return l},signal:o.signal,onDelta:o.onDelta,onSpawn:(e,t)=>{o.onDelta&&t&&o.onDelta({delta:"",note:claudePro.childLine(t)})}});let a=await n(t);if(a&&a.resumeStale){x.delete(e);try{M.del(e,s)}catch{}o.onDelta&&o.onDelta({delta:"",note:"aegis: the remembered Claude session no longer exists on this machine — continuing as a new conversation (earlier turns are not in its context)"}),a=await n(null)}if(e&&a&&a.sessionId&&!a.error){x.set(e,a.sessionId);try{M.set(e,a.sessionId,s)}catch{}}return a}throw new Error(`dispatch: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function Y(o,r){const s=o&&o.class,a=o&&o.model,i=reasoningBudget("byok"===s?splitByokModel(a).model:a,o&&o.maxTokens,o&&o.effort),d=statedCapOf(o),u="aegis"===s&&Boolean(o&&o.autonomous),f=Boolean(o&&o.roundsAsk),y=o&&o.sessionId||randomUUID(),g=Number.isInteger(o&&o.depth)?o.depth:0,k=o&&o.rootSessionId||y,b=o&&o.rootOnDelta||r,w="function"==typeof r?e=>e&&r({reasoning:e}):void 0,E=new AbortController,_=p.get(y)||null;p.set(y,E);const S=E.signal,T=!(o&&!1===o.tools),A=T?m.toolsFor({includeSubagent:g<4}):[],x=o&&o.toolChoice||null,M=o&&o.system||h(B(o)),O=n?await n({payload:o,env:B(o),system:M}):null,N="string"==typeof O?O:O&&"string"==typeof O.system?O.system:M,F=Array.isArray(o&&o.messages)?o.messages.filter(Boolean).slice():[];let R=F.length,D=o&&o.prompt||"";const I=String(D||""),U=Array.isArray(o&&o.attachments)?o.attachments.filter((e=>e&&"object"==typeof e)).slice(0,attachmentsModule.MAX_ATTACHMENTS):[];let L=U.length?attachmentsModule.buildContent(D,U):D,C=null;const $=B(o),q=((e,t)=>{if(null==l)return null;const o="function"==typeof l.policy?l.policy():l.policy;if(!o)return null;const r=require("./sandbox.js"),n=e&&e.cwd||process.cwd(),s=r.normalize(o,n);if("off"===s.mode)return null;let a=[];try{let e=null;try{e=require("node:os").homedir()}catch{e=null}a=r.autoGrants(n,{home:e,addDirs:(()=>{try{return K(n)}catch{return[]}})()})}catch{a=[]}if(a.length){const e=new Set;for(const t of s.fileSystem.entries)t&&t.path&&"path"===t.path.type&&t.path.path&&e.add(`${t.access}:${t.path.path}`);for(const t of a){const o=`${t.access}:${t.path.path}`;e.has(o)||(e.add(o),s.fileSystem.entries.push(t))}}return"local"===t&&"restricted"===s.network&&(s.network="open",s.networkExempt="local"),{policy:s,state:l.state||r.detect({appDir:l.appDir}),workspace:n,appDir:l.appDir,strict:!0===l.strict}})($,s),Y=$.cwd,z={getShell:()=>C||(C=new ShellSession({cwd:$.cwd,sandbox:q})),signal:S,cwd:Y,desktopdir:$.desktopdir,sandbox:q,repeat:repeatGuard.beginRepeatGuard({cwd:Y}),verify:verifyGuard.beginVerifyGuard({cwd:Y}),guard:beginTurnGuard(Y)};try{const n="byok"===s?splitByokModel(a):null;let l=null;const p="byok"===s?t.get(byokNamespace(n.provider))||{}:"local"===s&&t.get("local")||{},h="byok"===s?t.rawKey(byokNamespace(n.provider)):null,E="byok"!==s?null:h||providerKeyFromEnv(n.provider);if(!("byok"!==s||n.provider&&n.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(a||""));throw e.status=400,e}if("byok"===s&&!E){const t="anthropic"===n.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(n.provider).rejected,r=nexusFallbackModel({provider:n.provider,providerKey:E,providerKeyRefused:o,aegisKey:E?"":e.apiKey});if(!r){const e=new Error(o?`${o}. That is why this turn has no ${n.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${o.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${n.provider} <key> to set one here.`:t&&t.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${t.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${n.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${n.provider} <key>.`);throw e.status=400,e}l={from:n.provider,model:r}}if("byok"===s&&!e.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===s){const e=c.remoteRefusal(p.baseURL||c.DEFAULT_BASE);if(e)throw e}if("byok"===s&&"custom"===n.provider&&!(p.baseURL||"").trim()){const e=new Error('No endpoint saved for the "custom" provider — its key is on this machine but the address it dials is not, and no default exists for a vendor AEGIS does not know. Fix: /model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const _=l?"aegis":s,M={cls:_,model:l?l.model:a,mode:o&&o.mode,maxTokens:i,statedMaxTokens:d,autonomous:u,sessionId:y,signal:S,onDelta:r,cfg:p,apiKey:E,toolChoice:x,pooledFrom:l?l.from:void 0,cwd:Y,rootSessionId:k,sessionKey:o&&o.sessionKey||void 0,rootOnDelta:b,effort:o&&o.effort,workers:o&&o.workers,recallDeep:o&&!0===o.recallDeep,singlePass:o&&!0===o.singlePass,onReasoning:w,idleTimeoutMs:u?9e5:void 0,stream:!o||!1!==o.stream};let O=!1,C=!1;const $=u?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",q=(()=>{const e=Number.parseInt(process.env[$]||"",10);return Number.isFinite(e)&&e>0?e:0})(),B=q||(u?40:24);let K=v.keyFor(o,F),V=v.take(K);if(!V&&!v.isStatedKey(o)){const e=v.adopt();e&&(V=e.entry,K=e.key)}if(V){const e=v.resumePreamble(V);0===F.length?Array.isArray(V.messages)&&V.messages.length&&F.push(...V.messages):Array.isArray(V.added)&&V.added.length&&F.push(...V.added),D?(D=`${e}\n\n${D}`,L=U.length?attachmentsModule.buildContent(D,U):D):(F.push({role:"user",content:e}),L=""),b&&b({delta:`\n\n[resuming work this session left unfinished at ${V.rounds} tool rounds`+(V.interruptions>1?` (cut off ${V.interruptions}×)`:"")+"…]\n"})}let H=q||B+(V?v.bonus(B):0),X=0;const J=B,Q=8;let Z=0;const ee={calls:0},te=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],oe=e=>{const t=e&&e.usage;if(t&&"object"==typeof t){ee.calls+=1;for(const e of te)"number"==typeof t[e]&&Number.isFinite(t[e])&&(ee[e]=(ee[e]||0)+t[e]);if("number"!=typeof t.total_tokens){const e=(t.prompt_tokens??t.input_tokens??0)+(t.completion_tokens??t.output_tokens??0);e&&(ee.total_tokens=(ee.total_tokens||0)+e)}}},re=e=>{if(!e||"object"!=typeof e)return e;const t=l?{...e,pooled_from:l.from,pooled_model:l.model,pooled_notice:requireSharedByokCatalog().nexusFallbackNotice({pooled_from:l.from,pooled_model:l.model})}:e;return ee.calls?{...t,usage:{...ee}}:t},ne=()=>{if(""===L)return;const e=F[F.length-1],t=e&&"user"===e.role?flattenContent(e.content):null;e&&"user"===e.role&&t===flattenContent(L)||F.push({role:"user",content:L}),D="",L=""};R=F.length;const se=m&&m.MUTATING_TOOLS||new Set;let ae=0,ie=0,le=!1,ce=!1;for(;;){if(X>=H){if(f&&Z<Q&&!S.aborted&&await P(k,b,S,{spent:H,extensions:Z+1,max:Q,size:J})){Z+=1;const e=H;H+=J,F.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${J} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=f?"":`, or raise ${$} for a longer single turn`,t=`[stopped at ${H} tool rounds`+(ee.total_tokens?`, ${ee.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,o=v.record(K,{rounds:X,tokens:ee.total_tokens||0,note:t,chain:V?V.interruptions:0,messages:F,added:F.slice(R)});return b&&b({delta:`\n\n${t}`}),re({model:M.model,choices:[{message:{content:t},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:o.rounds,sessionInterruptions:o.interruptions,resumedFrom:K})}X+=1;const e={...M,system:N,messages:F,prompt:L,tools:A,recallDeep:M.recallDeep&&1===X};let t;if(t=await G(_,e),oe(t),S.aborted)return re(t);if(!O&&!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){O=!0;const o=reasonedButSilent(t);if(t=await G(_,{...e,singlePass:!0,recallDeep:!1,effort:o?"high":e.effort,maxTokens:retryBudgetFor(e,o),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),oe(t),S.aborted)return re(t)}const n=A.length?extractToolCalls(t):[];if(!n.length){if(assistantText(t)||C||!T){if(!le&&T&&wantsMutation(I,ie>0,ae)){le=!0,ne(),F.push({role:"assistant",content:assistantText(t)}),F.push({role:"user",content:UNMUTATED_TURN_NUDGE}),b&&b({delta:""});continue}if(z.verify&&!ce){const e=verifyGuard.shouldNudge(z.verify);if(e.nudge){ce=!0,ne(),F.push({role:"assistant",content:assistantText(t)}),F.push({role:"user",content:e.text}),b&&b({delta:""});continue}}return re(t)}C=!0,ne(),F.push({role:"user",content:reasonedButSilent(t)?THOUGHT_ONLY_NUDGE:EMPTY_TURN_NUDGE});const o={...e,singlePass:!0,recallDeep:!1,messages:F,prompt:"",tools:[]};t=await G(_,o);let r=o.maxTokens,n=o.effort;if(oe(t),S.aborted)return re(t);if(!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){const e=reasonedButSilent(t);if(r=retryBudgetFor(o,e),n=e?"high":o.effort,t=await G(_,{...o,effort:n,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),S.aborted)return re(t)}const i=(()=>{const e=Number(r)||0;if(!e)return r;const t={maxTokens:r};return o.statedMaxTokens&&(t.statedMaxTokens=o.statedMaxTokens),Math.max(e,retryBudgetFor(t,!0))})();let l=0;for(;!assistantText(t)&&l<2&&!S.aborted;){const e=reasonedButSilent(t);if(l+=1,F.push({role:"user",content:e?1===l?THOUGHT_ONLY_NUDGE:FINAL_ANSWER_NUDGE:EMPTY_TURN_NUDGE}),e&&(n="high"),r=i,t=await G(_,{...o,messages:F,effort:n,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),S.aborted)return re(t)}if(!assistantText(t))throw emptyTurnError({cls:s,model:a,effort:n,recoveryRounds:l,finishReason:finishReasonOf(t),reasoningChars:reasoningTextOf(t).length,reasoningTokens:reasoningTokensOf(t)});return re(t)}ne(),F.push({role:"assistant",content:assistantText(t),tool_calls:n.map((e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}})))});const i=new WeakMap,l=e=>{if("exec"!==e.name)return null;if(i.has(e))return i.get(e);const t=planExec(e.args&&e.args.command,{baseCwd:Y});return i.set(e,t),t},c=e=>{if(!se.has(e.name))return!0;const t=l(e);return Boolean(t&&t.oneShot)},u=[];for(const e of n){const t=u[u.length-1];c(e)&&t&&t.parallel?t.calls.push(e):u.push({parallel:c(e),calls:[e]})}const p=async e=>{r&&r({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:Y,phase:"run"}});const t=l(e),n=t&&t.oneShot?{...z,oneShotExec:!0,cwd:t.cwd||z.cwd}:z,i=e.name===m.SUBAGENT_TOOL?await W(e.args,{cls:s,model:a,statedMaxTokens:d,effort:o&&o.effort,mode:o&&o.mode,parentSignal:S,depth:g,rootSessionId:k,rootOnDelta:b}):await j(e,{toolCtx:n,rootSessionId:k,rootOnDelta:b,signal:S});return i&&i.usage&&oe({usage:i.usage}),r&&r({delta:"",tool:{name:e.name,args:e.args,ok:i.ok,id:e.id,cwd:Y,phase:"done"}}),i};for(const e of u){const t=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map((e=>p(e)))):[await p(e.calls[0])];e.calls.forEach(((e,o)=>{const r=t[o];se.has(e.name)&&(ae+=1,r&&r.ok&&(ie+=1)),F.push({role:"tool",tool_call_id:e.id,name:e.name,content:m.toolResultText(r)})}))}}}catch(e){throw S.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{C&&C.dispose(),p.get(y)===E&&(_&&!_.signal.aborted?p.set(y,_):p.delete(y))}}async function W({description:e,subagent_type:t,prompt:o}={},{cls:r,model:n,statedMaxTokens:s,effort:a,mode:i,parentSignal:l,depth:c,rootSessionId:d,rootOnDelta:u}={}){const f=String(o||e||"").trim();if(!f)return{ok:!1,error:"task requires a prompt"};const p=t&&"general"!==t?agentRoleLabel(t):"general",m=agentSystemPrompt(t),h=randomUUID();let y;if(l){if(l.aborted)return{ok:!1,error:"aborted"};y=()=>z(h),l.addEventListener("abort",y,{once:!0})}try{const e=await Y({class:r,model:n,mode:i,system:m,prompt:f,sessionId:h,depth:(c||0)+1,rootSessionId:d,rootOnDelta:u,statedMaxTokens:s,effort:a},(()=>{})),t=assistantText(e),o=e&&e.usage?{usage:e.usage}:{};return t?{ok:!0,output:t,...o}:{ok:!1,error:`subagent (${p}) produced no output`,...o}}catch(e){return{ok:!1,error:`subagent (${p}) failed: ${e&&e.message?e.message:e}`}}finally{l&&y&&l.removeEventListener("abort",y)}}function z(e){const t=p.get(e);return t&&t.abort(),{ok:Boolean(t)}}function V(e){const o=String(null==e?"":e).trim().toLowerCase();if(!o)return"";try{if(t&&"function"==typeof t.rawKey){const e=t.rawKey(byokNamespace(o));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(o)}async function H(t){let o=[];try{const t=await e.byokProviders();o=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[])))}catch(e){return{ok:!1,providers:[],missing:0,stale:0,skipped:[],failed:[],error:e&&e.message||String(e)}}const r={};for(const e of modelSync.askableProviders(o,t)){const t=V(e);t&&(r[e]=t)}return modelSync.plan(o,{keys:r,fetchImpl:d,only:t})}const X=createModelAutoSync({getPref:()=>{try{return t&&"function"==typeof t.getSharedPref?t.getSharedPref("modelAutoSync"):null}catch{return null}},plan:e=>H(e),apply:(e,t)=>modelSync.apply(e,{only:t})});return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map((o=>{if("aegis"===o.class)return{...o,configured:Boolean(e.apiKey)};if("byok"===o.class){const e=(t.list()||[]).some((e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(BYOK_NAMESPACE_PREFIX.length))))));return{...o,configured:e}}if("local"===o.class)return{...o,configured:!0};if("pro"===o.class){const e=claudePro.claudeProStatus({env:process.env}),t=claudePro.seamAvailable();return{...o,configured:e.loggedIn,status:e,seam:t}}return{...o,configured:!1}}))},listModels:async function(o){if("aegis"===o){if(!e.apiKey)return{class:o,models:[],needsKey:!0};const t=await e.listModels();return{class:o,models:offerableCatalog(normalizeCatalog(t&&t.models))}}if("byok"===o){let r=[],n=null,s=!1,a=null;try{const t=await e.byokProviders();r=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[]))),n=t&&t.fee||null}catch(e){r=[],s=!0,a=e&&e.message||String(e)}const i=[];for(const e of r){if(!e||!e.id)continue;const o=t.get(byokNamespace(e.id))||{},r=providerKeyRecord(e.id),n=r.key||"",s=Array.isArray(e.models)?e.models:[];for(const t of s){const s="string"==typeof t?t:t&&t.id;s&&i.push({id:`${e.id}:${s}`,label:`${e.label||e.id} — ${s}`,provider:e.id,configured:Boolean(o.configured||n),keyRejected:r.rejected||null})}}return{class:o,models:i,providers:r,needsProviderKey:i.length>0&&!i.some((e=>e.configured)),needsAegisKey:!e.apiKey,fee:n,providersFailed:s,providersError:a,unmatchedProviders:unmatchedUserProviders(r)}}if("local"===o){const e=(t.get("local")||{}).baseURL||c.DEFAULT_BASE,r=await c.probe(e);if(!r.running)return{class:o,models:[],baseURL:r.baseURL,needsDaemon:!0};let n=[],s=!0;try{n=await c.listTags(e)}catch{s=!1}return{class:o,models:n,baseURL:r.baseURL,listed:s}}if("pro"===o){const e=claudePro.claudeProStatus({env:process.env});return{class:o,models:claudePro.PRO_MODELS.map((t=>({id:t.id,label:t.label,note:t.note,configured:e.loggedIn}))),needsProviderKey:!1,needsAegisKey:!1,subscription:e.subscription,loggedIn:e.loggedIn,credentialFile:e.file,shadowed:e.shadowed||null,seam:claudePro.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(o)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:Y,cancel:z,respondApproval:function(e,t){const o=O.get(e);return o?(O.delete(e),o.resolve("session"===t||"once"===t||"always"===t?t:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,t){const o=N.get(e);return o?(N.delete(e),o.resolve(!0===t||"continue"===t),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){_.delete(e),S.delete(e),T.delete(e),x.delete(e);try{M.del(e,s)}catch{}return{ok:!0}},listUndoable:function(e){return(T.get(e)||[]).map((e=>({id:e.id,tool:e.tool,path:e.path,at:e.at}))).reverse()},undoMutation:function(e,t){const o=T.get(e)||[],r=t?o.findIndex((e=>e.id===t)):o.length-1;if(-1===r)return{ok:!1,error:t?`no undo record "${t}" for this conversation`:"nothing to undo in this conversation"};const n=o[r],s=U(n.path);if(!s||s.existed!==n.after.existed||s.content!==n.after.content)return{ok:!1,error:`${n.path} has changed since ${n.tool} ran — undo refused rather than overwriting work this session did not do. Resolve it by hand, or undo a different entry.`};try{n.before.existed?fs.writeFileSync(n.path,n.before.content,"utf8"):fs.unlinkSync(n.path)}catch(e){return{ok:!1,error:`undo failed: ${e&&e.message||e}`}}return o.splice(r,1),{ok:!0,path:n.path,restored:n.before.existed?"content":"deleted"}},settings:t,unloadLocalModels:function(){return c.unloadAll()},userModels:()=>loadUserModels(),addUserModel:(e,t)=>addUserModel(e,t),removeUserModel:(e,t)=>removeUserModel(e,t),discoverModels:async e=>{const t=String(null==e?"":e).trim().toLowerCase(),o=V(t),r=await discoverVendorModels(t,{key:o,fetchImpl:d});if(!r||!r.ok)return r;const n=[];try{const e=loadUserModels().map;for(const o of Array.isArray(e[t])?e[t]:[])n.push(o)}catch{}return{...r,declared:n,endpoint:(vendorEndpointFor(t)||{}).url||""}},modelSyncPlan:async e=>H(e),modelSyncApply:(e,t)=>modelSync.apply(e,{only:t}),modelAutoSync:X,modelAutoSyncRun:e=>X.runIfDue(e),modelAutoSyncStatus:()=>X.status(),addUserModels:(e,t)=>{const o=Array.isArray(t)?t:[],r={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const t of o)try{const o=addUserModel(e,t);r.file=o.file||r.file,o.added?r.added+=1:r.already.push(o.model)}catch(e){const n=e&&e.message||String(e);if(/the cap/.test(n)){r.capped=o.length-r.added-r.already.length-r.failed.length;break}r.failed.push({id:String(t),reason:n})}return r},canDiscoverModels:e=>canDiscoverVendorModels(e),discoverableProviders:()=>discoverableProviders()}}module.exports={CLASSES:CLASSES,createLocalEngine:createLocalEngine,extractToolCalls:extractToolCalls,parseArgs:parseArgs,reasoningBudget:reasoningBudget,nativeEffort:nativeEffort,hostEnv:hostEnv};
|
|
3
|
+
"use strict";const{randomUUID:randomUUID}=require("node:crypto"),os=require("node:os"),fs=require("node:fs"),toolsModule=require("./tools.js"),attachmentsModule=require("./attachments.js"),{flattenContent:flattenContent}=attachmentsModule,promptModule=require("./prompt.js"),localTransport=require("./local.js"),{ShellSession:ShellSession}=require("./shell.js"),{planExec:planExec}=require("./exec-plan.js"),claudePro=require("./claude-pro.js"),{agentSystemPrompt:agentSystemPrompt,agentRoleLabel:agentRoleLabel}=require("./agents.js"),{beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,blocksDestructive:blocksDestructive}=require("./turn-guard.js"),repeatGuard=require("./repeat-guard.js"),verifyGuard=require("./verify-stop.js"),{acquireWorktreeLock:acquireWorktreeLock,releaseWorktreeLock:releaseWorktreeLock}=require("./worktree-lock.js"),covenant=require("./covenant.js");let envFile=null;try{envFile=require("../../../client/env-file.js")}catch{try{envFile=require("../../vendor/env-file.js")}catch{envFile=null}}let platformLib=null;try{platformLib=require("../../../client/platform.js")}catch{try{platformLib=require("../../vendor/platform.js")}catch{platformLib=null}}let credentialsLib=null;try{credentialsLib=require("../../../client/credentials.js")}catch{try{credentialsLib=require("../../vendor/credentials.js")}catch{credentialsLib=null}}const PRO_TOOL_MAP=Object.freeze({Write:"writeFile",Edit:"editFile",MultiEdit:"editFile",NotebookEdit:"editFile",Bash:"exec",BashOutput:"exec"}),PRO_PLAN_MODE_SAFE=Object.freeze(new Set(["Read","Glob","Grep"]));function proAskArgs(e,t){const o=e&&"object"==typeof e?e:{};return"exec"===t?"string"==typeof o.command?{command:o.command}:{}:"writeFile"===t?"string"==typeof o.file_path?{file_path:o.file_path,content:o.content}:{}:"editFile"===t?Array.isArray(o.edits)?{file_path:o.file_path,edits:o.edits}:"string"==typeof o.file_path?{file_path:o.file_path,old_string:o.old_string,new_string:o.new_string,replace_all:!0===o.replace_all}:{}:o}function normalizeToolArgs(e,t,o,r){const n=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof toolsModule.normalizeArgs&&toolsModule.normalizeArgs||null;return n?n(t,o,r):{ok:!0,args:o&&"object"==typeof o?o:{},error:null}}function detectVcs(e){if(!e)return null;try{const t=require("node:fs"),o=require("node:path");let r=o.resolve(String(e));for(let e=0;e<8;e+=1){if(t.existsSync(o.join(r,".git")))return"git";const e=o.dirname(r);if(e===r)break;r=e}return""}catch{return null}}function hostEnv(e={},t={},o=null){const r=e||{},n=t||{},s=(e,t)=>null!=n[e]?n[e]:t;let a=r.homedir,i=r.cwd;try{a||(a=os.homedir()),i||(i=process.cwd())}catch{}let l=r.shell,c=r.shellKind;try{if(!l||!c){const e=require("./shell.js").resolveSessionShell();l=l||e.cmd,c=c||e.kind}}catch{}let d=r.desktopdir;try{!d&&platformLib&&(d=platformLib.desktopDir())}catch{}let u=r.dataDir;try{!u&&credentialsLib&&(u=credentialsLib.aegisHome())}catch{}let f=r.locale,p=r.localeName;try{!f&&platformLib&&"function"==typeof platformLib.appLocale&&(f=platformLib.appLocale()),f&&!p&&platformLib&&"function"==typeof platformLib.languageName&&(p=platformLib.languageName(f))}catch{}return{platform:s("platform",r.platform||process.platform),arch:s("arch",r.arch||process.arch),homedir:s("homedir",a),desktopdir:s("desktopdir",d),dataDir:s("dataDir",u),locale:s("locale",f),localeName:s("localeName",p),languages:s("languages",r.languages),cwd:s("cwd",i),vcs:s("vcs",null!=r.vcs?r.vcs:detectVcs(i)),shell:s("shell",l),shellKind:s("shellKind",c),roots:s("roots",r.roots),appVersion:s("appVersion",r.appVersion),model:s("model",o&&o.model)}}function requireSharedBrain(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedByokCatalog(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedUserModels(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedCatalogClient(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelDiscovery(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelSync(){const e=[()=>require("../../../client/model-sync.js"),()=>require("../../vendor/model-sync.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelAutoSync(){const e=[()=>require("../../../client/model-autosync.js"),()=>require("../../vendor/model-autosync.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`byok:${e}`}function splitByokModel(e){const t="string"==typeof e?e:"",o=t.indexOf(":");return o<0?{provider:"",model:t}:{provider:t.slice(0,o),model:t.slice(o+1)}}function providerKeyRecord(e){const t={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return t;try{const o=envFile.providerKeyFromEnv(e)||t;return{key:"string"==typeof o.key?o.key:"",env:"string"==typeof o.env?o.env:"",rejected:"string"==typeof o.rejected&&o.rejected?o.rejected:null}}catch{return t}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,t,o){const r=Number(t);return Number.isFinite(r)&&r>0?r:DEEPSEEK_REASONING_MODEL_RE.test(String(e||""))?EFFORT_TOKEN_BUDGET["low"===o||"medium"===o||"max"===o?o:"high"]:void 0}function nativeEffort(e,t,o){const r=String(t||"");if(EFFORT_INERT_RE.test(r))return;if(null===o)return;const n="low"===o||"medium"===o?o:"max"===o?"max":"high";for(const t of EFFORT_DIALECTS)if(t.provider===e&&t.re.test(r)){const e=Object.prototype.hasOwnProperty.call(t.map,n)?t.map[n]:t.extra&&Object.prototype.hasOwnProperty.call(t.extra,n)?t.extra[n]:void 0;if(void 0===e)return;return{field:t.field,level:e}}}function normalizeCatalog(e){return Array.isArray(e)?e.map(e=>"string"==typeof e?{id:e}:e).filter(e=>e&&e.id):[]}const{offerableCatalog:offerableCatalog}=requireSharedBrain(),{withByokAdditions:withByokAdditions,canonicalModelId:canonicalModelId,nexusFallbackModel:nexusFallbackModel}=requireSharedByokCatalog(),{withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders,load:loadUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel}=requireSharedUserModels(),{withCatalog:withCatalog}=requireSharedCatalogClient(),{discoverModels:discoverVendorModels,canDiscover:canDiscoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=requireSharedModelDiscovery(),modelSync=requireSharedModelSync(),{createModelAutoSync:createModelAutoSync}=requireSharedModelAutoSync();function parseArgs(e){if(null==e)return{};if("object"==typeof e)return e;try{const t=JSON.parse(String(e));return t&&"object"==typeof t?t:{}}catch{return{}}}function extractToolCalls(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map(e=>({id:e.id||"",name:e.name||"",args:parseArgs(e.args)})).filter(e=>e.name);const t=e.choices&&e.choices[0]&&e.choices[0].message,o=t&&t.tool_calls||[];return Array.isArray(o)?o.map(e=>{const t=e&&e.function||{};return{id:e&&e.id||"",name:t.name||e&&e.name||"",args:parseArgs(t.arguments)}}).filter(e=>e.name):[]}function proTurnPrompt(e){const t=Array.isArray(e.prompt)?flattenContent(e.prompt):e.prompt;if("string"==typeof t&&t.trim())return t;const o=Array.isArray(e.messages)?e.messages:[];for(let e=o.length-1;e>=0;e-=1){const t=o[e];if(!t||"user"!==t.role)continue;const r=flattenContent(t.content);if(r.trim())return r}return t}function assistantText(e){const t=e&&e.choices&&e.choices[0]&&e.choices[0].message;return t&&"string"==typeof t.content&&t.content||""}function finishReasonOf(e){const t=e&&e.choices&&e.choices[0];return t&&t.finish_reason||e&&e.stop_reason||""}function isTruncated(e){const t=finishReasonOf(e);return"length"===t||"max_tokens"===t}function reasoningTextOf(e){if(!e)return"";const t=e.choices&&e.choices[0],o=t&&t.message||{};if(Array.isArray(o.content)){const e=o.content.filter(e=>e&&("thinking"===e.type||"reasoning"===e.type)).map(e=>e.thinking||e.text||"").join("");if(e)return e}const r=o.content&&"object"==typeof o.content?o.content.reasoning_content:"",n=[o.reasoning_content,o.reasoning,t&&t.reasoning_content,e.reasoning_content,e.reasoning,r];for(const e of n)if("string"==typeof e&&e)return e;return""}function reasoningTokensOf(e){if(!e)return 0;const t=e.choices&&e.choices[0],o=t&&t.message||{},r=e.usage||{},n=r.completion_tokens_details||r.output_tokens_details||{},s=[o.thinking_tokens,o.reasoning_tokens,t&&t.thinking_tokens,e.thinking_tokens,n.reasoning_tokens,n.thinking_tokens];for(const e of s)if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;return 0}function reasonedButSilent(e){return!assistantText(e)&&(""!==reasoningTextOf(e)||reasoningTokensOf(e)>0)}const REASONING_RETRY_FLOOR=32768;function retryBudgetFor(e,t){const o=doubledBudget(e.maxTokens);return t&&ladderRung(e.maxTokens)?Math.max(o,32768):o}function ladderRung(e){const t=Number(e);return Number.isFinite(t)&&Object.values(EFFORT_TOKEN_BUDGET).includes(t)}function doubledBudget(e){const t=Number(e)||0;return t>0?2*t:8192}function statedCapOf(e){const t=e=>{const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?t(e.statedMaxTokens):t(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,t,o){if(t)return!1;if(!(o>0))return!1;const r=String(e||"");return!!r.trim()&&!/\?\s*$/.test(r.trim())&&MUTATION_INTENT_RE.test(r)}function emptyTurnError({cls:e,model:t,finishReason:o,reasoningChars:r,reasoningTokens:n,effort:s,recoveryRounds:a}){const i=Number(a)||0,l=Number(n)||0,c=new Error(`The model returned no answer after ${e}/${t} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${o||"none"}`+(s?`, effort: ${s}`:"")+(r?`, hidden reasoning: ${r} chars and no visible text`:l>0?`, ~${l} thinking tokens billed and no visible text`:"")+"). "+(r||l>0?"Every one of those calls spent its output on hidden reasoning instead of writing a word, so this is the model rather than the budget: pick a model that answers without a thinking pass, or ask for a smaller piece of work.":"No visible text came back from any of those calls. Send the request again, in smaller pieces, or from a different model."));return c.status=502,c}function createLocalEngine({aegis:e,settings:t,tools:o,promptBuilder:r,recallProvider:n,env:s,getConfirmMode:a,getPermissionMode:i,sandbox:l,localTransport:c=localTransport,fetchImpl:d,gitScope:u,permissionRules:f}){const p=new Map,m=o||toolsModule,h=r&&r.buildSystemPrompt||promptModule.buildSystemPrompt,y=f&&"function"==typeof f.rulesVerdict?f.rulesVerdict:null,g=f&&"function"==typeof f.alwaysAllow?f.alwaysAllow:null,k=f&&"function"==typeof f.subjectFor?f.subjectFor:null,v=require("./session-rounds.js"),b=()=>{if("function"==typeof a)return!1!==a();if(t&&"function"==typeof t.getConfirmMode){const e=t.getConfirmMode();return void 0===e||Boolean(e)}return!0},w=()=>"function"==typeof i?"plan"===i():!(!t||"function"!=typeof t.getPermissionMode)&&"plan"===t.getPermissionMode();function E(e,t){return`${e} was not executed — this session is in plan mode (read-only). Plan mode may read files, search, run read-only shell commands and deploy subagents to research, but may not create, edit or delete files, run a mutating command, or install packages`+(t?` (this command: ${t})`:"")+". Do NOT retry it or attempt the same effect by another route. Finish your research and present a plan in plain text; the user exits plan mode (`/permissions mode off`) before any edit can run."}const S=new Map,_=new Map,T=new Map,x=new Map,A=require("./pro-sessions.js"),M=new Map,O=new Map;function N(e,t){if("function"!=typeof k)return e;let o="";try{o=String(k(e,t||{})||"")}catch{o=""}return`${e}\0${o}`}function F(e,t,o){S.has(e)||S.set(e,new Set),S.get(e).add(N(t,o))}function D(e,t){const o=_.get(e);return Boolean(o&&o.has(t))}function R(e,t){_.has(e)||_.set(e,new Set),_.get(e).add(t)}function U(e){if(!e)return null;try{return{existed:!0,content:fs.readFileSync(e,"utf8")}}catch(e){return e&&"ENOENT"===e.code?{existed:!1,content:null}:null}}function I(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function L(e,t,o,r){return new Promise(n=>{if(o&&o.aborted)return void n("cancel");const s=randomUUID();let a=!1;const i=()=>l("cancel"),l=e=>{a||(a=!0,M.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),M.set(s,{resolve:l}),"function"==typeof t?t({delta:"",approval:{id:s,sessionId:e,tool:r.tool,args:r.args,diff:r.diff||null,canPersist:"function"==typeof g}}):l("cancel")})}function C(e,t,o,r){return new Promise(n=>{if(o&&o.aborted)return void n(!1);const s=randomUUID();let a=!1;const i=()=>l(!1),l=e=>{a||(a=!0,O.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),O.set(s,{resolve:l}),"function"==typeof t?t({delta:"",rounds:{id:s,sessionId:e,spent:r.spent,extensions:r.extensions,max:r.max,size:r.size}}):l(!1)})}async function P(e,t,o,r,n){const s=normalizeToolArgs(m,e,t,o||{});if(!s.ok)return{ok:!1,error:s.error};t=s.args;const a=o&&o.guard;if(a&&"exec"===e){const e=blocksDestructive(a,t&&t.command);if(!e.ok)return{ok:!1,error:e.reason}}const i=o&&o.repeat,l=i?repeatGuard.check(i,e,t):null;if(l&&"refuse"===l.action)return{ok:!1,error:l.error};const c=covenant.preActionAssert({tool:e,args:t||{}});if(!c.allowed){const o=covenant.bindRefusal({tool:e,args:t||{}},c);return{ok:!1,error:`refused by the ÆGIS covenant — ${c.clause} (${c.label}): ${c.reason}`,covenant:o}}const d="writeFile"===e||"editFile"===e,u=d?U(t&&t.file_path):null,f=await m.executeTool(e,t,o);a&&d&&f&&!1!==f.ok&&recordWrite(a,t&&t.file_path),i&&d&&f&&!1!==f.ok&&repeatGuard.recordWrite(i,t&&t.file_path);const p=o&&o.verify;if(p&&(verifyGuard.EXEC_TOOLS.has(e)&&f&&!1!==f.ok?verifyGuard.recordExec(p):d&&f&&!1!==f.ok&&verifyGuard.recordMutation(p,t&&t.file_path)),d&&u&&f&&!1!==f.ok){const o=U(t&&t.file_path);o&&function(e,t){if(!e)return;T.has(e)||T.set(e,[]);const o=T.get(e);o.push(t),o.length>200&&o.shift()}(r,{id:n||randomUUID(),tool:e,path:t&&t.file_path,before:u,after:o,at:Date.now()})}return l&&l.note?$(f,l.note):f}function $(e,t){if(!e||"object"!=typeof e)return{ok:!0,content:`${t}\n${null==e?"":e}`};if(!1===e.ok||!0===e.isError){const o=e.error||e.content||"";return{...e,error:`${t}\n${o}`,content:`${t}\n${o}`}}const o=null!=e.content?e.content:null!=e.output?e.output:"";return{...e,content:`${t}\n${o}`}}async function q(e,{toolCtx:t,rootSessionId:o,rootOnDelta:r,signal:n}){const{name:s}=e,a=normalizeToolArgs(m,s,e.args,t||{});if(!a.ok)return{ok:!1,error:a.error};const i=a.args;if(!m.MUTATING_TOOLS.has(s))return P(s,i,t,o,e.id);if(w()){if("exec"===s){const r=planExec(i&&i.command,{baseCwd:t&&t.cwd||void 0});return r.oneShot?P(s,i,t,o,e.id):{ok:!1,error:E(s,r.reason)}}return{ok:!1,error:E(s)}}if(!b())return P(s,i,t,o,e.id);if(function(e,t,o){const r=S.get(e);return Boolean(r&&r.has(N(t,o)))}(o,s,i))return P(s,i,t,o,e.id);if("function"==typeof y){let r;try{r=y(s,i)}catch(e){r={verdict:null,source:"error",error:e&&e.message||String(e)}}if(r&&"deny"===r.verdict)return R(o,s),{ok:!1,error:I(s),permissionRule:r.rule||null};if(r&&"allow"===r.verdict)return P(s,i,t,o,e.id)}if(D(o,s))return{ok:!1,error:I(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=m.previewMutation(s,i,t||{}),!l.ok))return{ok:!1,error:l.error};const c=await L(o,r,n,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return R(o,s),{ok:!1,error:I(s)};if("session"!==c&&"once"!==c&&"always"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};let d=null;if("always"===c){let e=null;if("function"==typeof g)try{e=g(s,i)}catch(t){e={ok:!1,reason:t&&t.message||String(t)}}else e={ok:!1,reason:"no durable store is wired on this host"};d=e&&e.ok?`[permission_rule] stored ${e.rule} — this command will not ask again`:`[permission_rule] nothing was stored — ${e&&e.reason||"unknown reason"}; this call was allowed once only`}if("session"===c&&F(o,s,i),l){const e=m.applyChecked(s,i,l,t||{});return e&&!1!==e.ok&&t&&t.guard&&recordWrite(t.guard,i&&i.file_path),d?$(e,d):e}const u=await P(s,i,t,o,e.id);return d?$(u,d):u}function j(e){return hostEnv(s||{},e&&e.env||{},e)}function B(e){const t=[],o=e=>String(e||"").replace(/[\\/]+$/,""),r=o(e),n=e=>{const n=o(e);n&&n!==r&&!t.includes(n)&&t.push(n)};let s=u;if(void 0===s)try{s=require("./git-scope.js")}catch{s=null}try{s&&"function"==typeof s.gitRoot&&n(s.gitRoot(e))}catch{}try{credentialsLib&&"function"==typeof credentialsLib.aegisHome&&n(credentialsLib.aegisHome())}catch{}return t}async function G(t,o){if("aegis"===t){const t=!o.singlePass&&(!!o.autonomous||void 0);return e.chatCompletion({prompt:o.prompt,system:o.system,messages:o.messages,model:o.model,mode:o.mode,maxTokens:o.statedMaxTokens,stream:!1!==o.stream,includeUsage:!0,onStream:o.onDelta,onReasoning:o.onReasoning,idleTimeoutMs:o.idleTimeoutMs,signal:o.signal,extra:{aegis_recall:!0,...o.recallDeep?{aegis_recall_deep:!0}:{},session:o.sessionId,...void 0===t?{}:{brain:t},...!1===t?{mode:"brain"}:{},...o.effort?{effort:o.effort}:{},...!0===t&&o.workers?{workers:o.workers}:{},...o.tools.length?{tools:o.tools}:{},...o.toolChoice?{tool_choice:o.toolChoice}:{}},agentKey:o.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===t){const{provider:t,model:r}=splitByokModel(o.model),n=canonicalModelId(t,r),s=nativeEffort(t,n,o.effort);try{return await e.byokChatCompletion({provider:t,model:n,providerKey:o.apiKey,baseURL:o.cfg&&o.cfg.baseURL,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,tools:o.tools,toolChoice:o.toolChoice,effort:s&&"effort"===s.field?s.level:void 0,reasoningEffort:s&&"reasoning_effort"===s.field?s.level:void 0,stream:!0,onStream:o.onDelta,signal:o.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===t){const e=o.cfg&&o.cfg.baseURL||c.DEFAULT_BASE,t=t=>c.chat({baseURL:e,model:o.model,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,signal:o.signal,onDelta:o.onDelta,...t&&o.tools.length?{tools:o.tools,toolChoice:o.toolChoice}:{}});try{return await t(!0)}catch(e){if(o.tools.length&&e&&400===e.status)return t(!1);throw e}}if("pro"===t){const e=o.sessionKey||o.rootSessionId||o.sessionId;let t=null;if(e&&(t=x.get(e)||null,!t)){try{t=A.get(e,s)||null}catch{}t&&x.set(e,t)}const r=B(o.cwd),n=e=>claudePro.runClaudePro({prompt:proTurnPrompt(o),model:o.model&&"default"!==o.model?o.model:void 0,system:o.system,cwd:o.cwd,addDir:r,resumeSessionId:e||void 0,gate:b(),onAsk:async e=>{if(!e||!e.requestId)return"deny";const t=o.rootSessionId,r=o.rootOnDelta,n=PRO_TOOL_MAP[String(e.toolName||"")]||null,s=n||String(e.toolName||"unknown"),a=proAskArgs(e.input||{},s),i=covenant.preActionAssert({tool:s,args:a});if(!i.allowed)return r&&r({delta:"",note:`aegis: refused by the ÆGIS covenant — ${i.clause} (${i.label}): ${i.reason}`}),"deny";if(w()){if("exec"===s){const e=planExec(a&&a.command,{baseCwd:o.cwd||void 0});return e.oneShot?"once":(r&&r({delta:"",note:E(s,e.reason)}),"deny")}if(n&&m.MUTATING_TOOLS.has(s))return r&&r({delta:"",note:E(s)}),"deny";if(!n&&!PRO_PLAN_MODE_SAFE.has(s))return r&&r({delta:"",note:E(s)}),"deny"}if(!b())return"once";if("function"==typeof y){let e;try{e=y(s,a)}catch{e=null}if(e&&"deny"===e.verdict)return r&&r({delta:"",note:I(s)}),"deny";if(e&&"allow"===e.verdict)return"once"}if(D(t,s))return r&&r({delta:"",note:I(s)}),"deny";const l=await L(t,r,o.signal,{tool:s,args:a,diff:null});if("deny"===l)return R(t,s),"deny";if("session"!==l&&"once"!==l&&"always"!==l)return"deny";if("session"===l&&F(t,s,a),"always"===l&&"function"==typeof g)try{g(s,a)}catch{}return l},signal:o.signal,onDelta:o.onDelta,onSpawn:(e,t)=>{o.onDelta&&t&&o.onDelta({delta:"",note:claudePro.childLine(t)})}});let a=await n(t);if(a&&a.resumeStale){x.delete(e);try{A.del(e,s)}catch{}o.onDelta&&o.onDelta({delta:"",note:"aegis: the remembered Claude session no longer exists on this machine — continuing as a new conversation (earlier turns are not in its context)"}),a=await n(null)}if(e&&a&&a.sessionId&&!a.error){x.set(e,a.sessionId);try{A.set(e,a.sessionId,s)}catch{}}return a}throw new Error(`dispatch: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function K(o,r){const s=o&&o.class,a=o&&o.model,i=reasoningBudget("byok"===s?splitByokModel(a).model:a,o&&o.maxTokens,o&&o.effort),d=statedCapOf(o),u="aegis"===s&&Boolean(o&&o.autonomous),f=Boolean(o&&o.roundsAsk),y=o&&o.sessionId||randomUUID(),g=Number.isInteger(o&&o.depth)?o.depth:0,k=o&&o.rootSessionId||y,b=o&&o.rootOnDelta||r,w="function"==typeof r?e=>e&&r({reasoning:e}):void 0,E=new AbortController,S=p.get(y)||null;p.set(y,E);const _=E.signal,T=!(o&&!1===o.tools),x=T?m.toolsFor({includeSubagent:g<4}):[],A=o&&o.toolChoice||null,M=o&&o.system||h(j(o)),O=n?await n({payload:o,env:j(o),system:M}):null,N="string"==typeof O?O:O&&"string"==typeof O.system?O.system:M,F=Array.isArray(o&&o.messages)?o.messages.filter(Boolean).slice():[];let D=F.length,R=o&&o.prompt||"";const U=String(R||""),I=Array.isArray(o&&o.attachments)?o.attachments.filter(e=>e&&"object"==typeof e).slice(0,attachmentsModule.MAX_ATTACHMENTS):[];let L=I.length?attachmentsModule.buildContent(R,I):R,P=null;const $=j(o),K=((e,t)=>{if(null==l)return null;const o="function"==typeof l.policy?l.policy():l.policy;if(!o)return null;const r=require("./sandbox.js"),n=e&&e.cwd||process.cwd(),s=r.normalize(o,n);if("off"===s.mode)return null;let a=[];try{let e=null;try{e=require("node:os").homedir()}catch{e=null}a=r.autoGrants(n,{home:e,addDirs:(()=>{try{return B(n)}catch{return[]}})()})}catch{a=[]}if(a.length){const e=new Set;for(const t of s.fileSystem.entries)t&&t.path&&"path"===t.path.type&&t.path.path&&e.add(`${t.access}:${t.path.path}`);for(const t of a){const o=`${t.access}:${t.path.path}`;e.has(o)||(e.add(o),s.fileSystem.entries.push(t))}}return"local"===t&&"restricted"===s.network&&(s.network="open",s.networkExempt="local"),{policy:s,state:l.state||r.detect({appDir:l.appDir}),workspace:n,appDir:l.appDir,strict:!0===l.strict}})($,s),W=$.cwd,z={getShell:()=>P||(P=new ShellSession({cwd:$.cwd,sandbox:K})),signal:_,cwd:W,desktopdir:$.desktopdir,sandbox:K,repeat:repeatGuard.beginRepeatGuard({cwd:W}),verify:verifyGuard.beginVerifyGuard({cwd:W}),guard:beginTurnGuard(W)};try{const n="byok"===s?splitByokModel(a):null;let l=null;const p="byok"===s?t.get(byokNamespace(n.provider))||{}:"local"===s&&t.get("local")||{},h="byok"===s?t.rawKey(byokNamespace(n.provider)):null,E="byok"!==s?null:h||providerKeyFromEnv(n.provider);if(!("byok"!==s||n.provider&&n.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(a||""));throw e.status=400,e}if("byok"===s&&!E){const t="anthropic"===n.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(n.provider).rejected,r=nexusFallbackModel({provider:n.provider,providerKey:E,providerKeyRefused:o,aegisKey:E?"":e.apiKey});if(!r){const e=new Error(o?`${o}. That is why this turn has no ${n.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${o.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${n.provider} <key> to set one here.`:t&&t.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${t.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${n.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${n.provider} <key>.`);throw e.status=400,e}l={from:n.provider,model:r}}if("byok"===s&&!e.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===s){const e=c.remoteRefusal(p.baseURL||c.DEFAULT_BASE);if(e)throw e}if("byok"===s&&"custom"===n.provider&&!(p.baseURL||"").trim()){const e=new Error('No endpoint saved for the "custom" provider — its key is on this machine but the address it dials is not, and no default exists for a vendor AEGIS does not know. Fix: /model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const S=l?"aegis":s,M={cls:S,model:l?l.model:a,mode:o&&o.mode,maxTokens:i,statedMaxTokens:d,autonomous:u,sessionId:y,signal:_,onDelta:r,cfg:p,apiKey:E,toolChoice:A,pooledFrom:l?l.from:void 0,cwd:W,rootSessionId:k,sessionKey:o&&o.sessionKey||void 0,rootOnDelta:b,effort:o&&o.effort,workers:o&&o.workers,recallDeep:o&&!0===o.recallDeep,singlePass:o&&!0===o.singlePass,onReasoning:w,idleTimeoutMs:u?9e5:void 0,stream:!o||!1!==o.stream};let O=!1,P=!1;const $=u?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",j=(()=>{const e=Number.parseInt(process.env[$]||"",10);return Number.isFinite(e)&&e>0?e:0})(),B=j||(u?40:24);let K=v.keyFor(o,F),V=v.take(K);if(!V&&!v.isStatedKey(o)){const e=v.adopt();e&&(V=e.entry,K=e.key)}if(V){const e=v.resumePreamble(V);0===F.length?Array.isArray(V.messages)&&V.messages.length&&F.push(...V.messages):Array.isArray(V.added)&&V.added.length&&F.push(...V.added),R?(R=`${e}\n\n${R}`,L=I.length?attachmentsModule.buildContent(R,I):R):(F.push({role:"user",content:e}),L=""),b&&b({delta:`\n\n[resuming work this session left unfinished at ${V.rounds} tool rounds`+(V.interruptions>1?` (cut off ${V.interruptions}×)`:"")+"…]\n"})}let H=j||B+(V?v.bonus(B):0),X=0;const J=B,Q=8;let Z=0;const ee={calls:0},te=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],oe=e=>{const t=e&&e.usage;if(t&&"object"==typeof t){ee.calls+=1;for(const e of te)"number"==typeof t[e]&&Number.isFinite(t[e])&&(ee[e]=(ee[e]||0)+t[e]);if("number"!=typeof t.total_tokens){const e=(t.prompt_tokens??t.input_tokens??0)+(t.completion_tokens??t.output_tokens??0);e&&(ee.total_tokens=(ee.total_tokens||0)+e)}}},re=e=>{if(!e||"object"!=typeof e)return e;const t=l?{...e,pooled_from:l.from,pooled_model:l.model,pooled_notice:requireSharedByokCatalog().nexusFallbackNotice({pooled_from:l.from,pooled_model:l.model})}:e;return ee.calls?{...t,usage:{...ee}}:t},ne=()=>{if(""===L)return;const e=F[F.length-1],t=e&&"user"===e.role?flattenContent(e.content):null;e&&"user"===e.role&&t===flattenContent(L)||F.push({role:"user",content:L}),R="",L=""};D=F.length;const se=m&&m.MUTATING_TOOLS||new Set;let ae=0,ie=0,le=!1,ce=!1;for(;;){if(X>=H){if(f&&Z<Q&&!_.aborted&&await C(k,b,_,{spent:H,extensions:Z+1,max:Q,size:J})){Z+=1;const e=H;H+=J,F.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${J} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=f?"":`, or raise ${$} for a longer single turn`,t=`[stopped at ${H} tool rounds`+(ee.total_tokens?`, ${ee.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,o=v.record(K,{rounds:X,tokens:ee.total_tokens||0,note:t,chain:V?V.interruptions:0,messages:F,added:F.slice(D)});return b&&b({delta:`\n\n${t}`}),re({model:M.model,choices:[{message:{content:t},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:o.rounds,sessionInterruptions:o.interruptions,resumedFrom:K})}X+=1;const e={...M,system:N,messages:F,prompt:L,tools:x,recallDeep:M.recallDeep&&1===X};let t;if(t=await G(S,e),oe(t),_.aborted)return re(t);if(!O&&!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){O=!0;const o=reasonedButSilent(t);if(t=await G(S,{...e,singlePass:!0,recallDeep:!1,effort:o?"high":e.effort,maxTokens:retryBudgetFor(e,o),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}const n=x.length?extractToolCalls(t):[];if(!n.length){if(assistantText(t)||P||!T){if(!le&&T&&wantsMutation(U,ie>0,ae)){le=!0,ne(),F.push({role:"assistant",content:assistantText(t)}),F.push({role:"user",content:UNMUTATED_TURN_NUDGE}),b&&b({delta:""});continue}if(z.verify&&!ce){const e=verifyGuard.shouldNudge(z.verify);if(e.nudge){ce=!0,ne(),F.push({role:"assistant",content:assistantText(t)}),F.push({role:"user",content:e.text}),b&&b({delta:""});continue}}return re(t)}P=!0,ne(),F.push({role:"user",content:reasonedButSilent(t)?THOUGHT_ONLY_NUDGE:EMPTY_TURN_NUDGE});const o={...e,singlePass:!0,recallDeep:!1,messages:F,prompt:"",tools:[]};t=await G(S,o);let r=o.maxTokens,n=o.effort;if(oe(t),_.aborted)return re(t);if(!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){const e=reasonedButSilent(t);if(r=retryBudgetFor(o,e),n=e?"high":o.effort,t=await G(S,{...o,effort:n,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}const i=(()=>{const e=Number(r)||0;if(!e)return r;const t={maxTokens:r};return o.statedMaxTokens&&(t.statedMaxTokens=o.statedMaxTokens),Math.max(e,retryBudgetFor(t,!0))})();let l=0;for(;!assistantText(t)&&l<2&&!_.aborted;){const e=reasonedButSilent(t);if(l+=1,F.push({role:"user",content:e?1===l?THOUGHT_ONLY_NUDGE:FINAL_ANSWER_NUDGE:EMPTY_TURN_NUDGE}),e&&(n="high"),r=i,t=await G(S,{...o,messages:F,effort:n,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}if(!assistantText(t))throw emptyTurnError({cls:s,model:a,effort:n,recoveryRounds:l,finishReason:finishReasonOf(t),reasoningChars:reasoningTextOf(t).length,reasoningTokens:reasoningTokensOf(t)});return re(t)}ne(),F.push({role:"assistant",content:assistantText(t),tool_calls:n.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}}))});const i=new WeakMap,l=e=>{if("exec"!==e.name)return null;if(i.has(e))return i.get(e);const t=planExec(e.args&&e.args.command,{baseCwd:W});return i.set(e,t),t},c=e=>{if(!se.has(e.name))return!0;const t=l(e);return Boolean(t&&t.oneShot)},u=[];for(const e of n){const t=u[u.length-1];c(e)&&t&&t.parallel?t.calls.push(e):u.push({parallel:c(e),calls:[e]})}const p=async e=>{r&&r({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:W,phase:"run"}});const t=l(e),n=t&&t.oneShot?{...z,oneShotExec:!0,cwd:t.cwd||z.cwd}:z,i=e.name===m.SUBAGENT_TOOL?await Y(e.args,{cls:s,model:a,statedMaxTokens:d,effort:o&&o.effort,mode:o&&o.mode,parentSignal:_,depth:g,rootSessionId:k,rootOnDelta:b}):await q(e,{toolCtx:n,rootSessionId:k,rootOnDelta:b,signal:_});return i&&i.usage&&oe({usage:i.usage}),r&&r({delta:"",tool:{name:e.name,args:e.args,ok:i.ok,id:e.id,cwd:W,phase:"done"}}),i};for(const e of u){const t=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map(e=>p(e))):[await p(e.calls[0])];e.calls.forEach((e,o)=>{const r=t[o];se.has(e.name)&&(ae+=1,r&&r.ok&&(ie+=1)),F.push({role:"tool",tool_call_id:e.id,name:e.name,content:m.toolResultText(r)})})}}}catch(e){throw _.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{P&&P.dispose(),p.get(y)===E&&(S&&!S.signal.aborted?p.set(y,S):p.delete(y))}}async function Y({description:e,subagent_type:t,prompt:o}={},{cls:r,model:n,statedMaxTokens:s,effort:a,mode:i,parentSignal:l,depth:c,rootSessionId:d,rootOnDelta:u}={}){const f=String(o||e||"").trim();if(!f)return{ok:!1,error:"task requires a prompt"};const p=t&&"general"!==t?agentRoleLabel(t):"general",m=agentSystemPrompt(t),h=randomUUID();let y;if(l){if(l.aborted)return{ok:!1,error:"aborted"};y=()=>W(h),l.addEventListener("abort",y,{once:!0})}try{const e=await K({class:r,model:n,mode:i,system:m,prompt:f,sessionId:h,depth:(c||0)+1,rootSessionId:d,rootOnDelta:u,statedMaxTokens:s,effort:a},()=>{}),t=assistantText(e),o=e&&e.usage?{usage:e.usage}:{};return t?{ok:!0,output:t,...o}:{ok:!1,error:`subagent (${p}) produced no output`,...o}}catch(e){return{ok:!1,error:`subagent (${p}) failed: ${e&&e.message?e.message:e}`}}finally{l&&y&&l.removeEventListener("abort",y)}}function W(e){const t=p.get(e);return t&&t.abort(),{ok:Boolean(t)}}function z(e){const o=String(null==e?"":e).trim().toLowerCase();if(!o)return"";try{if(t&&"function"==typeof t.rawKey){const e=t.rawKey(byokNamespace(o));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(o)}async function V(t){let o=[];try{const t=await e.byokProviders();o=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[])))}catch(e){return{ok:!1,providers:[],missing:0,stale:0,skipped:[],failed:[],error:e&&e.message||String(e)}}const r={};for(const e of modelSync.askableProviders(o,t)){const t=z(e);t&&(r[e]=t)}return modelSync.plan(o,{keys:r,fetchImpl:d,only:t})}const H=createModelAutoSync({getPref:()=>{try{return t&&"function"==typeof t.getSharedPref?t.getSharedPref("modelAutoSync"):null}catch{return null}},plan:e=>V(e),apply:(e,t)=>modelSync.apply(e,{only:t})});return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map(o=>{if("aegis"===o.class)return{...o,configured:Boolean(e.apiKey)};if("byok"===o.class){const e=(t.list()||[]).some(e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(5)))));return{...o,configured:e}}if("local"===o.class)return{...o,configured:!0};if("pro"===o.class){const e=claudePro.claudeProStatus({env:process.env}),t=claudePro.seamAvailable();return{...o,configured:e.loggedIn,status:e,seam:t}}return{...o,configured:!1}})},listModels:async function(o){if("aegis"===o){if(!e.apiKey)return{class:o,models:[],needsKey:!0};const t=await e.listModels();return{class:o,models:offerableCatalog(normalizeCatalog(t&&t.models))}}if("byok"===o){let r=[],n=null,s=!1,a=null;try{const t=await e.byokProviders();r=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[]))),n=t&&t.fee||null}catch(e){r=[],s=!0,a=e&&e.message||String(e)}const i=[];for(const e of r){if(!e||!e.id)continue;const o=t.get(byokNamespace(e.id))||{},r=providerKeyRecord(e.id),n=r.key||"",s=Array.isArray(e.models)?e.models:[];for(const t of s){const s="string"==typeof t?t:t&&t.id;s&&i.push({id:`${e.id}:${s}`,label:`${e.label||e.id} — ${s}`,provider:e.id,configured:Boolean(o.configured||n),keyRejected:r.rejected||null})}}return{class:o,models:i,providers:r,needsProviderKey:i.length>0&&!i.some(e=>e.configured),needsAegisKey:!e.apiKey,fee:n,providersFailed:s,providersError:a,unmatchedProviders:unmatchedUserProviders(r)}}if("local"===o){const e=(t.get("local")||{}).baseURL||c.DEFAULT_BASE,r=await c.probe(e);if(!r.running)return{class:o,models:[],baseURL:r.baseURL,needsDaemon:!0};let n=[],s=!0;try{n=await c.listTags(e)}catch{s=!1}return{class:o,models:n,baseURL:r.baseURL,listed:s}}if("pro"===o){const e=claudePro.claudeProStatus({env:process.env});return{class:o,models:claudePro.PRO_MODELS.map(t=>({id:t.id,label:t.label,note:t.note,configured:e.loggedIn})),needsProviderKey:!1,needsAegisKey:!1,subscription:e.subscription,loggedIn:e.loggedIn,credentialFile:e.file,shadowed:e.shadowed||null,seam:claudePro.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(o)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:K,cancel:W,respondApproval:function(e,t){const o=M.get(e);return o?(M.delete(e),o.resolve("session"===t||"once"===t||"always"===t?t:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,t){const o=O.get(e);return o?(O.delete(e),o.resolve(!0===t||"continue"===t),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){S.delete(e),_.delete(e),T.delete(e),x.delete(e);try{A.del(e,s)}catch{}return{ok:!0}},listUndoable:function(e){return(T.get(e)||[]).map(e=>({id:e.id,tool:e.tool,path:e.path,at:e.at})).reverse()},undoMutation:function(e,t){const o=T.get(e)||[],r=t?o.findIndex(e=>e.id===t):o.length-1;if(-1===r)return{ok:!1,error:t?`no undo record "${t}" for this conversation`:"nothing to undo in this conversation"};const n=o[r],s=U(n.path);if(!s||s.existed!==n.after.existed||s.content!==n.after.content)return{ok:!1,error:`${n.path} has changed since ${n.tool} ran — undo refused rather than overwriting work this session did not do. Resolve it by hand, or undo a different entry.`};try{n.before.existed?fs.writeFileSync(n.path,n.before.content,"utf8"):fs.unlinkSync(n.path)}catch(e){return{ok:!1,error:`undo failed: ${e&&e.message||e}`}}return o.splice(r,1),{ok:!0,path:n.path,restored:n.before.existed?"content":"deleted"}},settings:t,unloadLocalModels:function(){return c.unloadAll()},userModels:()=>loadUserModels(),addUserModel:(e,t)=>addUserModel(e,t),removeUserModel:(e,t)=>removeUserModel(e,t),discoverModels:async e=>{const t=String(null==e?"":e).trim().toLowerCase(),o=z(t),r=await discoverVendorModels(t,{key:o,fetchImpl:d});if(!r||!r.ok)return r;const n=[];try{const e=loadUserModels().map;for(const o of Array.isArray(e[t])?e[t]:[])n.push(o)}catch{}return{...r,declared:n,endpoint:(vendorEndpointFor(t)||{}).url||""}},modelSyncPlan:async e=>V(e),modelSyncApply:(e,t)=>modelSync.apply(e,{only:t}),modelAutoSync:H,modelAutoSyncRun:e=>H.runIfDue(e),modelAutoSyncStatus:()=>H.status(),addUserModels:(e,t)=>{const o=Array.isArray(t)?t:[],r={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const t of o)try{const o=addUserModel(e,t);r.file=o.file||r.file,o.added?r.added+=1:r.already.push(o.model)}catch(e){const n=e&&e.message||String(e);if(/the cap/.test(n)){r.capped=o.length-r.added-r.already.length-r.failed.length;break}r.failed.push({id:String(t),reason:n})}return r},canDiscoverModels:e=>canDiscoverVendorModels(e),discoverableProviders:()=>discoverableProviders()}}module.exports={CLASSES:CLASSES,createLocalEngine:createLocalEngine,extractToolCalls:extractToolCalls,parseArgs:parseArgs,reasoningBudget:reasoningBudget,nativeEffort:nativeEffort,hostEnv:hostEnv};
|
|
@@ -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 FREE_MAX_WORKERS=1,PAID_PLANS=Object.freeze(["pro","unlimited"]),TIER_NAMES=Object.freeze({pro:"Pro",unlimited:"Unlimited"});function tierName(e){return TIER_NAMES[normalizePlan(e)]||null}const LEGACY_PLAN_ALIASES=Object.freeze({cloud:"pro",memory:"pro",s:"pro",heavy:"pro",team:"pro",starter:"free"}),PRO_VALUE="Pro puts the drain in the cloud, so the job keeps running after you close the laptop",FREE_HONESTY="Everything on your machine is free, permanently. The cloud drain is what you pay for.",BYOK_FEE_NOTE="Bring your own key is relayed through AEGIS, not dialled from here — the routing, prompt assembly and caching are billed as a flat handling fee, on top of your provider's own bill.";function ratePerMillion(e){return`$${(1e3*Number(e)).toFixed(2)}/M`}function byokFeeLine(e){const n=e&&"object"==typeof e?e:null;if(!n)return"";const r=Number(n.in_usd_per_1k),a=Number(n.out_usd_per_1k);if(!Number.isFinite(r)||!Number.isFinite(a))return"";if(!0===n.disabled)return"Bring your own key is relayed free on this deployment right now.";const o=`Bring your own key: relayed through AEGIS, handled at ${ratePerMillion(r)} in / ${ratePerMillion(a)} out, on top of your provider's bill — no fee at all on Unlimited, and no fee at all during the free 1-month Unlimited trial`;let l="";if(!0===n.require_account)l="and needs an AEGIS account key (X-AEGIS-Key) for the fee to be billed";else{const e=Number(n.anonymous_daily_calls);Number.isFinite(e)&&e>0&&(l=`with ${e} relayed turns/24h before an AEGIS account is required`)}return l?`${o} — ${l}.`:`${o}.`}const CAMPAIGN="queue_cap",UPGRADE_URL="https://aegiscloud.org/go/upgrade?s=desktop&c=queue_cap",BALANCE_CAMPAIGN="topup_bank",BALANCE_URL="https://aegiscloud.org/go/topup?s=desktop&c=topup_bank",SIGNUP_SOURCES=Object.freeze(["desktop","cli","mcp"]),DEFAULT_HOST="desktop";function goUrl(e,n,r){const a=String(null==r?"":r).trim().toLowerCase(),o=SIGNUP_SOURCES.includes(a)?a:
|
|
3
|
+
"use strict";const FREE_MAX_WORKERS=1,PAID_PLANS=Object.freeze(["pro","unlimited"]),TIER_NAMES=Object.freeze({pro:"Pro",unlimited:"Unlimited"});function tierName(e){return TIER_NAMES[normalizePlan(e)]||null}const LEGACY_PLAN_ALIASES=Object.freeze({cloud:"pro",memory:"pro",s:"pro",heavy:"pro",team:"pro",starter:"free"}),PRO_VALUE="Pro puts the drain in the cloud, so the job keeps running after you close the laptop",FREE_HONESTY="Everything on your machine is free, permanently. The cloud drain is what you pay for.",BYOK_FEE_NOTE="Bring your own key is relayed through AEGIS, not dialled from here — the routing, prompt assembly and caching are billed as a flat handling fee, on top of your provider's own bill.";function ratePerMillion(e){return`$${(1e3*Number(e)).toFixed(2)}/M`}function byokFeeLine(e){const n=e&&"object"==typeof e?e:null;if(!n)return"";const r=Number(n.in_usd_per_1k),a=Number(n.out_usd_per_1k);if(!Number.isFinite(r)||!Number.isFinite(a))return"";if(!0===n.disabled)return"Bring your own key is relayed free on this deployment right now.";const o=`Bring your own key: relayed through AEGIS, handled at ${ratePerMillion(r)} in / ${ratePerMillion(a)} out, on top of your provider's bill — no fee at all on Unlimited, and no fee at all during the free 1-month Unlimited trial`;let l="";if(!0===n.require_account)l="and needs an AEGIS account key (X-AEGIS-Key) for the fee to be billed";else{const e=Number(n.anonymous_daily_calls);Number.isFinite(e)&&e>0&&(l=`with ${e} relayed turns/24h before an AEGIS account is required`)}return l?`${o} — ${l}.`:`${o}.`}const CAMPAIGN="queue_cap",UPGRADE_URL="https://aegiscloud.org/go/upgrade?s=desktop&c=queue_cap",BALANCE_CAMPAIGN="topup_bank",BALANCE_URL="https://aegiscloud.org/go/topup?s=desktop&c=topup_bank",SIGNUP_SOURCES=Object.freeze(["desktop","cli","mcp"]),DEFAULT_HOST="desktop";function goUrl(e,n,r){const a=String(null==r?"":r).trim().toLowerCase(),o=SIGNUP_SOURCES.includes(a)?a:"desktop";return`https://aegiscloud.org/go/${String(e).trim().toLowerCase()}?s=${o}&c=${n}`}function promptUrlFor(e){return{upgrade:goUrl("upgrade",CAMPAIGN,e),balance:goUrl("topup","topup_bank",e)}}const DEFAULT_TTL_MS=6e4;function normalizePlan(e){const n=String(null==e?"":e).trim().toLowerCase();return n?PAID_PLANS.includes(n)?n:LEGACY_PLAN_ALIASES[n]||"free":"free"}const ASK_EXAMPLE="Do X autonomously";function isPaidPlan(e){return"free"!==normalizePlan(e)}function fanoutRefusal(){return`Fan-out needs Pro: ${PRO_VALUE}. Write it in the message: "${ASK_EXAMPLE}". Unlock: Pro, or any Token Bank balance. Free keeps the local drain on your own key — one worker per task, while this window is open.`}function balanceRefusal(){return`Your AEGIS balance is empty — ${PRO_VALUE}. Write it in the message: "${ASK_EXAMPLE}". Unlock: top up the Token Bank, or upgrade to Pro. Local drains stay free: one worker per task, on your own key, while this window is open.`}function balanceOf(e){if(!e||"object"!=typeof e)return{balanceKnown:!1,balanceMicros:null};let n=null;return null!=e.balance_micros?n=Number(e.balance_micros):null!=e.balance_eur&&(n=1e6*Number(e.balance_eur)),null!=n&&Number.isFinite(n)?{balanceKnown:!0,balanceMicros:Math.trunc(n)}:{balanceKnown:!1,balanceMicros:null}}function classifyProbe(e,n){if(n){const e=balanceOf(n&&n.data),r=n.status,a=n&&n.data||{},o=String(a.error||a.code||""),l=String(n&&n.message||"");return 400===r||401===r||/api_key required|invalid api key|unauthor/i.test(`${o} ${l}`)?{source:"no-key",plan:"free",degraded:!1,...e}:{source:"unreachable",plan:"free",degraded:!0,...e}}const r=e&&"object"==typeof e?e:{},a=balanceOf(r);if(!1===r.valid)return{source:"no-key",plan:"free",degraded:!1,...a};const o=null!=r.plan_effective&&String(r.plan_effective).trim()?r.plan_effective:r.plan,l=String(null==o?"":o).trim();return l?{source:"server-plan",plan:normalizePlan(l),degraded:!1,...a}:{source:"no-plan-field",plan:"free",degraded:!0,...a}}function createEntitlement({probe:e,now:n=Date.now,ttlMs:r=6e4,host:a="desktop"}={}){const o=promptUrlFor(a);let l=Object.freeze({pro:!1,entitled:!1,balanceKnown:!1,balanceMicros:null,balanceZero:!1,wall:"plan",plan:"free",tier:null,tierName:null,planRaw:null,maxWorkers:1,source:"unresolved",degraded:!0,checkedAt:null,campaign:CAMPAIGN,host:SIGNUP_SOURCES.includes(String(a).toLowerCase())?String(a).toLowerCase():"desktop",upgradeUrl:o.upgrade,refusal:null}),t=null;function i({source:e,plan:r,degraded:a,planRaw:l,balanceKnown:t=!1,balanceMicros:i=null}){const u=normalizePlan(r),c="free"!==u,s=t&&Number.isFinite(i)&&i>0,p=c||s,d=t&&!s,f=p?null:d?"balance":"plan";return Object.freeze({pro:c,entitled:p,balanceKnown:Boolean(t),balanceMicros:t?i:null,balanceZero:d,wall:f,plan:c?u:"free",tier:c?u:null,tierName:c&&TIER_NAMES[u]||null,planRaw:null==l?null:String(l),maxWorkers:p?null:1,source:e,degraded:Boolean(a),checkedAt:n(),campaign:"balance"===f?"topup_bank":CAMPAIGN,upgradeUrl:"balance"===f?o.balance:o.upgrade,refusal:p?null:"balance"===f?balanceRefusal():fanoutRefusal()})}return{refresh:async function({force:a=!1}={}){if(null!=l.checkedAt&&n()-l.checkedAt<r&&!a)return l;if(t)return t;t=(async()=>{if("function"!=typeof e)return l=i({source:"no-probe",plan:"free",degraded:!0}),l;try{const n=await e(),r=classifyProbe(n,null);l=i({...r,planRaw:n&&n.plan})}catch(e){const n=classifyProbe(null,e);l=i(n)}return l})();try{return await t}finally{t=null}},current:function(){return l},gateFanout:function({workers:e,fanout:n}={}){const r=Number.isInteger(e)?e:null;return!0===n||null!=r&&r>1?l.entitled?{ok:!0,workers:r,fanout:!0}:{ok:!1,code:"balance"===l.wall?"fanout_requires_balance":"fanout_requires_pro",reason:l.refusal||fanoutRefusal(),campaign:l.campaign,upgradeUrl:l.upgradeUrl,wall:l.wall,pro:!1,entitled:!1,maxWorkers:1,entitlement:l}:{ok:!0,workers:r,fanout:Boolean(n)}}}}module.exports={createEntitlement:createEntitlement,normalizePlan:normalizePlan,isPaidPlan:isPaidPlan,tierName:tierName,TIER_NAMES:TIER_NAMES,classifyProbe:classifyProbe,fanoutRefusal:fanoutRefusal,balanceRefusal:balanceRefusal,ASK_EXAMPLE:ASK_EXAMPLE,balanceOf:balanceOf,FREE_MAX_WORKERS:1,PAID_PLANS:PAID_PLANS,LEGACY_PLAN_ALIASES:LEGACY_PLAN_ALIASES,CAMPAIGN:CAMPAIGN,UPGRADE_URL:UPGRADE_URL,BALANCE_CAMPAIGN:"topup_bank",BALANCE_URL:BALANCE_URL,PRO_VALUE:PRO_VALUE,FREE_HONESTY:FREE_HONESTY,BYOK_FEE_NOTE:BYOK_FEE_NOTE,byokFeeLine:byokFeeLine,DEFAULT_TTL_MS:6e4,SIGNUP_SOURCES:SIGNUP_SOURCES,DEFAULT_HOST:"desktop",goUrl:goUrl,promptUrlFor:promptUrlFor};
|
|
@@ -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
|
-
const READ_VERBS=new Set(["cat","head","tail","less","more","wc","grep","egrep","fgrep","rg","sed","awk","cut","sort","uniq","tr","diff","comm","join","nl","ls","dir","tree","stat","file","du","df","pwd","which","type","basename","dirname","realpath","readlink","find","locate","echo","printf","date","uname","whoami","id","env","printenv","true","test"]),GIT_READ_SUBCOMMANDS=new Set(["diff","status","log","show","blame","grep","ls-files","rev-parse","describe","cat-file","shortlog","whatchanged","reflog","show-ref","ls-tree","diff-tree","diff-files","diff-index","merge-base"]),WRITE_PATTERNS=[/(^|[\s;&|(])rm(\s|$)/,/(^|[\s;&|(])rmdir(\s|$)/,/(^|[\s;&|(])mv(\s|$)/,/(^|[\s;&|(])cp(\s|$)/,/(^|[\s;&|(])ln(\s|$)/,/(^|[\s;&|(])mkdir(\s|$)/,/(^|[\s;&|(])touch(\s|$)/,/(^|[\s;&|(])chmod(\s|$)/,/(^|[\s;&|(])chown(\s|$)/,/(^|[\s;&|(])truncate(\s|$)/,/(^|[\s;&|(])dd(\s|$)/,/(^|[\s;&|(])tee(\s|$)/,/(^|[\s;&|(])install(\s|$)/,/(^|[\s;&|(])patch(\s|$)/,/(^|[\s;&|(])git\s+(commit|add|rm|mv|checkout|switch|reset|apply|revert|merge|rebase|stash|clean|init|clone|pull|push|fetch|tag|branch|config)\b/,/(^|[\s;&|(])sed\s+(-[a-zA-Z]*i|--in-place)/,/(^|[\s;&|(])sort\b[^|;]*\s-o(\s|$)/,/(^|[\s;&|(])sort\b[^|;]*--output=/,/(^|[\s;&|(])dd\b[^|;]*\bof=/,/(^|[\s;&|(])find\b[^|;]*\s-(fprint|fprint0|fls)\b/,/(^|[\s;&|(])find\b[^|]*\s-(delete|exec|execdir|ok|okdir)\b/,/(^|[\s;&|(])(pip|pip3)\s+(install|uninstall|download)\b/,/(^|[\s;&|(])npm\s+(install|i|ci|uninstall|publish|run)\b/,/(^|[\s;&|(])yarn\s+(add|install|remove)\b/,/(^|[\s;&|(])apt(-get)?\s+(install|remove|purge|update|upgrade)\b/,/(^|[\s;&|(])(python|python3)\s+-m\s+pip\s+install\b/,/(^|[\s;&|(])pytest\b[^|]*--(cov|junitxml)/,/(?<![0-9&])>>?(?![&-])/,/\bexport\s+[A-Za-z_]/,/(^|[\s;&|(])source(\s|$)/],STATEFUL_PATTERNS=[/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/,/(^|[\s;&|(])pushd(\s|$)/,/(^|[\s;&|(])popd(\s|$)/,/(^|[\s;&|(])nohup(\s|$)/,/(^|[\s;&|(])disown(\s|$)/,/<<-?\s*['"]?[A-Za-z_]/,/(^|[\s;&|(])\&$/,/(^|[\s;&|(])exec(\s|$)/,/(^|[\s;&|(])history(\s|$)/,/(^|[\s;&|(])jobs(\s|$)/];function effectiveVerb(e){let s=0;for(let t=0;t<4&&s<e.length;t++){const t=e[s];if("time"!==t&&"command"!==t)if("env"!==t)if("timeout"!==t){if("nice"!==t)break;s+=1,s<e.length&&"-n"===e[s]?s+=2:s<e.length&&/^-?\d+$/.test(e[s])&&(s+=1)}else{for(s+=1;s<e.length&&e[s].startsWith("-");)s+=1;s<e.length&&/^[0-9]+(\.[0-9]+)?[smhd]?$/.test(e[s])&&(s+=1)}else for(s+=1;s<e.length&&(e[s].startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[s]));)s+=1;else s+=1}return s<e.length?{verb:e[s],rest:e.slice(s)}:null}function segments(e){const s=[],t=/(\|\||&&|[;|])/g;let n,r=0;for(;n=t.exec(e);)s.push({sep:null,text:e.slice(r,n.index)}),s.push({sep:n[1]}),r=n.index+n[1].length;return s.push({sep:null,text:e.slice(r)}),s}function leadingCd(e){const s=/^\s*cd\s+(?:--\s+)?(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))\s*&&\s*([\s\S]+)$/.exec(e);if(!s)return{cwd:null,rest:e};const t=(s[1]||s[2]||s[3]||"").trim();return t.startsWith("/")?{cwd:t,rest:s[4]}:{cwd:null,rest:e}}function planExec(e,s={}){const t=s.baseCwd||null,n="string"==typeof e?e:"",r=e=>({oneShot:!1,cwd:null,reason:e});if(!n.trim())return r("empty command");if(n.includes("\n"))return r("multi-line command");for(const e of STATEFUL_PATTERNS)if(e.test(n))return r("depends on session state");for(const e of WRITE_PATTERNS)if(e.test(n))return r("contains a write");const{cwd:i,rest:o}=leadingCd(n),l=o.trim();if(!l)return r("nothing after the cd");const a=segments(l).filter(
|
|
3
|
+
const READ_VERBS=new Set(["cat","head","tail","less","more","wc","grep","egrep","fgrep","rg","sed","awk","cut","sort","uniq","tr","diff","comm","join","nl","ls","dir","tree","stat","file","du","df","pwd","which","type","basename","dirname","realpath","readlink","find","locate","echo","printf","date","uname","whoami","id","env","printenv","true","test"]),GIT_READ_SUBCOMMANDS=new Set(["diff","status","log","show","blame","grep","ls-files","rev-parse","describe","cat-file","shortlog","whatchanged","reflog","show-ref","ls-tree","diff-tree","diff-files","diff-index","merge-base"]),WRITE_PATTERNS=[/(^|[\s;&|(])rm(\s|$)/,/(^|[\s;&|(])rmdir(\s|$)/,/(^|[\s;&|(])mv(\s|$)/,/(^|[\s;&|(])cp(\s|$)/,/(^|[\s;&|(])ln(\s|$)/,/(^|[\s;&|(])mkdir(\s|$)/,/(^|[\s;&|(])touch(\s|$)/,/(^|[\s;&|(])chmod(\s|$)/,/(^|[\s;&|(])chown(\s|$)/,/(^|[\s;&|(])truncate(\s|$)/,/(^|[\s;&|(])dd(\s|$)/,/(^|[\s;&|(])tee(\s|$)/,/(^|[\s;&|(])install(\s|$)/,/(^|[\s;&|(])patch(\s|$)/,/(^|[\s;&|(])git\s+(commit|add|rm|mv|checkout|switch|reset|apply|revert|merge|rebase|stash|clean|init|clone|pull|push|fetch|tag|branch|config)\b/,/(^|[\s;&|(])sed\s+(-[a-zA-Z]*i|--in-place)/,/(^|[\s;&|(])sort\b[^|;]*\s-o(\s|$)/,/(^|[\s;&|(])sort\b[^|;]*--output=/,/(^|[\s;&|(])dd\b[^|;]*\bof=/,/(^|[\s;&|(])find\b[^|;]*\s-(fprint|fprint0|fls)\b/,/(^|[\s;&|(])find\b[^|]*\s-(delete|exec|execdir|ok|okdir)\b/,/(^|[\s;&|(])(pip|pip3)\s+(install|uninstall|download)\b/,/(^|[\s;&|(])npm\s+(install|i|ci|uninstall|publish|run)\b/,/(^|[\s;&|(])yarn\s+(add|install|remove)\b/,/(^|[\s;&|(])apt(-get)?\s+(install|remove|purge|update|upgrade)\b/,/(^|[\s;&|(])(python|python3)\s+-m\s+pip\s+install\b/,/(^|[\s;&|(])pytest\b[^|]*--(cov|junitxml)/,/(?<![0-9&])>>?(?![&-])/,/\bexport\s+[A-Za-z_]/,/(^|[\s;&|(])source(\s|$)/],STATEFUL_PATTERNS=[/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/,/(^|[\s;&|(])pushd(\s|$)/,/(^|[\s;&|(])popd(\s|$)/,/(^|[\s;&|(])nohup(\s|$)/,/(^|[\s;&|(])disown(\s|$)/,/<<-?\s*['"]?[A-Za-z_]/,/(^|[\s;&|(])\&$/,/(^|[\s;&|(])exec(\s|$)/,/(^|[\s;&|(])history(\s|$)/,/(^|[\s;&|(])jobs(\s|$)/];function effectiveVerb(e){let s=0;for(let t=0;t<4&&s<e.length;t++){const t=e[s];if("time"!==t&&"command"!==t)if("env"!==t)if("timeout"!==t){if("nice"!==t)break;s+=1,s<e.length&&"-n"===e[s]?s+=2:s<e.length&&/^-?\d+$/.test(e[s])&&(s+=1)}else{for(s+=1;s<e.length&&e[s].startsWith("-");)s+=1;s<e.length&&/^[0-9]+(\.[0-9]+)?[smhd]?$/.test(e[s])&&(s+=1)}else for(s+=1;s<e.length&&(e[s].startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[s]));)s+=1;else s+=1}return s<e.length?{verb:e[s],rest:e.slice(s)}:null}function segments(e){const s=[],t=/(\|\||&&|[;|])/g;let n,r=0;for(;n=t.exec(e);)s.push({sep:null,text:e.slice(r,n.index)}),s.push({sep:n[1]}),r=n.index+n[1].length;return s.push({sep:null,text:e.slice(r)}),s}function leadingCd(e){const s=/^\s*cd\s+(?:--\s+)?(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))\s*&&\s*([\s\S]+)$/.exec(e);if(!s)return{cwd:null,rest:e};const t=(s[1]||s[2]||s[3]||"").trim();return t.startsWith("/")?{cwd:t,rest:s[4]}:{cwd:null,rest:e}}function planExec(e,s={}){const t=s.baseCwd||null,n="string"==typeof e?e:"",r=e=>({oneShot:!1,cwd:null,reason:e});if(!n.trim())return r("empty command");if(n.includes("\n"))return r("multi-line command");for(const e of STATEFUL_PATTERNS)if(e.test(n))return r("depends on session state");for(const e of WRITE_PATTERNS)if(e.test(n))return r("contains a write");const{cwd:i,rest:o}=leadingCd(n),l=o.trim();if(!l)return r("nothing after the cd");const a=segments(l).filter(e=>!e.sep);if(!a.length)return r("no command");for(const e of a){const s=e.text.trim().replace(/^\(+\s*/,"").split(/\s+/).filter(Boolean);if(!s.length)continue;const t=effectiveVerb(s);if(!t)return r("empty command after wrappers");const n=t.verb;if("git"===n){const e=t.rest[1];if(!e||e.startsWith("-"))continue;if(!GIT_READ_SUBCOMMANDS.has(e))return r(`git ${e} is not read-only`);continue}if(!READ_VERBS.has(n))return r(`${n} is not a known read verb`);if(("sed"===n||"awk"===n)&&/(^|\s)-[a-zA-Z]*w\s/.test(t.rest.join(" ")))return r(`${n} writes a file`)}return{oneShot:!0,cwd:i||t,reason:"read-only"}}module.exports={planExec:planExec,READ_VERBS:READ_VERBS,GIT_READ_SUBCOMMANDS:GIT_READ_SUBCOMMANDS,WRITE_PATTERNS:WRITE_PATTERNS,STATEFUL_PATTERNS:STATEFUL_PATTERNS};
|
|
@@ -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{createHash:createHash}=require("node:crypto"),{existsSync:existsSync,readFileSync:readFileSync}=require("node:fs"),path=require("node:path"),PACKAGE_ROOT=path.join(__dirname,"..",".."),SALT="aegis-desktop-interlock-v1",PAD="aegis-desktop-pad-v1",sha256=e=>createHash("sha256").update(e).digest("hex"),PAD_HEX=sha256(PAD);function unmask(e){let t="";for(let r=0;r<e.length;r++){const n=parseInt(e[r],16),i=parseInt(PAD_HEX[r%PAD_HEX.length],16);if(Number.isNaN(n)||Number.isNaN(i))return null;t+=(n^i).toString(16)}return t}const UNITS=Object.freeze([{id:"d1",rel:Buffer.from("bWFpbi5qcw==","base64").toString("utf8")},{id:"d2",rel:Buffer.from("bGliL2xvY2FsL3NoZWxsLmpz","base64").toString("utf8")},{id:"d3",rel:Buffer.from("bGliL2xvY2FsL3Rvb2xzLmpz","base64").toString("utf8")},{id:"d4",rel:Buffer.from("bGliL2xvY2FsL2V4ZWMtcGxhbi5qcw==","base64").toString("utf8")},{id:"d5",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3guanM=","base64").toString("utf8")},{id:"d6",rel:Buffer.from("bGliL2xvY2FsL3Blcm0tcnVsZXMuanM=","base64").toString("utf8")},{id:"d7",rel:Buffer.from("bGliL2xvY2FsL3Blcm0td3JpdGUuanM=","base64").toString("utf8")},{id:"d8",rel:Buffer.from("bGliL2xvY2FsL3Blcm0tc3RvcmUuanM=","base64").toString("utf8")},{id:"d9",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtc2VhdGJlbHQuanM=","base64").toString("utf8")},{id:"d10",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtYXBwY29udGFpbmVyLmpz","base64").toString("utf8")},{id:"d11",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtYndyYXAuanM=","base64").toString("utf8")}]),SEALED="
|
|
3
|
+
"use strict";const{createHash:createHash}=require("node:crypto"),{existsSync:existsSync,readFileSync:readFileSync}=require("node:fs"),path=require("node:path"),PACKAGE_ROOT=path.join(__dirname,"..",".."),SALT="aegis-desktop-interlock-v1",PAD="aegis-desktop-pad-v1",sha256=e=>createHash("sha256").update(e).digest("hex"),PAD_HEX=sha256(PAD);function unmask(e){let t="";for(let r=0;r<e.length;r++){const n=parseInt(e[r],16),i=parseInt(PAD_HEX[r%PAD_HEX.length],16);if(Number.isNaN(n)||Number.isNaN(i))return null;t+=(n^i).toString(16)}return t}const UNITS=Object.freeze([{id:"d1",rel:Buffer.from("bWFpbi5qcw==","base64").toString("utf8")},{id:"d2",rel:Buffer.from("bGliL2xvY2FsL3NoZWxsLmpz","base64").toString("utf8")},{id:"d3",rel:Buffer.from("bGliL2xvY2FsL3Rvb2xzLmpz","base64").toString("utf8")},{id:"d4",rel:Buffer.from("bGliL2xvY2FsL2V4ZWMtcGxhbi5qcw==","base64").toString("utf8")},{id:"d5",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3guanM=","base64").toString("utf8")},{id:"d6",rel:Buffer.from("bGliL2xvY2FsL3Blcm0tcnVsZXMuanM=","base64").toString("utf8")},{id:"d7",rel:Buffer.from("bGliL2xvY2FsL3Blcm0td3JpdGUuanM=","base64").toString("utf8")},{id:"d8",rel:Buffer.from("bGliL2xvY2FsL3Blcm0tc3RvcmUuanM=","base64").toString("utf8")},{id:"d9",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtc2VhdGJlbHQuanM=","base64").toString("utf8")},{id:"d10",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtYXBwY29udGFpbmVyLmpz","base64").toString("utf8")},{id:"d11",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtYndyYXAuanM=","base64").toString("utf8")}]),SEALED="d52aecc5027b818f4bce66299286d3c2ff1d36ed34f1ad9e60fd3e0314e6b062";function check(){const e=[];for(const t of UNITS){const r=path.join(PACKAGE_ROOT,t.rel);if(!existsSync(r))return{tripped:!0,code:"d1",units:UNITS.length};try{e.push(sha256(readFileSync(r)))}catch{return{tripped:!0,code:"d1",units:UNITS.length}}}const t=sha256(`${SALT}\n${e.join("\n")}`),r=SEALED.trim();return 64!==r.length?{tripped:!0,code:"d2",units:UNITS.length}:unmask(r)!==t?{tripped:!0,code:"d3",units:UNITS.length}:{tripped:!1,code:null,units:UNITS.length}}function line(e){return e&&e.tripped?`aegis-desktop: reduced mode (${e.code}) — this build is not the one that was published.\n`:null}let ARMED=null;function armed(){if(null!==ARMED)return ARMED;let e;try{e=check()}catch{e={tripped:!0,code:"d2",units:UNITS.length}}if(ARMED=Boolean(e.tripped),ARMED){process.env.AEGIS_REDUCED_MODE="1";const t=line(e);t&&process.stderr.write(t)}return ARMED}function sealOf(e){const t=e.map(e=>sha256(readFileSync(e)));return sha256(`${SALT}\n${t.join("\n")}`)}module.exports={UNITS:UNITS,SALT:SALT,PAD:PAD,check:check,armed:armed,line:line,sealOf:sealOf,mask:unmask};
|