aegisone 1.0.34 → 1.0.37
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/LICENSE +661 -0
- package/README.md +1 -1
- package/SOURCE-OFFER.txt +9 -0
- package/bin/aegis.js +1 -322
- package/package.json +4 -5
- package/scripts/bump.mjs +1 -211
- package/scripts/bundle.js +1 -129
- package/scripts/predist.mjs +1 -976
- package/src/child.js +1 -285
- package/src/dispatch.js +1 -269
- package/src/doctor.js +1 -639
- package/src/host.js +1 -111
- package/src/iface/paths.js +3 -0
- package/src/iface/pty.js +3 -0
- package/src/iface/update.js +3 -0
- package/src/iface/window.js +3 -0
- package/src/permissions.js +1 -383
- package/src/probes.js +1 -159
- package/src/protocol.js +3 -0
- package/src/release.js +1 -409
- package/src/selfhost.js +3 -0
- package/vendor/cli/package.json +3 -7
- package/vendor/cli/scripts/check.mjs +1 -52
- package/vendor/cli/scripts/demo.mjs +1 -94
- package/vendor/cli/scripts/predist.mjs +1 -75
- package/vendor/cli/scripts/runtests.mjs +1 -56
- package/vendor/cli/scripts/seal-gate.mjs +1 -74
- package/vendor/cli/src/agents.js +1 -139
- package/vendor/cli/src/app.js +1 -2957
- package/vendor/cli/src/art.js +1 -289
- package/vendor/cli/src/chatflow.js +1 -3023
- package/vendor/cli/src/checkpoint.js +1 -90
- package/vendor/cli/src/clipboard.js +1 -424
- package/vendor/cli/src/cloudsync.js +1 -528
- package/vendor/cli/src/commands.js +1 -4089
- package/vendor/cli/src/config.js +1 -581
- package/vendor/cli/src/connect.js +1 -349
- package/vendor/cli/src/credentials.js +1 -33
- package/vendor/cli/src/deps.js +1 -232
- package/vendor/cli/src/devrun.js +1 -187
- package/vendor/cli/src/diff.js +1 -333
- package/vendor/cli/src/diffview.js +1 -296
- package/vendor/cli/src/engine.js +1 -297
- package/vendor/cli/src/entitlement.js +1 -355
- package/vendor/cli/src/events.js +1 -707
- package/vendor/cli/src/export.js +1 -67
- package/vendor/cli/src/filepreview.js +1 -153
- package/vendor/cli/src/fingerprint.js +1 -592
- package/vendor/cli/src/format.js +1 -259
- package/vendor/cli/src/fuzzy.js +1 -119
- package/vendor/cli/src/history.js +1 -423
- package/vendor/cli/src/init.js +1 -175
- package/vendor/cli/src/input.js +1 -139
- package/vendor/cli/src/keys.js +1 -183
- package/vendor/cli/src/markdown.js +1 -306
- package/vendor/cli/src/models.js +1 -507
- package/vendor/cli/src/naming.js +1 -57
- package/vendor/cli/src/overlays.js +1 -462
- package/vendor/cli/src/panels.js +1 -1418
- package/vendor/cli/src/ping.js +1 -226
- package/vendor/cli/src/presence.js +1 -238
- package/vendor/cli/src/render.js +1 -516
- package/vendor/cli/src/screen.js +1 -518
- package/vendor/cli/src/screens.js +1 -896
- package/vendor/cli/src/secret.js +1 -59
- package/vendor/cli/src/securefs.js +1 -359
- package/vendor/cli/src/settings.js +1 -155
- package/vendor/cli/src/shared.js +1 -52
- package/vendor/cli/src/sharedpaths.js +1 -53
- package/vendor/cli/src/signup.js +1 -156
- package/vendor/cli/src/summarize.js +1 -95
- package/vendor/cli/src/sysdiag.js +1 -585
- package/vendor/cli/src/system.js +1 -40
- package/vendor/cli/src/theme.js +1 -570
- package/vendor/cli/src/title.js +1 -220
- package/vendor/cli/src/todos.js +1 -115
- package/vendor/cli/src/tokens.js +1 -263
- package/vendor/cli/src/topup.js +1 -210
- package/vendor/cli/src/update.js +1 -191
- package/vendor/cli/vendor/client/aegis.js +1 -2441
- package/vendor/cli/vendor/client/attest.js +1 -518
- package/vendor/cli/vendor/client/authorship-key.js +1 -410
- package/vendor/cli/vendor/client/auto-provision.js +1 -134
- package/vendor/cli/vendor/client/brain-catalog.js +1 -268
- package/vendor/cli/vendor/client/byok-catalog.js +1 -199
- package/vendor/cli/vendor/client/catalog-client.js +1 -487
- package/vendor/cli/vendor/client/conversation-export.js +1 -177
- package/vendor/cli/vendor/client/credentials.js +1 -494
- package/vendor/cli/vendor/client/device-fingerprint.js +1 -141
- package/vendor/cli/vendor/client/drive-connect.js +1 -110
- package/vendor/cli/vendor/client/drive-upload.js +1 -234
- package/vendor/cli/vendor/client/env-file.js +1 -1273
- package/vendor/cli/vendor/client/fingerprint.js +1 -1064
- package/vendor/cli/vendor/client/foreign-memory.js +1 -669
- package/vendor/cli/vendor/client/google-signin.js +1 -133
- package/vendor/cli/vendor/client/hooks.js +1 -430
- package/vendor/cli/vendor/client/model-discovery.js +1 -373
- package/vendor/cli/vendor/client/naming.js +1 -283
- package/vendor/cli/vendor/client/platform.js +1 -937
- package/vendor/cli/vendor/client/prefs.js +1 -351
- package/vendor/cli/vendor/client/presence-constants.js +1 -107
- package/vendor/cli/vendor/client/presence.js +1 -438
- package/vendor/cli/vendor/client/record-vault.js +3 -1055
- package/vendor/cli/vendor/client/session-store.js +1 -575
- package/vendor/cli/vendor/client/topup.js +1 -297
- package/vendor/cli/vendor/client/touch.js +1 -458
- package/vendor/cli/vendor/client/update.js +1 -763
- package/vendor/cli/vendor/client/user-models.js +1 -381
- package/vendor/cli/vendor/desktop/lib/local/agents.js +1 -105
- package/vendor/cli/vendor/desktop/lib/local/attachments.js +1 -276
- package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1045
- package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1028
- package/vendor/cli/vendor/desktop/lib/local/context.js +1 -125
- package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -3666
- package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -660
- package/vendor/cli/vendor/desktop/lib/local/git-scope.js +1 -228
- package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/local.js +1 -2145
- package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -280
- package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -560
- package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -238
- package/vendor/cli/vendor/desktop/lib/local/spill.js +1 -75
- package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -300
- package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -235
- package/vendor/cli/vendor/desktop/lib/settings.js +1 -890
- package/vendor/cli/vendor/desktop/main.js +67 -1
- package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1239
- package/vendor/cli/vendor/hosts/install.js +1 -638
- package/vendor/cli/vendor/hosts/openai-shim.js +1 -515
- package/vendor/cli/vendor/hosts/spec.js +1 -164
- package/vendor/cli/vendor/hosts/targets.js +1 -346
- package/vendor/cli/vendor/mcp/server.js +1 -221
- package/vendor/cli/vendor/mcp/tools.js +1 -408
- package/vendor/cli/vendor/one/src/child.js +1 -285
- package/vendor/cli/vendor/one/src/permissions.js +1 -383
- package/vendor/cli/vendor/one/src/selfhost.js +3 -0
- package/vendor/desktop/bin/aegis.js +1 -32
- package/vendor/desktop/lib/account-key.js +1 -56
- package/vendor/desktop/lib/auto.js +1 -461
- package/vendor/desktop/lib/avatar/companion.js +1 -698
- package/vendor/desktop/lib/avatar/cosmetics.js +1 -532
- package/vendor/desktop/lib/avatar/events.js +1 -344
- package/vendor/desktop/lib/avatar/holder-turn.js +1 -350
- package/vendor/desktop/lib/avatar/holders.js +1 -612
- package/vendor/desktop/lib/avatar/identity.js +1 -641
- package/vendor/desktop/lib/avatar/level.js +1 -368
- package/vendor/desktop/lib/avatar/mirror.js +1 -524
- package/vendor/desktop/lib/avatar/persona.js +1 -388
- package/vendor/desktop/lib/avatar/profile.js +1 -977
- package/vendor/desktop/lib/avatar/register.js +1 -307
- package/vendor/desktop/lib/avatar/store.js +1 -472
- package/vendor/desktop/lib/avatar/tiers.js +1 -38
- package/vendor/desktop/lib/avatar/transfer.js +1 -415
- package/vendor/desktop/lib/avatar/turn.js +1 -216
- package/vendor/desktop/lib/avatar/voice.js +1 -328
- package/vendor/desktop/lib/avatar/xp.js +1 -404
- package/vendor/desktop/lib/deep-link.js +1 -120
- package/vendor/desktop/lib/fingerprint.js +2 -347
- package/vendor/desktop/lib/google-connect.js +1 -323
- package/vendor/desktop/lib/local/agents.js +1 -105
- package/vendor/desktop/lib/local/attachments.js +1 -276
- package/vendor/desktop/lib/local/autonomous.js +1 -1045
- package/vendor/desktop/lib/local/claude-pro.js +1 -1028
- package/vendor/desktop/lib/local/context.js +1 -125
- package/vendor/desktop/lib/local/engine.js +1 -3666
- package/vendor/desktop/lib/local/entitlement.js +1 -660
- package/vendor/desktop/lib/local/git-scope.js +1 -228
- package/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/lib/local/local.js +1 -2145
- package/vendor/desktop/lib/local/prompt.js +1 -280
- package/vendor/desktop/lib/local/queue.js +1 -560
- package/vendor/desktop/lib/local/session-rounds.js +1 -238
- package/vendor/desktop/lib/local/spill.js +1 -75
- package/vendor/desktop/lib/local/telemetry.js +1 -470
- package/vendor/desktop/lib/local/turn-guard.js +1 -300
- package/vendor/desktop/lib/local/worktree-lock.js +1 -235
- package/vendor/desktop/lib/provider-key-mirror.js +1 -252
- package/vendor/desktop/lib/quick-launcher.js +1 -84
- package/vendor/desktop/lib/settings.js +1 -890
- package/vendor/desktop/lib/sync/memory-queue.js +1 -60
- package/vendor/desktop/lib/sync/persist-gate.js +1 -148
- package/vendor/desktop/lib/sync/sessions.js +1 -106
- package/vendor/desktop/lib/window-state.js +1 -66
- package/vendor/desktop/main.js +67 -1
- package/vendor/desktop/package.json +3 -5
- package/vendor/desktop/preload.js +1 -679
- package/vendor/desktop/renderer/app.js +1 -7250
- package/vendor/desktop/renderer/avatar/assemble.js +1 -335
- package/vendor/desktop/renderer/avatar/avatar.js +1 -380
- package/vendor/desktop/renderer/avatar/cards.js +1 -141
- package/vendor/desktop/renderer/avatar/hud.js +1 -206
- package/vendor/desktop/renderer/avatar/machine.js +1 -213
- package/vendor/desktop/renderer/avatar/pane.js +1 -439
- package/vendor/desktop/renderer/avatar/parts.js +1 -437
- package/vendor/desktop/renderer/budget.js +1 -172
- package/vendor/desktop/renderer/companion.js +1 -223
- package/vendor/desktop/renderer/diff.js +1 -359
- package/vendor/desktop/renderer/diffview.js +1 -336
- package/vendor/desktop/renderer/filepreview.js +1 -211
- package/vendor/desktop/renderer/fingerprint.js +3 -789
- package/vendor/desktop/renderer/markdown.js +1 -168
- package/vendor/desktop/renderer/provider-mark.js +1 -311
- package/vendor/desktop/renderer/provider-toolbar.js +1 -134
- package/vendor/desktop/renderer/providers.js +1 -259
- package/vendor/desktop/renderer/quick.js +1 -285
- package/vendor/desktop/renderer/stream-policy.js +1 -387
- package/vendor/desktop/renderer/transcript-view.js +1 -323
- package/vendor/desktop/renderer/usage.js +1 -1239
- package/vendor/desktop/vendor/aegis.js +1 -2441
- package/vendor/desktop/vendor/attest.js +1 -518
- package/vendor/desktop/vendor/authorship-key.js +1 -410
- package/vendor/desktop/vendor/auto-provision.js +1 -134
- package/vendor/desktop/vendor/brain-catalog.js +1 -268
- package/vendor/desktop/vendor/byok-catalog.js +1 -199
- package/vendor/desktop/vendor/catalog-client.js +1 -487
- package/vendor/desktop/vendor/conversation-export.js +1 -177
- package/vendor/desktop/vendor/credentials.js +1 -494
- package/vendor/desktop/vendor/device-fingerprint.js +1 -141
- package/vendor/desktop/vendor/drive-connect.js +1 -110
- package/vendor/desktop/vendor/drive-upload.js +1 -234
- package/vendor/desktop/vendor/env-file.js +1 -1273
- package/vendor/desktop/vendor/faces/cli/LICENSE +661 -0
- package/vendor/desktop/vendor/faces/cli/README.md +784 -0
- package/vendor/desktop/vendor/faces/cli/bin/aegiscode.js +20 -0
- package/vendor/desktop/vendor/faces/cli/package.json +44 -0
- package/vendor/desktop/vendor/faces/cli/scripts/check.mjs +4 -0
- package/vendor/desktop/vendor/faces/cli/scripts/demo.mjs +4 -0
- package/vendor/desktop/vendor/faces/cli/scripts/predist.mjs +4 -0
- package/vendor/desktop/vendor/faces/cli/scripts/runtests.mjs +4 -0
- package/vendor/desktop/vendor/faces/cli/scripts/seal-gate.mjs +3 -0
- package/vendor/desktop/vendor/faces/cli/src/agents.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/app.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/art.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/autonomous.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/caps.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/chatflow.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/checkpoint.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/clipboard.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/cloudsync.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/commands.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/config.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/connect.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/credentials.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/deps.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/devrun.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/diff.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/diffview.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/engine.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/entitlement.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/events.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/export.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/filepreview.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/fingerprint.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/format.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/fuzzy.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/gate.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/history.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/init.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/input.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/keys.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/limits.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/markdown.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/mcp.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/models.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/naming.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/overlays.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/panels.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/permissions.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/ping.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/presence.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/provenance.js +58 -0
- package/vendor/desktop/vendor/faces/cli/src/provenance.lock.json +36 -0
- package/vendor/desktop/vendor/faces/cli/src/render.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/screen.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/screens.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/secret.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/securefs.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/settings.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/shared.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/sharedpaths.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/signup.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/summarize.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/sysdiag.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/system.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/theme.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/title.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/todos.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/tokens.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/topup.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/update.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/aegis.js +4 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/attest.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/authorship-key.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/auto-provision.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/brain-catalog.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/catalog-client.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/conversation-export.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/credentials.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/device-fingerprint.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/drive-connect.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/drive-upload.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/env-file.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/fingerprint.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-memory.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/google-signin.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/hooks.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/model-discovery.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/platform.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/presence-constants.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/presence.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/record-vault.js +105 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/session-store.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/topup.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/touch.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/update.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/user-models.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/covenant/README.md +21 -0
- package/vendor/desktop/vendor/faces/cli/vendor/covenant/aegis.seal +177 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/aegis-seal.mjs +241 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/agents.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/attachments.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/autonomous.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/context.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/covenant.js +567 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/entitlement.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/exec-plan.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/git-scope.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/local.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/queue.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/session-rounds.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/shell.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/spill.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/turn-guard.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/worktree-lock.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +4 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/renderer/usage.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/hosts/install.js +1 -0
- package/vendor/desktop/vendor/faces/cli/vendor/hosts/openai-shim.js +2 -0
- package/vendor/desktop/vendor/faces/cli/vendor/hosts/spec.js +1 -0
- package/vendor/desktop/vendor/faces/cli/vendor/hosts/targets.js +1 -0
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/server.js +4 -0
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/tools.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/child.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/permissions.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/selfhost.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/tools/agent-gate.mjs +1203 -0
- package/vendor/desktop/vendor/fingerprint.js +1 -1064
- package/vendor/desktop/vendor/foreign-memory.js +1 -669
- package/vendor/desktop/vendor/google-signin.js +1 -133
- package/vendor/desktop/vendor/hooks.js +1 -430
- package/vendor/desktop/vendor/model-discovery.js +1 -373
- package/vendor/desktop/vendor/naming.js +1 -283
- package/vendor/desktop/vendor/platform.js +1 -937
- package/vendor/desktop/vendor/prefs.js +1 -351
- package/vendor/desktop/vendor/presence-constants.js +1 -107
- package/vendor/desktop/vendor/presence.js +1 -438
- package/vendor/desktop/vendor/record-vault.js +3 -1055
- package/vendor/desktop/vendor/selfhost.js +3 -0
- package/vendor/desktop/vendor/session-store.js +1 -575
- package/vendor/desktop/vendor/topup.js +1 -297
- package/vendor/desktop/vendor/touch.js +1 -458
- package/vendor/desktop/vendor/update.js +1 -763
- package/vendor/desktop/vendor/user-models.js +1 -381
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
4
|
+
"use strict";const path=require("node:path");for(const e of[process.stdout,process.stderr])e.on("error",(e=>{throw!e||"EPIPE"!==e.code&&"ERR_STREAM_DESTROYED"!==e.code||process.exit(0),e}));const HELP="aegiscode — AEGIS in your shell.\n\nUsage:\n aegiscode interactive session\n aegiscode \"question\" one-shot, then exit\n aegiscode -p \"question\" same, explicit\n echo \"q\" | aegiscode -p - read the prompt from stdin\n\nAccount:\n aegiscode connect sign this machine in — registers a device account\n if it has none (idempotent per machine), and that\n key is what cloud memory and the record vault use\n aegiscode connect --status is this machine connected? (--json; exit 1 if not)\n aegiscode connect --logout sign out (forget the saved key here)\n aegiscode login [<key>] save your AEGIS API key (prompts, no echo, if omitted)\n aegiscode logout remove the saved key\n aegiscode key status show which key is in use and where it came from\n aegiscode topup [EUR] add credit to the token bank (2..1000, default 10):\n opens the payment page, then confirms the credit\n here — the account this machine auto-provisions\n has no browser session, so the page cannot show it\n\nAutomation:\n aegiscode autonomous help run queued tasks with no terminal at all\n aegiscode mcp install put AEGIS inside VS Code / Cursor / Zed /\n Cline / Windsurf / … ('mcp list' shows them)\n aegiscode mcp status which editors are configured, and do they work\n aegiscode mcp shim OpenAI-compatible endpoint for clients that\n take a base URL but speak no MCP\n aegiscode mcp help all subcommands and their flags\n\nAttestation (φ(α) — a sealed record of what a session was):\n aegiscode fingerprint status which authorship key is in use, and where\n aegiscode fingerprint keygen mint a private key (0600, never printed)\n aegiscode fingerprint mint seal the last session as a record\n aegiscode fingerprint verify <file> recompute a record's attestation\n aegiscode fingerprint backup --to DIR copy the key somewhere safe\n aegiscode fingerprint publish [<file>] publish a record, link the copy\n aegiscode fingerprint anchor <file> is the published copy still ours?\n aegiscode fingerprint vault --audit what is in the vault, and is a key in it\n aegiscode fingerprint help all subcommands and their flags\n\nCode protection (the agent-key gate on aegiscodex-dev / aegiscode-plugin):\n aegiscode gate status can THIS machine edit a gated tree?\n aegiscode gate import-key [PATH] adopt a key dropped at PATH\n (default ~/Downloads/agent.key),\n then delete PATH\n aegiscode gate bind-machine trust this machine in the manifest\n aegiscode gate rotate mint a fresh key, burn the old one\n aegiscode gate add-key add another key (from stdin)\n aegiscode gate lock-status the server-side half of the lock\n aegiscode gate help all subcommands and their flags\n\nProvenance (this binary, and whether it is still the published one):\n aegiscode provenance licence, source, and a self-check of\n this build against the published seal\n (--json for scripts; exit 1 if a\n sealed unit has moved)\n\nOptions:\n -m, --model <id> pin a model id (see /models; default: server choice)\n --class <name> run this turn on aegis|byok|local|pro. The one-shot\n path had no way to state a class, so '-p' always ran\n the pooled route (DEFAULT_CLASS) no matter what was\n pinned — a headless turn could not use a BYOK key at\n all. '--class byok' needs '--model <provider>:<model>'.\n --base <url> API base (default $AEGIS_API_BASE or aegiscloud.org)\n --key <key> API key for THIS RUN only — it is not saved. Use\n \"aegiscode login\" to store one for good.\n --json with -p: emit JSON instead of text\n --no-stream buffer the answer instead of streaming it\n --max-tokens <n> output ceiling hint\n --light light theme\n --width <cols> force a render width (useful for piping/logs)\n --automode skip tool-approval prompts (exec/writeFile/editFile\n run without asking) — same as the in-session /automode\n --yolo alias of --automode (the pre-rename spelling)\n --ascii draw with the ASCII mark and glyph set (no Unicode).\n Same as AEGIS_ART=ascii; /terminal ascii toggles it\n mid-session.\n --no-color no colour at all (same as NO_COLOR=1)\n --terminal print the resolved terminal capabilities and exit —\n one report shape on every platform, so pasting it\n from PowerShell (or into a bug report) reads the same\n as pasting it from zsh\n -c, --continue skip onboarding and resume the most recent session\n -h, --help this text\n -v, --version print the version\n\nIn-session: type /help for commands, /quit to exit, esc/ctrl+c to interrupt a\nrunning call. Plain text is a prompt (identical to /ask) — a question that\nneeds a file read, a shell command, or an edit is handled the same turn.\n";function parseArgs(e){const s={model:null,base:null,key:null,json:!1,class:null,stream:!0,maxTokens:void 0,light:!1,width:null,yolo:!1,ascii:null,color:null,terminal:!1,continue:!1,prompt:null,help:!1,version:!1,command:null,commandArg:null,commandArgv:null},t=[],n=e[0];if(n&&!n.startsWith("-")&&ACCOUNT_COMMANDS.has(n)){const t=e[1];s.command=n,s.commandArg=t&&!t.startsWith("-")?t:null,e=e.slice(s.commandArg?2:1)}else if("autonomous"===n){const t=e[1]&&!e[1].startsWith("-")?e[1]:"help";s.command="autonomous",s.commandArg=t,s.commandArgv=e.slice(e[1]&&!e[1].startsWith("-")?2:1),e=[]}else if("mcp"===n){const t=e[1]&&!e[1].startsWith("-")?e[1]:"status";s.command="mcp",s.commandArg=t,s.commandArgv=e.slice(e[1]&&!e[1].startsWith("-")?2:1),e=[]}else if("fingerprint"===n){const t=e[1]&&!e[1].startsWith("-")?e[1]:"status";s.command="fingerprint",s.commandArg=t,s.commandArgv=e.slice(e[1]&&!e[1].startsWith("-")?2:1),e=[]}else if("gate"===n){const t=e[1]&&!e[1].startsWith("-")?e[1]:"status";s.command="gate",s.commandArg=t,s.commandArgv=e.slice(e[1]&&!e[1].startsWith("-")?2:1),e=[]}else if("connect"===n)s.command="connect",s.commandArg=null,s.commandArgv=e.slice(1),e=[];else if("provenance"===n)s.command="provenance",e=e.slice(1);else if("topup"===n){const t=e[1]&&!e[1].startsWith("-")?e[1]:null;s.command="topup",s.commandArg=t,e=t?e.slice(2):e.slice(1)}for(let n=0;n<e.length;n++){const o=e[n],r=()=>{const s=e[++n];if(void 0===s)throw new Error(`${o} needs a value`);return s};switch(o){case"-h":case"--help":s.help=!0;break;case"-v":case"--version":s.version=!0;break;case"-p":case"--print":s.prompt=e[n+1]&&!e[n+1].startsWith("-")?r():"-";break;case"-m":case"--model":s.model=r();break;case"--class":s.class=r();break;case"--base":s.base=r();break;case"--key":s.key=r();break;case"--json":s.json=!0;break;case"--no-stream":s.stream=!1;break;case"--stream":s.stream=!0;break;case"--max-tokens":s.maxTokens=Number(r());break;case"--light":s.light=!0;break;case"--automode":case"--yolo":s.yolo=!0;break;case"-c":case"--continue":s.continue=!0;break;case"--width":s.width=Number(r());break;case"--ascii":s.ascii=!0;break;case"--unicode":s.ascii=!1;break;case"--no-color":case"--no-colour":s.color=!1;break;case"--color":case"--colour":s.color=!0;break;case"--terminal":case"--caps":s.terminal=!0;break;default:if(o.startsWith("-")&&"-"!==o)throw new Error(`unknown option: ${o}`);t.push(o)}}return!s.prompt&&t.length&&(s.prompt=t.join(" ")),s}
|
|
5
|
+
/**
|
|
6
|
+
* `aegiscode provenance` — what this binary is, and whether its safety files are
|
|
7
|
+
* the ones that were published.
|
|
8
|
+
*
|
|
9
|
+
* The use case is a user (or an auditor, or a script) holding an install they
|
|
10
|
+
* did not build: `npm i -g aegiscode`, a tarball mailed to them, a rebuilt fork.
|
|
11
|
+
* It answers with the licence, the copyright holder, the source URL, and the
|
|
12
|
+
* result of the startup self-check against `src/provenance.lock.json`.
|
|
13
|
+
*
|
|
14
|
+
* Exit codes: 0 = identity intact and safety files verified; 1 = a safety file
|
|
15
|
+
* has moved, or the manifest is missing and the install therefore cannot be
|
|
16
|
+
* verified at all (absence is a failure — see src/provenance.js for why the
|
|
17
|
+
* cheap attack must be the loud one). A fork that has deliberately rebuilt is
|
|
18
|
+
* expected to regenerate the manifest and exit 0 naming itself; one that has
|
|
19
|
+
* not now says so instead of staying silent.
|
|
20
|
+
*/function runProvenance(e={}){const s=require(path.join(__dirname,"..","package.json")),t=require("../src/provenance.js"),n=t.describe({version:s.version});return e.json?(process.stdout.write(JSON.stringify({product:t.IDENTITY.product,bin:t.IDENTITY.bin,version:s.version,license:t.IDENTITY.license,source:t.IDENTITY.source,homepage:t.IDENTITY.homepage,copyright:t.IDENTITY.copyright,safety:{ok:n.report.ok,checked:n.report.checked,problems:n.report.problems}},null,2)+"\n"),n.ok?0:1):(process.stdout.write(n.text),n.ok?0:1)}const ACCOUNT_COMMANDS=new Set(["login","logout","key"]);async function runAccountCommand(e,s,t={}){const n=t.stdout||process.stdout,o=t.stderr||process.stderr,r=t.stdin||process.stdin,{credentials:i,readSecret:a,maskKey:c}=loadAccountDeps();if("logout"===e||"key"===e&&["clear","remove","rm"].includes(String(s||"").toLowerCase())){const e=i.clearApiKey();return n.write(e.cleared?`aegiscode: key removed from ${e.path}\n`:"aegiscode: no saved key to remove\n"),i.legacyKeyOnDisk()&&n.write('aegiscode: note — a plaintext copy is also in config.json, written by an older AEGIS CLI; delete its "aegiscloud" block as well to finish removing it\n'),0}if("key"===e&&["status","show",""].includes(String(s||"").toLowerCase())){const e=i.keyStatus();return t.json?(n.write(JSON.stringify({configured:e.configured,source:e.source,source_label:i.sourceLabel(e.source),path:e.path,file_mode:e.fileMode,masked:e.configured?c(e.key):null,memory_token:e.memoryToken,verified_at:e.verifiedAt,plaintext_copy_in_config:e.legacyPlaintext},null,2)+"\n"),e.configured?0:1):(n.write([`key: ${e.configured?c(e.key):"not set"}`,`source: ${i.sourceLabel(e.source)}`,`file: ${e.path}${e.fileMode?` (${e.fileMode})`:""}`,"memory: "+(e.memoryToken?"token held (cloud sync ready)":"no token"),e.verifiedAt?`verified: ${e.verifiedAt}`:null,e.legacyPlaintext?"note: a plaintext copy also sits in config.json — re-save with `aegiscode login` to move it":null].filter(Boolean).join("\n")+"\n"),e.configured?0:1)}let d=s&&"status"!==s?String(s).trim():"";if(!d){if(!r.isTTY)return o.write("aegiscode: no terminal to prompt on — pass the key: `aegiscode login <api_key>`\n (or set AEGIS_API_KEY for a single run)\n"),2;d=await a("AEGIS API key (kept off screen, Enter to cancel): ",{stdin:r,stdout:n})}if(!d)return o.write("aegiscode: no key given — nothing saved\n"),2;const{createApp:l}=require("../src/app.js"),u=l({interactive:!1}),m=await u.setApiKey(d);if(!m.ok)return o.write(`aegiscode: ${m.message||"that key could not be saved"}\n`),2;const p=m.account&&(m.account.email||m.account.plan);if(n.write(`aegiscode: key saved to ${m.path}${p?` — ${p}`:""}\n`),m.error){const e=m.error.status;return o.write(`aegiscode: the account check failed: ${m.error.message}\n`),401===e||403===e?(o.write("aegiscode: the key is stored but the server refused it — re-run with a fresh key\n"),1):(o.write("aegiscode: (stored anyway — the server could not be reached to confirm it)\n"),0)}return n.write("aegiscode: verified — run `aegiscode` to start a session\n"),0}function loadAccountDeps(){const e=require("../src/credentials.js"),{readSecret:s}=require("../src/secret.js"),{maskKey:t}=require("../src/format.js");return{credentials:e,readSecret:s,maskKey:t}}function readStdin(){return new Promise((e=>{let s="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(e=>{s+=e})),process.stdin.on("end",(()=>e(s.trim())))}))}async function main(e=process.argv.slice(2)){let s;try{s=parseArgs(e)}catch(e){return process.stderr.write(`aegiscode: ${e.message}\n\n${HELP}`),2}if(s.help)return process.stdout.write(HELP),0;const t=require(path.join(__dirname,"..","package.json"));if(s.version)return process.stdout.write(t.version+"\n"),0;let n=!1;try{const e=require("../src/limits.js");if(n=e.armed(),n&&e.isPrivileged(s.command))return e.refuse()}catch{}try{const{resolveClientModule:e}=require("../src/shared.js"),s=require(e("env-file.js")).loadEnvFile();s.loose&&process.stderr.write(`aegiscode: ${s.file} is readable by other accounts (mode ${s.mode.toString(8)}) — consider \`chmod 600\` on it.\n`)}catch(e){process.stderr.write(`aegiscode: could not read ~/.aegiscode/.env: ${e&&e.message}\n`)}const{setCaps:o,describe:r}=require("../src/caps.js"),i={...process.env};if(!0===s.ascii&&(i.AEGIS_ART="ascii"),!1===s.ascii&&(i.AEGIS_ART="unicode"),!1===s.color&&(i.NO_COLOR="1"),!0===s.color&&(delete i.NO_COLOR,i.FORCE_COLOR="3"),s.width&&(i.AEGIS_WIDTH=String(s.width)),o(null,i),s.terminal){const e=r(),s=e.reduce(((e,[s])=>Math.max(e,s.length)),0);process.stdout.write(`aegiscode ${t.version} — terminal capabilities\n\n`);for(const[t,n]of e)process.stdout.write(` ${t.padEnd(s)} ${n}\n`);return process.stdout.write("\nOverride with --ascii / --color / --light / --width, or AEGIS_ART,\nAEGIS_STAR, AEGIS_COLOR, AEGIS_BACKGROUND, AEGIS_BACKGROUND_PROBE, AEGIS_VT,\nAEGIS_WIDTH (see README).\n"),0}if(s.base&&(process.env.AEGIS_API_BASE=s.base),s.key&&(process.env.AEGIS_API_KEY=s.key),"fingerprint"===s.command){const{runFingerprint:e}=require("../src/fingerprint.js");return e(s.commandArg||"status",s.commandArgv||[],{json:s.json,stdout:process.stdout,stderr:process.stderr})}if("connect"===s.command){const{runConnect:e}=require("../src/connect.js");return e(s.commandArgv||[],{json:s.json,stdout:process.stdout,stderr:process.stderr})}if("gate"===s.command){const{runGate:e}=require("../src/gate.js");return e(s.commandArg||"status",s.commandArgv||[])}if("topup"===s.command){const{runTopupCommand:e}=require("../src/topup.js");return e(s.commandArg,{json:s.json,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}if(ACCOUNT_COMMANDS.has(s.command))return runAccountCommand(s.command,s.commandArg,{json:s.json,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr});if("autonomous"===s.command){const e=require("../src/presence.js"),t=require("../src/credentials.js");e.start({credentials:t,autonomous:!0,queueDepth:e.queueDepthReader()}),process.once("exit",(()=>e.stop()));const{runQueueCommand:n}=require("../src/autonomous.js");return n(s.commandArg,s.commandArgv||[],{json:s.json,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}if("mcp"===s.command){const{runMcpCommand:e}=require("../src/mcp.js");return e(s.commandArg,s.commandArgv||[],{json:s.json,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}if("provenance"===s.command&&!n)return runProvenance({json:s.json});const{createApp:a}=require("../src/app.js");if(!n)try{const e=require("../src/provenance.js"),s=e.warning(e.selfCheck());s&&process.stderr.write(s)}catch{}const c=require("../src/presence.js");c.start({credentials:require("../src/credentials.js"),queueDepth:c.queueDepthReader()}),process.once("exit",(()=>c.stop()));let d=s.prompt;if("-"===d){if(process.stdin.isTTY)return process.stderr.write("aegiscode: -p - expects a prompt on stdin\n"),2;if(d=await readStdin(),!d)return process.stderr.write("aegiscode: empty stdin\n"),2}const l=a({model:s.model,class:s.class,stream:s.stream,light:s.light,maxTokens:s.maxTokens,...s.effort?{effort:s.effort}:{},width:s.width?()=>s.width:void 0,interactive:!d&&Boolean(process.stdin.isTTY),confirmMode:!s.yolo&&void 0,continue:s.continue});if(d)return l.runOnce(d,{json:s.json});if(!process.stdin.isTTY)return process.stderr.write('aegiscode: no terminal and no prompt. Use `aegiscode -p "question"` or pipe a prompt in.\n'),2;const u=require("../src/screen.js");u.queueExitNotice("\nResume this session with:\n aegiscode --continue (or /resume for the list)\n");const m=()=>{try{u.isAltScreen()&&u.leaveAltScreen(),u.flushExitNotice()}catch{}},p=l.runInteractive();process.once("exit",m);const h=await p;return m(),h}require.main===module&&main().then((async e=>{try{await require("../src/presence.js").flush()}catch{}process.exit(e||0)})).catch((e=>{process.stderr.write(`aegiscode: ${e&&e.message?e.message:e}\n`),process.exit(1)})),module.exports={main:main,parseArgs:parseArgs,HELP:HELP,ACCOUNT_COMMANDS:ACCOUNT_COMMANDS,runAccountCommand:runAccountCommand};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "aegiscode",
|
|
3
|
+
"productName": "AEGIS Code",
|
|
4
|
+
"version": "7.0.29",
|
|
5
|
+
"description": "aegiscode — the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
|
|
6
|
+
"author": {
|
|
7
|
+
"name": "AEGIS Code",
|
|
8
|
+
"email": "nborneklint@gmail.com"
|
|
9
|
+
},
|
|
10
|
+
"license": "AGPL-3.0-or-later",
|
|
11
|
+
"homepage": "https://aegiscloud.org",
|
|
12
|
+
"bin": {
|
|
13
|
+
"aegiscode": "bin/aegiscode.js",
|
|
14
|
+
"aegiscodex": "bin/aegiscode.js"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"bin",
|
|
18
|
+
"src",
|
|
19
|
+
"scripts",
|
|
20
|
+
"vendor",
|
|
21
|
+
"README.md"
|
|
22
|
+
],
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=22.0.0"
|
|
25
|
+
},
|
|
26
|
+
"scripts": {
|
|
27
|
+
"start": "node bin/aegiscode.js",
|
|
28
|
+
"predist": "node scripts/predist.mjs",
|
|
29
|
+
"prepack": "node scripts/predist.mjs --quiet",
|
|
30
|
+
"prepublishOnly": "npm run predist",
|
|
31
|
+
"precheck": "node scripts/predist.mjs",
|
|
32
|
+
"check": "node scripts/check.mjs",
|
|
33
|
+
"pretest": "node scripts/predist.mjs",
|
|
34
|
+
"test": "node scripts/runtests.mjs"
|
|
35
|
+
},
|
|
36
|
+
"keywords": [
|
|
37
|
+
"aegis",
|
|
38
|
+
"aegiscode",
|
|
39
|
+
"aegiscloud",
|
|
40
|
+
"cli",
|
|
41
|
+
"terminal",
|
|
42
|
+
"llm"
|
|
43
|
+
]
|
|
44
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
4
|
+
import{readdirSync as s}from"node:fs";import{spawnSync as e}from"node:child_process";import{dirname as t,join as o,resolve as r}from"node:path";import{fileURLToPath as i}from"node:url";const c=t(i(import.meta.url)),n=r(c,".."),a=o(n,"src"),p=[o(n,"bin","aegiscode.js"),...s(a).filter((s=>s.endsWith(".js"))).sort().map((s=>o(a,s))),o(c,"predist.mjs")];0===p.length&&(process.stderr.write("check: no files to check\n"),process.exit(1));const d=[];for(const s of p){const t=e(process.execPath,["--check",s],{stdio:"inherit"});0!==t.status&&d.push({file:s,status:t.status})}if(d.length){process.stderr.write(`\ncheck failed (${d.length}):\n`);for(const{file:s,status:e}of d)process.stderr.write(` ✗ ${s} (exit ${e})\n`);process.exit(1)}process.stdout.write(`check ok: ${p.length} files\n`);
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
4
|
+
import{createRequire as e}from"node:module";import n from"node:path";import{fileURLToPath as r}from"node:url";const t=e(import.meta.url),s=n.dirname(r(import.meta.url)),o=n.join(s,"..","src"),i=t(n.join(o,"render.js")),{stripAnsi:a}=t(n.join(o,"screen.js")),d=t(n.join(o,"art.js")),{version:u}=t(n.join(s,"..","package.json")),l=process.argv.slice(2),m=Number(((e,n)=>{const r=l.indexOf("--width");return-1===r?0:l[r+1]})())||Math.min(96,Math.max(48,process.stdout.columns||84)),c={light:l.includes("--light")},g=l.includes("--plain"),p=[],h=e=>p.push(...Array.isArray(e)?e:[e]);h(i.renderBanner(c,{width:m,version:u,model:"nexus-brain",base:"https://aegiscloud.org",key:"aegis_••••4f2a",stream:!0})),h(""),h(i.renderTurn(c,{role:"user",text:"summarise what changed in the token accounting"},m)),h(i.renderTurn(c,{role:"assistant",text:["Three things changed, and one of them was costing you money:","","- the pool **merges** worker usage instead of overwriting it","- cache reads and writes are billed, not ignored","- a zero-token call no longer refunds its reservation","","```","merge_usage({input_tokens: 1250}, {output_tokens: 312})","=> 1562 total","```","","Use `/balance` to see tokens beside € on every row."].join("\n"),meta:{model:"nexus-brain",tokens:1562,usage:{input:1250,output:312},eur:7e-4,ms:4200,calls:4}},m)),h(""),h(i.renderWorking(c,{tick:3,verb:"Consulting",elapsedMs:2100})),h(i.renderStatus(c,{model:"nexus-brain",tokens:1562,spend:7e-4,mode:"stream"},m)),process.stdout.write((g?p.map(a):p).join("\n")+"\n\n"),g||process.stdout.write(a(`${d.WELCOME_TITLE} — ${p.length} lines rendered at ${m} cols${c.light?" (light)":""}\n`));
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
4
|
+
import e from"node:path";import{fileURLToPath as t,pathToFileURL as r}from"node:url";import{sealGate as s}from"./seal-gate.mjs";const a=e.dirname(t(import.meta.url)),i=e.join(a,"..","..","one","scripts","predist.mjs");async function o(e){const t=(Array.isArray(e)?e:process.argv.slice(2)).includes("--quiet")?["--quiet"]:[],a=s();if(!a.ok&&!process.env.AEGIS_ALLOW_UNSEALED)return process.stderr.write(`${a.line}\ncut: refusing to stage a package from it. Reseal the tree deliberately, or set AEGIS_ALLOW_UNSEALED=1 to stage a build that is known not to be the published one.\n`),1;let o;process.stderr.write(a.ok?`${a.line}\n`:`${a.line}\ncut: AEGIS_ALLOW_UNSEALED is set — staging anyway; this artifact will not match the published manifest.\n`);try{o=await import(r(i).href)}catch(e){return process.stderr.write(`predist: the shared stager is not reachable at ${i}.\npredist: it lives in the repo (one/scripts/predist.mjs) and is not shipped inside the aegiscode tarball — a built package already carries its vendor tree.\n${e&&e.message||e}\n`),1}return o.main(["--mirror-only",...t])}process.argv[1]&&e.resolve(process.argv[1])===t(import.meta.url)&&(process.exitCode=await o(process.argv.slice(2)));export{o as main,s as sealGate};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
4
|
+
import{readdirSync as s}from"node:fs";import{spawnSync as t}from"node:child_process";import{dirname as e,join as o,resolve as r}from"node:path";import{fileURLToPath as n}from"node:url";const i=r(e(n(import.meta.url)),"..","..","test"),a=s(i).filter((s=>/^cli-.*\.test\.mjs$/.test(s))).sort();0===a.length&&(process.stderr.write(`no cli-*.test.mjs found in ${i}\n`),process.exit(1));const c=[],p=[];for(const s of a){const e=o(i,s);process.stdout.write(`\n── ${s} ${"─".repeat(Math.max(0,60-s.length))}\n`);const r=t(process.execPath,[e],{stdio:"inherit"});0===r.status?p.push(s):c.push({f:s,status:r.status,signal:r.signal})}if(process.stdout.write(`\n${"═".repeat(64)}\n`),process.stdout.write(`cli suite: ${p.length}/${a.length} files passed\n`),c.length){process.stdout.write(`\nFAILED (${c.length}):\n`);for(const{f:s,status:t,signal:e}of c)process.stdout.write(` ✗ ${s}${e?` (signal ${e})`:` (exit ${t})`}\n`);process.exit(1)}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
import e from"node:path";import{createRequire as t}from"node:module";import{fileURLToPath as o}from"node:url";const r=e.dirname(o(import.meta.url)),i=e.join(r,".."),s=t(import.meta.url);function n(){let t,o;try{t=s(e.join(i,"src","limits.js")),o=s(e.join(i,"src","provenance.js"))}catch(e){return{ok:!1,line:`cut: the safety modules are unreadable (${e&&e.message||e}).`}}const r=t.check();if(r.tripped)return{ok:!1,line:`cut: the sealed set has moved (${r.code}) — this tree is not the published one.`};const n=o.selfCheck();return n.ok?{ok:!0,line:`cut: ${n.checked} sealed units verified — this tree is the published one.`}:{ok:!1,line:`cut: ${n.problems.join("; ")}`}}export{n as sealGate};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";const AGENT_PRESETS={synthesizer:"You are a senior technical lead. Given analysis from multiple specialist agents, synthesize their findings into a clear, actionable summary.\nStructure your response as: key findings, recommended approach, top action items.\nBe direct, concrete, and avoid repeating everything the agents said.\nFocus on delivering a decision-ready synthesis.",architect:"You are a System Architect. Design the new application architecture.\nDefine: project structure, tech stack, directory layout, key modules, data flow, API design.\nConsider: scalability, maintainability, testing strategy, deployment.\nOutput a concrete file tree and architecture decisions log. Be specific.",scaffolder:"You are a Project Scaffolder. Build the complete application from scratch.\n\nYOUR JOB IS TO CREATE ALL PROJECT FILES - not just describe them.\n\nUse Write to create: package.json, tsconfig.json, source files, configs, tests.\nGenerate COMPLETE, WORKING code - not stubs or placeholders.\nSet up build scripts, lint config, and any necessary tooling.\n\nAfter creating files, use Bash to run: npm/pnpm install, then build/compile.\nFix any errors until the project builds successfully.\n\nBe thorough - a real, runnable project is the goal.",planner:"You are a Refactoring Planner. Given the analyzer findings, create a step-by-step plan.\nEach step: file path, what to change, why, risk level (LOW/MEDIUM/HIGH).\nInclude before/after snippets. Order by impact. Be concrete.",implementer:"You are an Implementation Engineer. Execute the refactoring plan.\nUse Edit and Write to make actual code changes.\nAfter each change, use Read to verify correctness. Keep existing code style.\nRun build commands to ensure nothing is broken.",reviewer:"You are a Code Reviewer. Review the approach and code.\nCheck: logic errors, type safety, error handling, performance, security.\nBe critical but constructive. Report specific issues with file paths.",debugger:"You are a Debugging Specialist. Analyze potential issues and edge cases.\nIdentify: failure modes, error handling gaps, testing considerations.\nThink about what could go wrong and how to prevent it.",scanner:"You are a Security Vulnerability Scanner.\nScan for: hardcoded API keys/secrets, SQL injection, XSS, unsafe eval/exec, path traversal.\nUse Grep with targeted patterns. Report every finding with: file path, severity (CRITICAL/HIGH/MEDIUM/LOW), line number.",analyzer:"You are a Code Analyzer. Find refactoring opportunities.\nLook for: duplicated code, long functions (>20 lines), complex conditionals, unused imports,\ncircular dependencies, inconsistent patterns. Report with file paths and line numbers."};function agentRoleLabel(e){return{synthesizer:"Technical Lead",architect:"System Architect",scaffolder:"Project Scaffolder",planner:"Refactoring Planner",implementer:"Implementation Engineer",reviewer:"Code Reviewer",debugger:"Debugging Specialist",scanner:"Vulnerability Scanner",analyzer:"Code Analyzer"}[e]||e}function composeAgentPrompt(e,t){return`${AGENT_PRESETS[e]}\n\nTask: ${t}\n\nRespond directly — no preamble.`}function agentRoles(){return Object.keys(AGENT_PRESETS)}function composeResearchPrompt(e,t=process.cwd()){return["Research the following question from four perspectives, then synthesize:","",`Question: ${e}`,"","You are a research council with these members:","- Analyst: reasons from data, statistics, and empirical evidence; values measurable outcomes.","- Architect: evaluates designs, tradeoffs, and architectural decisions; focuses on scalability, maintainability, and system coherence.","- Ethicist: evaluates safety, fairness, privacy, and societal impact; raises concerns others miss.","- Pragmatist: evaluates practicality, implementation effort, and real-world constraints; balances idealism with what works in production.","",`Workspace: ${t} — read files with Read, search with Grep, browse with Glob, and check recent git changes with Git to ground your analysis in the real codebase.`,"","Format: one reasoned section per perspective, then a Synthesis with a clear recommendation. Always state VOTE: approve, reject, or abstain and REASONING with clear justification."].join("\n")}function composeDebatePrompt(e,t=""){return[`Hold a structured debate on: ${e}`,"","Present two opposing positions fairly (with the strongest argument FOR and AGAINST), then act as moderator:","1. Opening statements for each side.","2. Rebuttals — each side attacks the other's weakest claim.","3. Cross-examination questions and answers.","4. Closing statements.","5. A moderator verdict summarizing where each side won and a final recommendation.","","Be rigorous and balanced — steelman both sides before judging."+(t?` (Simulated on ${t} — the reference runs a multi-model discussion.)`:"")].join("\n")}module.exports={AGENT_PRESETS:AGENT_PRESETS,agentRoleLabel:agentRoleLabel,composeAgentPrompt:composeAgentPrompt,agentRoles:agentRoles,composeResearchPrompt:composeResearchPrompt,composeDebatePrompt:composeDebatePrompt};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";const readline=require("node:readline"),os=require("node:os"),{randomUUID:randomUUID}=require("node:crypto"),{createTools:createTools,createClient:createClient,usageTokens:usageTokens,usageBuckets:usageBuckets,buildSystemPrompt:buildSystemPrompt,autoProvisionApiKey:autoProvisionApiKey,provisionFailureText:provisionFailureText,trialNote:trialNote,hostEnv:hostEnv,autonomous:autonomous,claudePro:claudePro}=require("./deps.js"),{createEngine:createEngine,HOST_CLASSES:HOST_CLASSES,DEFAULT_CLASS:DEFAULT_CLASS,byokNamespace:byokNamespace,effortRung:effortRung,offeredClasses:offeredClasses,proEnabled:proEnabled}=require("./engine.js"),{GLYPH:GLYPH,VERBS:VERBS,themeOf:themeOf,RESET:RESET,THEME_TABLE:THEME_TABLE,AUTO_THEME_INDEX:AUTO_THEME_INDEX,themeIsLight:themeIsLight,reconcileThemeIndex:reconcileThemeIndex}=require("./theme.js"),{probeTerminalBackground:probeTerminalBackground}=require("./caps.js"),{LiveRegion:LiveRegion,termWidth:termWidth,w:w}=require("./screen.js"),{estimateTokensFromCells:estimateTokensFromCells}=require("./tokens.js"),{editPreview:editPreview}=require("./diff.js"),{defaultOpen:defaultOpen}=require("./diffview.js"),{parseLine:parseLine,COMMANDS:COMMANDS,visibleCommands:visibleCommands}=require("./commands.js"),{updateConfig:updateConfig,loadPermissions:loadPermissions,loadConfig:loadConfig,configExists:configExists,memoryPersistState:memoryPersistState,memoryPersistEnabled:memoryPersistEnabled,setMemoryPersist:setMemoryPersist,confirmPosture:confirmPosture}=require("./config.js"),credentials=require("./credentials.js"),events=require("./events.js"),cloudsync=require("./cloudsync.js"),{readSecret:readSecret}=require("./secret.js"),{normalizeModelCatalog:normalizeModelCatalog,pickerEntries:pickerEntries,catalogIds:catalogIds,providerForModel:providerForModel}=require("./models.js"),{appendHistory:appendHistory,readSessionTranscript:readSessionTranscript,readOwnSessions:readOwnSessions,setSessionTitle:setSessionTitle}=require("./history.js"),naming=require("./naming.js"),{snapshotCheckpoint:snapshotCheckpoint}=require("./checkpoint.js"),screens=require("./screens.js"),chatflow=require("./chatflow.js"),overlays=require("./overlays.js"),render=require("./render.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,maskKey:maskKey,feeBillable:feeBillable}=require("./format.js"),{resolveSkip:resolveSkip}=require("./permissions.js"),VERSION=require("../package.json").version;let _defaultSystem=null;function defaultSystemPrompt(){if(null===_defaultSystem)try{_defaultSystem=buildSystemPrompt(hostEnv({},{},null))}catch{_defaultSystem=""}return _defaultSystem||void 0}function normalizeDecision(e){const t="string"==typeof e?e.trim().toLowerCase():"";return"session"===t?"session":"once"===t||"allow"===t||"yes"===t||"approve"===t||"approved"===t?"once":"deny"}const PROVIDER_REFUSAL_PATTERNS=Object.freeze([/^invalid api key\b/i,/^fix external api key\b/i,/^you've hit your session limit\b/i,/^you have hit your session limit\b/i,/^provider request timed out\b/i,/^insufficient (?:credit|balance|quota)\b/i,/^rate limit(?:ed)?\b/i,/^unauthorized\b/i]);function providerRefusal(e,t){if("string"!=typeof e)return null;const n=t&&(t.total_tokens||0),r=t&&(t.output_tokens||t.completion_tokens||0);if(n>0||r>0)return null;const o=e.trim();if(!o||o.length>160||o.includes("\n"))return null;for(const e of PROVIDER_REFUSAL_PATTERNS)if(e.test(o))return o;return null}function briefArgs(e){let t;try{t="string"==typeof e?e:JSON.stringify(e??"")}catch{t=String(e)}return t=String(t).replace(/\s+/g," ").trim(),t.length>140?`${t.slice(0,137)}...`:t}function createApp(e={}){const t={model:null,stream:!0,light:!1,maxTokens:void 0,system:void 0,interactive:!0,...e},n=e.out||process.stdout,r=e.err||process.stderr,o=e.client||createClient(credentials.clientOptions({channel:"cli"})),{TOOLS:s,toolList:i}=e.tools||createTools(o);let a=!1,l="";async function c(){const e=await autoProvisionApiKey(o,credentials,{app:"cli"});return l=e.key?"":provisionFailureText(e),e}async function d(){if(o.apiKey||a)return;a=!0;const e=await c();e.key&&Y(render.renderNotice(b(),"info","auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.`))}let u=!1!==e.confirmMode,m=(()=>{try{return autonomous.autoRoundsDefault(process.env)}catch{return!0}})();const f=e.engine||createEngine({client:o,getClass:()=>g.modelClass,getProEnabled:()=>{try{return proEnabled(loadConfig())}catch{return!1}},getConfirmMode:()=>{if(void 0!==e.confirmMode)return u;try{const e=resolveSkip({env:process.env,interactive:Boolean(process.stdin.isTTY&&process.stdout.isTTY)});if(e.warned&&!skipEnvWarned&&(skipEnvWarned=!0,process.stderr.write(`aegiscode: ${e.warning}\n`)),e.skip)return!1}catch{}try{return confirmPosture().enabled}catch{return u}}}),p=e=>"function"==typeof f.classLabel?f.classLabel(e):String(e||"");let y=null;const h=()=>e.width?e.width():termWidth(),g={light:t.light,model:t.model,modelClass:DEFAULT_CLASS,effort:null,thinking:!1,recallDeep:!1,themeIndex:t.light?2:AUTO_THEME_INDEX,vim:!1,stream:t.stream,cwd:process.cwd(),lastRecap:null,sessionId:randomUUID()};g.themeIndex===AUTO_THEME_INDEX&&(g.light=themeIsLight(AUTO_THEME_INDEX));const k=[];let v=!1;const b=()=>({light:g.light}),S={turns:0,calls:0,tokens:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,cost:0,balance:null,seenLedgerRows:new Map,ledgerBaselined:!1,startedAt:Date.now()};let T=null,E=!1;function C(e){if(!e||"object"!=typeof e)return null;if("usage"!==e.kind)return null;const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6;return Number.isFinite(t)?Math.abs(t):null}function I(e){return[e.created_at||"",e.kind||"",null!=e.amount_eur?e.amount_eur:"",null!=e.charged_micros?e.charged_micros:"",null!=e.id?e.id:"",null!=e.note?e.note:""].join("|")}async function N(){try{const e=await o.tokenBankBalance(),t=Number(e.balance_eur);Number.isFinite(t)&&(S.balance=t);let n=null;const r=Array.isArray(e.ledger)?e.ledger:[],s=new Map;for(const e of r){const t=I(e),n=s.get(t);n?n.n+=1:s.set(t,{n:1,row:e})}for(const[e,{n:t,row:r}]of s){const o=S.seenLedgerRows.get(e)||0;if(S.seenLedgerRows.set(e,t),!S.ledgerBaselined)continue;const s=t-o;if(s<=0)continue;const i=C(r);null!=i&&i>0&&(S.cost+=i*s,null==n&&(n=i))}return S.ledgerBaselined=!0,{balance:S.balance,lastCost:n}}catch{return null}}async function P(e,{verify:t=!0}={}){const n=credentials.saveApiKey(e);if(!n.ok)return n;o.setApiKey(n.key),R.models=[],R.at=0;let r=null,s=null;if(t)try{const e=await o.verifyApiKey()||{};r=e;const t={verifiedAt:(new Date).toISOString()};e.memory_token&&(t.memoryToken=e.memory_token),e.plan&&(t.plan=e.plan),t.account={plan:e.plan||null,email:e.email||null,valid:!1!==e.valid},credentials.writeCredentials(t),e.plan&&(S.plan=e.plan),e.email&&(S.account={...S.account||{},email:e.email})}catch(e){s=e}return{...n,account:r,error:s}}function x(){const e=credentials.clearApiKey();return o.setApiKey(""),R.models=[],R.at=0,e}function A(){try{return memoryPersistEnabled()}catch{return!0}}function L(){try{return memoryPersistState()}catch{return{enabled:!0,source:"default",explicit:!1}}}function O(e){return setMemoryPersist(e)}function _(){try{return"config"!==credentials.resolveApiKey().source?[]:credentials.adoptLegacy().adopted}catch{return[]}}const M=3e5,R={at:0,models:[]},$={at:0,models:[],declared:""};async function K({force:e=!1}={}){const t=function(){try{if("function"!=typeof f.userModels)return"";const e=(f.userModels()||{}).map||{};return JSON.stringify(Object.keys(e).sort().map((t=>[t,e[t]])))}catch{return""}}(),n=$.models.length&&Date.now()-$.at<M&&t===$.declared;if(!e&&n)return $.models;if("function"!=typeof f.listModels)return[];const r=await f.listModels("byok");return $.models=(r&&r.models||[]).map((e=>({...e,note:e.configured?"key on this machine":`no key — /byok-key ${e.provider}`}))),$.at=Date.now(),$.declared=t,$.models}async function D(e){const t=H();if(e&&!t.includes(e)&&HOST_CLASSES.includes(e))return[];const n=t.includes(e)?e:g.modelClass;try{if("byok"===n){const e=await K();if(!R.models.length)try{await F()}catch{}return q(e,n)}if("pro"===n){const e=await f.listModels("pro");return e&&e.models||[]}if("aegis"!==n){const e=await f.listModels(n);return e&&e.models||[]}return await F()}catch{return[]}}function j(){return pickerEntries(R.models).map((e=>({...e,cls:"aegis"})))}function q(e,t){const n=H(),r=n.includes(t)?t:g.modelClass;if("pro"===t&&!n.includes("pro"))return[];if("pro"===r)return pickerEntries(claudePro.PRO_MODELS.map((e=>({id:e.id,label:e.label,note:e.note})))).map((e=>({...e,cls:"pro"})));if("byok"!==r)return j();const o=Array.isArray(e)?e.map((e=>({...e,cls:"byok"}))):pickerEntries($.models).map((e=>({...e,cls:"byok"})));return[...j(),...o]}function B(){return new Set(claudePro.PRO_MODELS.map((e=>String(e.id).toLowerCase())))}function H(){try{return offeredClasses(proEnabled(loadConfig()))}catch{return offeredClasses(!1)}}async function F({force:e=!1}={}){const t=R.models.length&&Date.now()-R.at<M;if(!e&&t)return R.models;const n=await o.listModels();return R.models=normalizeModelCatalog(n&&n.models),R.at=Date.now(),R.models}async function U(){const e=g.model;if(!e)return null;if("byok"===g.modelClass)return String(e).includes(":")?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" belongs to the pooled class — on BYOK an id is "<provider>:<model>"; pin cleared, /models lists what this machine can relay.`)),e);if("pro"===g.modelClass){if(!B().has(String(e).toLowerCase()))return g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" is not one the Claude Code CLI resolves — pin cleared, the CLI will choose; /models lists the aliases (${claudePro.PRO_MODELS.map((e=>e.id)).join(", ")}).`)),e;let t=!0;try{t=!!claudePro.claudeProStatus({env:process.env}).credentialPresent}catch{t=!0}return t?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" needs a Claude Pro subscription or an ANTHROPIC_API_KEY, and this host has neither — pin cleared. Run \`claude /login\`, export a console key, or \`/class pro off\`.`)),e)}let t;try{t=await F()}catch{return null}return t.length?catalogIds(t).has(String(e).toLowerCase())?null:(g.model=null,updateConfig({model:null,currentModelId:null}),Y(render.renderNotice(b(),"warn",`pinned model "${e}" is not advertised by AEGIS Cloud — pin cleared, the pool will choose; /models lists what you can pin.`)),e):null}function W(){return render.renderBanner(b(),{width:h(),version:VERSION,model:g.model||"server default",base:o.apiBase,key:maskKey(o.apiKey),stream:g.stream})}function Y(e){const t="string"==typeof e?[e]:e;for(const e of t)n.write(e+"\n")}async function V(e,{history:o=[],presenter:s=null,signal:i=null}={}){const a=Date.now(),l=!s&&t.interactive&&t.stream&&n.isTTY?new LiveRegion(n):null;let c=0,d=0,u="",m=0,p=0,k=VERBS[Math.floor(Math.random()*VERBS.length)],v=!1,S=!1;const E=()=>{l&&l.update([render.renderWorking(b(),{tick:c++,verb:k,elapsedMs:Date.now()-a,streamed:estimateTokensFromCells(d+m)+p,streamedFloor:p>0})])},C=l?setInterval(E,90):null;C&&C.unref&&C.unref(),E();const I=s||{},N=new Map,P=randomUUID();T=P;let x=!1;const A=()=>{x=!0,f.cancel(P)},L=()=>A();process.once("SIGINT",L),i&&(i.aborted?A():i.addEventListener("abort",A,{once:!0}));const O=e=>(r.write(`aegiscode: ${e.tool} needs confirmation but this run has no prompt for it — denied (pass --automode (alias --yolo) to auto-approve mutating tools).\n`),Promise.resolve("deny")),_=()=>Promise.resolve(!1),M=e=>{if(e){if(e.thinkingTokens&&(p+=e.thinkingTokens,v||(v=!0,k="Reasoning"),(e=>{I.thinkingTokens&&I.thinkingTokens(e)})(e.thinkingTokens),E()),e.reasoning&&(m+=w(e.reasoning),v||(v=!0,k="Reasoning",E()),(e=>{I.reasoning&&I.reasoning(e)})(e.reasoning)),e.delta&&(d+=w(e.delta),u+=e.delta,(e=>{if(I.text)return I.text(e);l&&c%2==0&&E()})(e.delta)),e.tool&&(S=!0,(e=>{if(I.tool)return I.tool(e);l&&l.clear();const t=(e=>{const t=e&&void 0!==e.id?`id:${e.id}`:`${e&&e.name}:${JSON.stringify(e&&e.args)}`;return N.has(t)||N.set(t,editPreview(e&&e.name,e&&e.args,{cwd:process.cwd()})),N.get(t)})(e);Y(render.renderTurn(b(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:defaultOpen(t)},h())),E()})(e.tool)),e.approval){const t=e.approval;l&&l.clear();const n=I.approval||y||O;Promise.resolve(n(t)).catch((()=>"deny")).then((e=>f.respondApproval(t.id,normalizeDecision(e))))}if(e.rounds){const t=e.rounds;l&&l.clear();const n=I.rounds||_;Promise.resolve(n(t)).catch((()=>!1)).then((e=>f.respondRoundsAsk(t.id,!0===e)))}}};try{const n=await f.chat({prompt:e,messages:o,model:g.model||void 0,system:t.system||defaultSystemPrompt(),maxTokens:t.maxTokens,effort:effortRung(g.effort),recallDeep:!0===g.recallDeep||void 0,stream:!1!==g.stream,sessionId:P,sessionKey:g.sessionId,roundsAsk:Boolean(I.rounds)},M),r=n.choices&&n.choices[0]||{};return{text:r.message&&r.message.content||u,usage:n.usage||null,model:n.model||g.model||null,ms:Date.now()-a,interrupted:x,reasoningChars:m,usedTools:S}}catch(e){if(x&&u)return{text:u,usage:null,model:g.model||null,ms:Date.now()-a,interrupted:!0,reasoningChars:m,usedTools:S};throw e}finally{C&&clearInterval(C),process.removeListener("SIGINT",L),i&&i.removeEventListener("abort",A),l&&l.clear(),T=null}}function G(e){Y(render.renderTurn(b(),e,h()))}async function z(e,{label:t="you"}={}){if(!e)return void Y(render.renderNotice(b(),"warn","nothing to ask — give /ask a prompt"));if(o.apiKey||await d(),!o.apiKey)return void Y(render.renderNotice(b(),"error",`no AEGIS account key — ${credentials.HOW_TO_SET} (or set $${credentials.KEY_ENV})`));const n=k.filter((e=>"user"===e.role||"assistant"===e.role)).map((e=>({role:e.role,content:e.text})));let r;G({role:"user",text:e,label:t}),k.push({role:"user",text:e});try{r=await V(e,{history:n})}catch(t){return ae(e,{text:"",error:t.message},"error"),void Y(render.renderTurn(b(),{role:"error",text:t.message},h()))}r.text&&k.push({role:"assistant",text:r.text});const s=ie(r);let i=null;try{const e=await N();i=e?e.lastCost:null}catch{}ae(e,r,r.interrupted?"stopped":r.error?"error":"done",i),G({role:"assistant",text:r.text||"(the pool returned no text — see /balance for what it charged)",meta:{model:r.model,tokens:s,usage:null==r.usage?null:usageBuckets(r.usage),eur:i,ms:r.ms,calls:1}}),r.interrupted&&Y(render.renderNotice(b(),"warn","interrupted — the pool may still be running and billing this call"))}async function X(e,t){const n=s[e];if(!n)throw new Error(`unknown tool: ${e}`);if(o.apiKey||await d(),!o.apiKey)throw new Error(`no AEGIS account key — ${credentials.HOW_TO_SET}`);const r=await n.run(t||{});Y(render.renderToolResult(b(),e,r,h()))}function J(e){const t=String(e||"").toLowerCase();if(!t)return null;let n=null;for(const e of COMMANDS)for(const r of[e.name,...e.aliases||[]])r!==t&&(r.startsWith(t)||t.startsWith(r))&&(null==n||Math.abs(r.length-t.length)<Math.abs(n.length-t.length))&&(n=r);return n}function Q(){const e=loadPermissions(),t=confirmPosture();return{version:VERSION,model:g.model||"server default",class:g.modelClass,effort:g.effort,thinking:g.thinking,theme:g.light?"light":"dark",themeIndex:g.themeIndex,vim:g.vim,stream:g.stream,cwd:g.cwd,home:os.homedir(),sessionId:g.sessionId,base:o.apiBase,keyMask:maskKey(o.apiKey),online:!!o.apiKey,turns:S.turns,calls:S.calls,startedAt:S.startedAt,tokens:{input:S.inputTokens,output:S.outputTokens,cacheRead:S.cacheReadTokens,cacheWrite:S.cacheWriteTokens,total:S.tokens},costEur:S.cost,balance:S.balance,plan:S.plan||null,account:S.account||null,permissions:{mode:t.enabled?e.defaultMode:"allow",confirm:t.enabled,source:t.source,rules:e},models:q(),commands:visibleCommands(),transcript:k.slice(),sessions:[],memory:{},lastRecap:g.lastRecap,backend:g.modelClass,url:o.apiBase}}function Z(e){return Array.isArray(e)?e.map((e=>e&&(e.s||"")+(null==e.t?"":e.t)||"")).join(""):String(null==e?"":e)}function ee(e){if(!e||"object"!=typeof e)return;const t=h();switch(e.role){case"panel":{const t=Array.isArray(e.lines)?e.lines:[];for(const e of t)Y(Z(e));return}case"note":case"tip":return void Y(render.renderNotice(b(),"info",e.text));case"done":return void Y(render.renderNotice(b(),"ok",e.text));case"error":return void Y(render.renderNotice(b(),"error",e.text));case"user":return void Y(render.renderTurn(b(),{role:"user",text:e.text,label:e.label},t));case"assistant":return void Y(render.renderTurn(b(),{role:"assistant",text:e.text},t));case"tool":return void 0===e.diff&&(e.diff=editPreview(e.name||e.label,e.args,{cwd:process.cwd()}),e.diffOpen=defaultOpen(e.diff)),void Y(render.renderTurn(b(),{role:"tool",label:e.label||e.name,args:e.args,ok:e.ok,diff:e.diff,diffOpen:!!e.diffOpen},t));default:return void Y(render.renderNotice(b(),"info",null==e.text?"":String(e.text)))}}function te(e){return{t:e,s:"",w:w(e)}}async function ne(){return!e.readline&&process.stdin.isTTY&&process.stdout.isTTY&&!1!==e.chatflow?screens.showThemePicker(g):(g.light=!g.light,g.themeIndex=g.light?2:1,Y(render.renderNotice(b(),"ok","theme: "+(g.light?"light":"dark"))),g.themeIndex)}function re(){const e={ctx:g,transcript:k,push:e=>ee(e),note:e=>ee({role:"note",text:e}),panel:e=>ee({role:"panel",lines:e}),render:()=>{},openOverlay:e=>function(e){if(!e||"object"!=typeof e)return;const t=h(),n=Math.max(5,process.stdout&&process.stdout.rows||24);let r=null;if("panel"===e.type?r=e.lines:"palette"===e.type?r=overlays.renderPalette(visibleCommands(),{query:e.query||"",sel:e.sel||0},t,n):"model"===e.type?r=overlays.renderModelPicker(e.items||[],e.sel||0,t,n,null!=e.current?e.current:g.model,e.cls||g.modelClass,p):"effort"===e.type?r=overlays.renderEffortPicker(e.sel||0,t,g.effort):"class"===e.type?r=overlays.renderClassPicker(e.items||[],e.sel||0,t,e.current||g.modelClass,p):"provider"===e.type?r=overlays.renderProviderPicker(e.items||[],e.sel||0,t,e.current,e.hint):"resume"===e.type?r=overlays.renderResumeList(e.items||[],e.sel||0,t,n):"confirm"===e.type&&(r=render.renderApproval(b(),e.info||{},t).map((e=>[te(e)]))),r)for(const e of r)Y(Z(e))}(e),closeOverlay:()=>{},setAutoRounds:e=>{m=Boolean(e)},askInput:()=>Promise.resolve(null),withWorking:e=>async function(e){const r=new AbortController,o=t.interactive&&n.isTTY?new LiveRegion(n):null;let s=null;if(o){let e=0;const t=Date.now(),n=()=>o.update([render.renderWorking(b(),{tick:e++,verb:VERBS[0],elapsedMs:Date.now()-t})]);n(),s=setInterval(n,90),s.unref&&s.unref()}try{return await e(r.signal)}finally{s&&clearInterval(s),o&&o.clear()}}(e),runPrompt:e=>z(e),ask:e=>V(e),runTool:(e,t)=>X(e,t),loadModels:()=>D(g.modelClass),settings:()=>f.settings||null,byokNamespace:e=>byokNamespace(e),listModelsFor:e=>D(e),refreshByokModels:()=>K({force:!0}),switchClass:e=>function(e){const t=String(null==e?"":e).trim().toLowerCase(),n=H();if(!n.includes(t))return"pro"===t?{ok:!1,error:"the pro class (your Claude Code subscription) is off by default — enable it once with `/class pro on`"}:{ok:!1,error:`unknown class "${e}" — classes: ${n.join(", ")}`};const r=g.modelClass;g.modelClass=t;let o=null;return r!==t&&g.model&&(function(e,t){const n=String(null==t?"":t);return"byok"===e?n.includes(":"):"pro"===e?B().has(n.toLowerCase()):!n.includes(":")}(t,g.model)||(o=g.model,g.model=null)),updateConfig({modelClass:t,model:g.model,currentModelId:g.model}),{ok:!0,class:t,prev:r,cleared:o}}(e),classLabel:e=>p(e),classes:()=>"function"==typeof f.listClasses?f.listClasses():[],refreshSpend:()=>N(),state:()=>Q(),setInput:()=>{},exit:()=>{v=!0},client:o,TOOLS:s,saveConfig:e=>updateConfig(e),showThemePicker:()=>ne(),keyStatus:()=>credentials.keyStatus(),setApiKey:(e,t)=>P(e,t),forgetApiKey:()=>x(),registerAccount:()=>async function(){return o.apiKey?{alreadyKeyed:!0}:c()}(),readSecret:e=>readSecret(e,{stdin:process.stdin,stdout:n}),cloudsync:cloudsync,cloudSyncEnabled:()=>A(),cloudSyncState:()=>L(),setCloudSync:e=>O(e),adoptLegacyKey:()=>_()};return Object.defineProperty(e,"sessionId",{enumerable:!0,get:()=>g.sessionId,set:e=>{g.sessionId=e}}),e.clearConversationMemory=()=>{f&&"function"==typeof f.clearSessionApprovals&&f.clearSessionApprovals(g.sessionId)},e}async function oe(e,t=null){const r=parseLine(e);if("empty"===r.kind)return!0;if("prompt"===r.kind)return await z(r.text),!0;if("unknown"===r.kind){const e=J(r.name);return Y(render.renderNotice(b(),"error",`unknown command: /${r.name}${e?` — did you mean /${e}?`:" — try /help"}`)),!0}if("unavailable"===r.kind){const e=r.command;if(Y(render.renderNotice(b(),"warn",`/${e.name} is not available in aegiscode — ${e.unavailable}`)),e.alt)Y(render.renderNotice(b(),"info",`try ${e.alt} instead`));else{const t=J(e.name);t&&Y(render.renderNotice(b(),"info",`try /${t} instead`))}return!0}const s=r.command,i=r.arg;if(s.generic){let t;try{t=s.build(i)}catch(e){return Y(render.renderNotice(b(),"error",e.message)),!0}const{tool:n,args:r}=t;if(!n)return Y(render.renderNotice(b(),"error","/tool needs a tool name — see /help")),!0;try{await X(n,r)}catch(e){Y(render.renderNotice(b(),"error",e.message))}return!0}if("function"==typeof s.handler){const n=function(e,t){const n=String(null==t?"":t),r=Array.isArray(e.args)?e.args:[],o=function(e){const t=[];let n="",r=null,o=!1;for(const s of String(e||""))r?s===r?r=null:n+=s:'"'!==s&&"'"!==s?/\s/.test(s)?(n||o)&&(t.push(n),n="",o=!1):(n+=s,o=!0):(r=s,o=!0);return(n||o)&&t.push(n),t}(n),s={_rest:n.trim()};return r.forEach(((e,t)=>{void 0!==o[t]&&(s[e]=o[t])})),s}(s,i),r=t||re();try{return!1!==await s.handler(r,n)}catch(e){return Y(render.renderNotice(b(),"error",e&&e.message?e.message:String(e))),!0}}try{let e=s.build(i);if(s.secret){const t=await async function(e,t){if("function"!=typeof e.secretDescribe)return null;try{const n=await e.secretDescribe(t,o);return n&&"object"==typeof n?n:null}catch{return null}}(s,e);if(t&&t.note&&Y(render.renderNotice(b(),"info",t.note)),t&&null===t.prompt)return!0;t&&t.provider&&(e={...e,provider:t.provider});const r=await function(e){const t=themeOf(b());return readSecret(t.gray+e+RESET,{stdin:process.stdin,stdout:n})}(t&&t.prompt||`provider key for ${e.provider}: `);if(!r)return Y(render.renderNotice(b(),"warn","empty key — nothing sent")),!0;e={...e,api_key:r}}if("aegis_ask"===s.tool)return await z(e.prompt);await X(s.tool,e),"aegis_memory_list"!==s.tool&&"aegis_memory_search"!==s.tool||function(){let e;try{e=cloudsync.status()}catch{return}const t=e.quota;if(!t)return;const n=fmtTokens(t.used||0),r=fmtTokens(t.limit||0);e.overQuota?Y(render.renderNotice(b(),"warn",`cloud memory: ${n} of ${r} synced tokens — at the plan's ceiling. Everything stored stays readable; new writes are paused until there is room. /cloud memory for the full state.`)):Y(render.renderNotice(b(),"info",`cloud memory: ${n} of ${r} synced tokens — /cloud memory for the full state`))}()}catch(e){Y(render.renderNotice(b(),"error",e.message))}return!0}async function se(){if(f&&"function"==typeof f.unloadLocalModels)try{await f.unloadLocalModels()}catch{}}function ie(e){S.turns++,S.calls+=Number(e&&e.calls||1)||1;const t=e&&e.usage,n=usageTokens(t);if(null!=n){S.tokens+=n;const e=usageBuckets(t);S.inputTokens+=e.input,S.outputTokens+=e.output,S.cacheReadTokens+=e.cacheRead,S.cacheWriteTokens+=e.cacheWrite}return n}function ae(e,t,n="done",r=null){try{const o=t&&t.usage,s="number"==typeof r&&Number.isFinite(r)?r:null,i=String(t&&t.model||g.model||"").trim();appendHistory({sessionId:g.sessionId,prompt:e,reply:t&&t.text||"",status:n,model:i||void 0,provider:i&&providerForModel({id:i,cls:g.modelClass})||void 0,usage:o?{...usageBuckets(o),...null!=s?{costUsd:s}:{}}:null!=s?{input:0,output:0,cacheRead:0,cacheWrite:0,costUsd:s}:null}),snapshotCheckpoint(g.sessionId,k)}catch{}A()&&o.apiKey&&Promise.resolve().then((()=>cloudsync.push(o))).then((e=>{if(e&&e.failed&&e.failed.length){const t=e.failed[0];if(le.has(t.kind))return;if(le.add(t.kind),"quota"===t.kind)return void Y(render.renderNotice(b(),"warn","cloud memory: the plan's synced-token ceiling is reached — earlier sessions stay readable, only NEW writes pause. /cloud memory shows the quota; /cloud memory off stops trying."));const n=t.hint?` — ${t.hint}`:"";Y(render.renderNotice(b(),"error",`cloud sync: ${t.message}${n}`))}})).catch((()=>{}))}let le=new Set;function ce(){const e=[S.outputTokens>0?`${fmtTokens(S.outputTokens)} tokens`:`${fmtTokens(S.tokens)} tokens`,`${S.calls} call${1===S.calls?"":"s"}`];return feeBillable()&&(e.push(fmtEur(S.cost)),null!=S.balance&&e.push(`balance ${fmtEur(S.balance)}`)),e.join(" · ")}async function de(e){if(!e||!e.id)return;const t=readSessionTranscript(e.id);if(t.length){k.length=0;for(const e of t)k.push(e);g.sessionId=e.id,Y(render.renderNotice(b(),"ok",`resumed ${e.id} — ${t.length} turn(s)`))}else Y(render.renderNotice(b(),"warn",`no stored turns for ${e.id}`))}function ue(){return{ctx:g,version:VERSION,transcript:k,session:S,client:o,TOOLS:s,ask:(e,t)=>V(e,t),makeCommandContext:()=>re(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=f.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},loadModels:e=>F(e),buildState:()=>Q(),dispatchLine:(e,t)=>oe(e,t),refreshSpend:()=>N(),updateConfig:e=>updateConfig(e),showThemePicker:()=>ne(),persistTurn:(e,t,n,r)=>ae(e,t,n,r),nameConversation:(e,t)=>async function(e,{signal:t=null}={}){const n=await naming.nameConversation(e,{signal:t,callModel:(e,n)=>V(e,{system:n&&n.system||naming.TITLE_SYSTEM,maxTokens:64,signal:n&&n.signal||t}).then((e=>e&&e.text||null))}),r=String(n||"").trim();return r&&setSessionTitle(g.sessionId,r),r}(e,t),visibleCommands:()=>visibleCommands(),tokensFor:e=>usageTokens(e),recordTurn:e=>ie(e),tokenSummary:()=>ce(),resumeSession:e=>de(e),requestExit:()=>{v=!0},wantsExit:()=>v,keyNotice:()=>o.apiKey?"":l,isYolo:()=>{if(!m)return!1;try{return!1===confirmPosture().enabled}catch{return!1}},setAutoRounds:e=>{m=Boolean(e)}}}async function me(){Y(W()),await N(),n.write("\n");const t=e.readline||readline.createInterface({input:process.stdin,output:n,terminal:!0}),r=themeOf(b()).gold+GLYPH.cursor+" "+RESET;return t.setPrompt(r),t.prompt(),new Promise((e=>{t.on("line",(async e=>{t.pause();let n=!0;try{n=await oe(e)}catch(e){Y(render.renderNotice(b(),"error",e.message))}if(!n||v)return E=!0,void t.close();t.resume(),t.prompt()})),t.on("close",(()=>{E||n.write("\n"),e(0)}))}))}function fe(){if(e.readline)return;if(!configExists())return;let n;try{n=loadConfig()}catch{return}if(H().includes(n.modelClass)&&(g.modelClass=n.modelClass),t.class){const e=String(t.class).trim().toLowerCase();if(!H().includes(e))throw new Error(`--class ${t.class}: not available on this host (offered: ${H().join(", ")})`);g.modelClass=e}if(!t.model&&n.model&&(g.model=n.model),g.effort=effortRung(t.effort||n.effort),"boolean"==typeof n.vim&&(g.vim=n.vim),n.lastRecap&&(g.lastRecap=n.lastRecap),!t.light&&"number"==typeof n.themeIndex&&THEME_TABLE[n.themeIndex]){g.themeIndex=n.themeIndex,g.light=themeIsLight(n.themeIndex);const e=reconcileThemeIndex(g.themeIndex);if(e.changed){g.themeIndex=e.index,g.light=themeIsLight(e.index),g.themeNotice=e.reason;try{updateConfig({themeIndex:e.index,light:themeIsLight(e.index)})}catch{g.themeNotice+=" (could not save it)"}}}}return{opts:t,session:S,client:o,TOOLS:s,toolList:i,ctx:g,transcript:k,ask:V,runPrompt:z,handleLine:oe,runOnce:async function(e,t={}){try{return await async function(e,{json:t=!1}={}){if(fe(),_(),!o.apiKey&&!a){a=!0;const e=await autoProvisionApiKey(o,credentials,{app:"cli"});e.key&&r.write("aegiscode: auto-provisioned a free account"+(e.ok?` (saved to ${credentials.credentialsPath()})`:" (could not save it — reconfigure with /key)")+trialNote(e)+`. Fund it at ${o.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.\n`)}if(!o.apiKey)return r.write(`aegiscode: no AEGIS account key. ${credentials.HOW_TO_SET}, or set $${credentials.KEY_ENV}.\n`),2;await N();const s=[],i=[],l=t?{tool:e=>{if("done"===(e&&e.phase)){const t=e.id&&i.find((t=>t.id===e.id&&!0!==t.settled))||(e.id?null:i[i.length-1]);t?(t.settled=!0,t.ok=!1!==e.ok):(e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!0,ok:!1!==e.ok}))}else e&&e.name&&s.push(e.name),i.push({name:e&&e.name||null,id:e&&e.id||null,args:briefArgs(e&&e.args),settled:!1,ok:null});const t=e&&void 0!==e.preview?e.preview:null,n=render.renderTurn(b(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:!1},h());for(const e of Array.isArray(n)?n:[n])r.write(e+"\n")}}:null,c=await V(e,l?{presenter:l}:{});await N();const d=usageTokens(c.usage),u=providerRefusal(c.text,c.usage);if(t)n.write(JSON.stringify({text:c.text,model:c.model,class:g.modelClass,rounds:c.usage&&Number(c.usage.calls)||null,usage:c.usage,reasoning_chars:"number"==typeof c.reasoningChars?c.reasoningChars:null,tokens:d,ms:c.ms,interrupted:c.interrupted,...s.length?{tools:s}:{},...i.length?{tool_log:i}:{},...u?{error:u}:{},balance_eur:S.balance},null,2)+"\n");else if(n.write(c.text+"\n"),u&&r.write(`aegiscode: the provider refused this turn — ${u}\n`),null!=d){const e=themeOf(b());n.write(e.dim+GLYPH.hook+" "+e.blue+(c.model||"aegis")+RESET+e.dim+" "+GLYPH.bullet+" "+RESET+e.white+`${fmtTokens(d)} tokens`+RESET+"\n")}return c.interrupted?130:u?1:0}(e,t)}finally{await se()}},runInteractive:async function(){try{return await async function(){if(!e.readline&&!1!==e.chatflow&&process.stdin.isTTY&&process.stdout.isTTY){await probeTerminalBackground({onLeftover:e=>events.feedKeys(e,{keystrokes:!0})}),fe(),function(){if(!g.themeNotice)return;const e=g.themeNotice;g.themeNotice="",Y(render.renderNotice(b(),"warn",`theme: ${e} (saved)`))}(),_(),o.apiKey||await d();const t=await screens.runOnboarding(g,{continue:!!e.continue,seen:e.seen||configExists,save:e=>updateConfig(e),needsKey:()=>!o.apiKey,submitKey:e=>P(e)});if(!t.ok)return 0;if(t.key&&t.key.set&&Y(render.renderNotice(b(),"info",`key saved to ${credentials.credentialsPath()} — no export needed from now on`)),t.key&&t.key.skipped&&!o.apiKey&&Y(render.renderNotice(b(),"warn","no key saved — /key <api_key> or `aegiscode login` whenever you are ready")),t.firstRun&&function(){if(!L().enabled)return void Y(render.renderNotice(b(),"info","cross-session memory: off (you turned it off) — /cloud memory on stores sessions so an interrupted turn can be picked up later"));const e=cloudsync.status().quota,t=e&&e.limit?` (used ${fmtTokens(e.used||0)} of ${fmtTokens(e.limit)} tokens)`:"";Y(render.renderNotice(b(),"info",`cross-session memory: on${t} — sessions are stored to your account so a turn that is interrupted can be resumed. /cloud memory shows the quota; /cloud memory off stops it. Past the ceiling, saved memory stays readable and only new writes pause.`))}(),await U(),e.continue){const e=readOwnSessions(1)[0];e&&(g.continueSession=e.id,await de({id:e.id}))}return await N(),await chatflow.runSession(ue()),0}return fe(),_(),me()}()}finally{await se()}},runLinearRepl:me,refreshSpend:N,bannerLines:W,makeHost:ue,loadModels:F,validatePinnedModel:U,recordTurn:ie,persistTurn:ae,restorePrefs:fe,setApiKey:P,forgetApiKey:x,adoptLegacyKeyOnce:_,cloudSyncEnabled:A,cloudSyncState:L,setCloudSync:O,cloudsync:cloudsync,keyStatus:()=>credentials.keyStatus(),accountConfigured:()=>!!(credentials.keyStatus()||{}).configured,hasProviderKey:e=>{const t=f.settings;if(!t||!e)return!1;const n=byokNamespace(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},sessionId:()=>g.sessionId,tokenSummary:ce,resumeSession:de,makeCommandContext:re,buildState:Q,get aborted(){return!1}}}module.exports={createApp:createApp,VERSION:VERSION,normalizeDecision:normalizeDecision};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";const{caps:caps,detect:detect,cells:cells,padCells:padCells}=require("./caps.js");function capsOf(t){return t?"string"==typeof t?detect(process.env,process.stdout,t):t:caps()}const WELCOME_MARK=["╔═╗╔═╗╔═╗╦╔═╗","╠═╣║╣ ║ ╦║╚═╗","╩ ╩╚═╝╚═╝╩╚═╝"],WELCOME_ART=WELCOME_MARK,WELCOME_ART_STACKED=WELCOME_MARK,WELCOME_TITLE="Welcome to AEGIS Code",WELCOME_BACK="Welcome back!",TAGLINE="Your intent, AI automated.",TAGLINE_SHORT="Your intent, automated.",STAR="✦",EDGE_RUNES=["▐","▛","▜","▌","▝","▘"],BOX_RUNES=["╔","╗","╚","╝","╠","╣","╦","╩","║","═"],BOX_STENCIL=new Map([...["╔","╗","╚","╝","╠","╣","╦","╩"].map((t=>[t,"+"])),["═","-"],["║","|"]]),ASCII_STENCIL=new Map([...BOX_STENCIL,["█","#"],["▓","@"],["▒","="],["░","."],...EDGE_RUNES.map((t=>[t,"#"])),["✦","*"],["·","."]]),EDGE_STENCIL=new Map(EDGE_RUNES.map((t=>[t,"#"]))),STAR_STENCIL=new Map([["✦","*"]]),STENCILS={ascii:ASCII_STENCIL,edges:EDGE_STENCIL,star:STAR_STENCIL},PASSES=["native","star","edges","ascii"];function stencilFor(t=null){const e=capsOf(t);if("ascii"===e.glyphs)return ASCII_STENCIL;const E=new Map;if("edges"===e.face)for(const[t,e]of EDGE_STENCIL)E.set(t,e);if("narrow"===e.star)for(const[t,e]of STAR_STENCIL)E.set(t,e);return E.size?E:null}function stencilGlyph(t,e=null){const E=stencilFor(e);return E&&E.get(t)||t}function portabilityFor(t,e=null){const E=stencilFor(e);return E?t.map((t=>[...t].map((t=>E.get(t)??t)).join(""))):t}function portability(t){return portabilityFor(t,null)}function welcomeArtFor(){return portability(WELCOME_ART)}function welcomeArtParts(){const t=portability(WELCOME_MARK);return{rows:t.map((t=>[t,""])),width:Math.max(...t.map(cells)),gutter:0}}function center(t,e){return t.map((t=>{const E=Math.max(0,Math.floor((e-cells(t))/2));return" ".repeat(E)+padCells(t,e-E)}))}function padBoth(t,e){const E=Math.max(...t.map(cells));return t.map((t=>{const r=Math.floor((e-E)/2);return" ".repeat(Math.max(0,r))+t}))}module.exports={WELCOME_MARK:WELCOME_MARK,WELCOME_ART:WELCOME_ART,WELCOME_ART_STACKED:WELCOME_ART_STACKED,WELCOME_TITLE:WELCOME_TITLE,WELCOME_BACK:WELCOME_BACK,TAGLINE:TAGLINE,TAGLINE_SHORT:TAGLINE_SHORT,STAR:"✦",EDGE_RUNES:EDGE_RUNES,BOX_RUNES:BOX_RUNES,PASSES:PASSES,STENCILS:STENCILS,stencilFor:stencilFor,stencilGlyph:stencilGlyph,portability:portability,portabilityFor:portabilityFor,welcomeArtFor:welcomeArtFor,welcomeArtParts:welcomeArtParts,center:center,padBoth:padBoth};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";const path=require("node:path"),{queue:queue,autonomous:autonomous}=require("./deps.js"),{createEngine:createEngine,proEnabled:proEnabled}=require("./engine.js"),{loadConfig:loadConfig}=require("./config.js"),{fmtElapsed:fmtElapsed}=require("./format.js"),limits=require("./limits.js"),SUBCOMMANDS=new Set(["add","list","run","proceed","reconcile","clear","retry","help"]),EXECUTES=new Set(["run","proceed","retry","reconcile"]);function parseFlags(e){const t={terms:[],json:!1,flags:{}},n=new Set(["cwd","model","effort","workers","max","max-rounds","source","class"]);for(let o=0;o<e.length;o++){const r=e[o];if("--json"!==r)if(r.startsWith("--")){const[s,i]=r.slice(2).split("="),a=s.trim();if(new Set(["commit","all","auto","stop-on-error","single-pass","help"]).has(a)){t.flags[a]=!0;continue}if(!n.has(a))throw new Error(`unknown option: --${a}`);const u=void 0!==i?i:e[++o];if(void 0===u)throw new Error(`--${a} needs a value`);t.flags[a]=u}else t.terms.push(r);else t.json=!0}return t}function intFlag(e,t){const n=e[t];if(void 0===n||""===n)return null;const o=Number.parseInt(n,10);return Number.isFinite(o)&&o>0?o:null}function taskLine(e){const t=e.model||"(default)",n=String(e.status||"?").padEnd(7),o=`#${e.id}`.padEnd(4),r=String(e.task||"").replace(/\s+/g," ").trim();return`${o} ${n} ${t} ${r.length>72?`${r.slice(0,71)}…`:r}`}function describeCounts(e){const t={pending:0,running:0,done:0,error:0};for(const n of e)void 0!==t[n.status]&&(t[n.status]+=1);return t}function printRunReport(e,t){for(const n of e){const e=Boolean(n.ok&&n.stoppedOnRounds),o=e?"⏸":n.ok?"✓":"✗",r=e?"paused — will resume":n.ok?"done":"failed";if(t.stdout.write(`aegiscode: ${o} #${n.id} ${r} (${fmtElapsed(n.ms)})`),n.commit&&n.commit.ok&&n.commit.staged?t.stdout.write(` — committed ${n.commit.staged} path(s)`):n.commit&&n.commit.skipped&&n.commit.reason&&t.stdout.write(` — no commit (${n.commit.reason})`),t.stdout.write("\n"),!n.ok&&n.error&&t.stderr.write(`aegiscode: #${n.id}: ${n.error}\n`),n.ok&&n.output){const e=String(n.output).trim();t.stdout.write(`${e.length>4e3?`${e.slice(0,4e3)}\n… [output clipped]`:e}\n`)}}}function buildEngine({io:e,quiet:t=!1}){const n=require("./credentials.js"),o=require("./deps.js").createClient(n.clientOptions({channel:"cli"}));if(!o.apiKey)return{error:`no AEGIS account key — ${n.HOW_TO_SET}, or set ${n.KEY_ENV}`};const r=createEngine({client:o,getConfirmMode:()=>!1,getProEnabled:()=>{try{return proEnabled(loadConfig())}catch{return!1}}});let s=null;try{s=require("./entitlement.js").createCliEntitlement({aegis:o})}catch{s=null}return{client:o,engine:r,entitlement:s}}function progressSink(e,{json:t}){return t?()=>{}:t=>{if(t&&"object"==typeof t)if("start"!==t.type)if("tool"===t.type&&t.tool&&"run"===t.tool.phase){const n=t.tool.args||{},o=n.command||n.pattern||autonomous.writtenPath(t.tool)||"",r=String(o).slice(0,100);e.stderr.write(` ⚙ ${t.tool.name}${r?` ${r}`:""}\n`)}else"healed"!==t.type?"note"===t.type&&t.note?e.stderr.write(` ⓘ ${t.note}\n`):"recovered"===t.type&&e.stdout.write(`aegiscode: re-queued task(s) ${t.ids.join(", ")} from a dead worker\n`):e.stdout.write(`aegiscode: PLAN.md status list healed for phase(s) ${t.phases.join(", ")}\n`);else e.stdout.write(`aegiscode: #${t.taskId} running on ${t.model} in ${t.cwd}\n`)}}async function runQueueCommand(e,t,n={}){const o=n.stdout||process.stdout,r=n.stderr||process.stderr,s={stdout:o,stderr:r};let i;try{i=parseFlags(t||[])}catch(e){return r.write(`aegiscode autonomous: ${e.message}\n`),2}const a=Boolean(n.json||i.json),u=(e,t)=>{a?o.write(`${JSON.stringify(e,null,2)}\n`):void 0!==t&&o.write(t.endsWith("\n")?t:`${t}\n`)};if("help"===e||!SUBCOMMANDS.has(e))return o.write(usageText()),"help"===e?0:2;if(EXECUTES.has(e)&&limits.armed())return limits.refuse();const l=i.flags.cwd?path.resolve(String(i.flags.cwd)):process.cwd();if("add"===e){const t=i.terms.join(" ").trim();if(!t)return r.write('aegiscode autonomous add: a task needs text — `aegiscode autonomous add "…"`\n'),2;let n;try{n=queue.addTask(process.env,{task:t,cwd:l,class:i.flags.class||null,model:i.flags.model||null,effort:i.flags.effort||null,workers:intFlag(i.flags,"workers"),maxRounds:intFlag(i.flags,"max-rounds"),singlePass:Boolean(i.flags["single-pass"]),commit:Boolean(i.flags.commit),source:i.flags.source||"cli"})}catch(e){return r.write(`aegiscode autonomous add: ${e.message}\n`),2}return u({ok:!0,id:n.id,item:n,queue:queue.queuePath(process.env)},`aegiscode: queued #${n.id} — ${queue.pendingCount(queue.loadQueue(process.env))} pending`),0}if("list"===e){const e=queue.loadQueue(process.env),t=describeCounts(e);if(a)u({ok:!0,file:queue.queuePath(process.env),counts:t,tasks:e,runs:queue.readRuns(process.env,{limit:10})});else{o.write(`queue: ${queue.queuePath(process.env)}\n`),o.write(`tasks: ${e.length} (${t.pending} pending, ${t.running} running, ${t.done} done, ${t.error} error)\n`);for(const t of e)o.write(`${taskLine(t)}\n`);e.length||o.write("(empty)\n")}return 0}if("clear"===e){const e=queue.clearQueue(process.env,{all:Boolean(i.flags.all)});return u({ok:!0,...e},`aegiscode: removed ${e.removed} finished task(s); ${e.kept} kept`),0}if("retry"===e){const e=i.terms[0];if(!e)return r.write("aegiscode autonomous retry: which task? `aegiscode autonomous retry <id>`\n"),2;const t=queue.retryTask(process.env,e);return t?(u({ok:!0,id:t.id,item:t},`aegiscode: #${t.id} is pending again`),0):(r.write(`aegiscode autonomous retry: no task #${e}\n`),1)}const d=buildEngine({io:n});if(d.error)return r.write(`aegiscode autonomous: ${d.error}\n`),2;if(d.entitlement)try{await d.entitlement.refresh()}catch{}const c=autonomous.createQueueWorker({engine:d.engine,env:process.env,log:progressSink(s,{json:a}),canFanOut:()=>{if(!d.entitlement)return!1;try{const e=d.entitlement.current();return Boolean(e&&!0===e.entitled)}catch{return!1}}});if(d.entitlement)try{const e=d.entitlement.current();e&&!1===e.entitled&&!1===e.degraded&&e.refusal&&(r.write(`aegiscode autonomous: ${e.refusal}\n`),r.write(" ↳ write tasks like: Do X autonomously\n"),r.write("balance"===e.wall?" ↳ unlock: top up the Token Bank, or upgrade to Unlimited\n":" ↳ unlock: Unlimited, or any Token Bank balance\n"),e.upgradeUrl&&r.write(` ${e.upgradeUrl}\n`))}catch{}const m=!!i.flags.commit||void 0,g=()=>{const e=queue.loadQueue(process.env).find((e=>"running"===e.status&&e.pid===process.pid));e&&c.cancel(e.id)};process.on("SIGINT",g);try{if("reconcile"===e){const e=await c.reconcile({cwd:l,auto:Boolean(i.flags.auto),commit:m,max:intFlag(i.flags,"max")||0,stopOnError:Boolean(i.flags["stop-on-error"])});return e.ok?(a||printRunReport(e.ran||[],s),u(e,e.exhausted?"aegiscode: every phase in PLAN.md is done — nothing to queue":`aegiscode: phase ${e.phase} queued${e.ran?` — ${e.ran.length} task(s) run`:""}`),0):(r.write(`aegiscode autonomous reconcile: ${e.error||"reconcile failed"}\n`),u(e,void 0),1)}if("proceed"===e||"run"===e){const t="run"===e?1:intFlag(i.flags,"max")||0,n=await c.proceed({commit:m,max:t,stopOnError:Boolean(i.flags["stop-on-error"])});if(n.locked)return r.write(`aegiscode autonomous: another drain holds the queue lock (pid ${n.holder&&n.holder.pid})\n`),u({ok:!1,locked:!0,holder:n.holder},void 0),1;a||printRunReport(n.ran,s);const o=n.ran.filter((e=>!e.ok)).length;return u({ok:0===o,ran:n.ran.map((e=>({id:e.id,ok:e.ok,error:e.error||null,ms:e.ms}))),failed:o},n.ran.length?`aegiscode: ${n.ran.length} task(s) run${o?`, ${o} failed`:""}`:"aegiscode: nothing pending"),o?1:0}}finally{process.removeListener("SIGINT",g)}return o.write(usageText()),2}function usageText(){return["aegiscode autonomous <command> — the unattended work queue","","Commands:",' add "<task>" queue a task (--cwd, --class, --model, --effort, --commit,'," --single-pass, --workers N, --max-rounds N)"," --class aegis|byok|local|pro (default aegis); --model must"," match the class (pro takes a claude alias, or none at all)"," list show queued tasks and the tail of the runs log"," run drain ONE task, then stop"," proceed drain every pending task (--max N, --stop-on-error, --commit)"," reconcile queue the next unfinished PLAN.md phase (--auto drains it)"," retry <id> put a finished task back in the queue"," clear drop finished tasks (--all empties the queue)","","Options:"," --json emit JSON instead of text (also on add/list/clear/retry)","","A drain runs with tool approval DISABLED (nobody is there to click a card),","one task at a time, and commits only the paths the task itself changed."].join("\n")+"\n"}module.exports={runQueueCommand:runQueueCommand,parseFlags:parseFlags,taskLine:taskLine,usageText:usageText,SUBCOMMANDS:SUBCOMMANDS};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";const RE_ZERO=/[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE00-\uFE0F\uFE20-\uFE2F]/u,RE_WIDE=/[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA000-\uA4CF\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F64F}\u{1F680}-\u{1F6FF}\u{1F900}-\u{1F9FF}\u{1FA70}-\u{1FAFF}\u{20000}-\u{3FFFD}]/u,MODERN_WINDOWS=["WT_SESSION","WT_PROFILE_ID","ConEmuANSI","ANSICON","TERM_PROGRAM","WEZTERM_PANE","ALACRITTY_SOCKET","KITTY_WINDOW_ID"],TRUTHY_RE=/^(1|true|yes|on)$/i;function truthy(e){return null!=e&&(""===e||TRUTHY_RE.test(String(e).trim()))}function firstEnv(e,n){for(const r of n){const n=e[r];if(null!=n&&""!==n)return{name:r,value:String(n)}}return null}function modernWindows(e){return firstEnv(e,MODERN_WINDOWS)}function localeOf(e){const n=firstEnv(e,["LC_ALL","LC_CTYPE","LANG"]);return n?n.value:""}function artMode(e){const n=String(e.AEGIS_ART||"").trim().toLowerCase();return"ascii"===n||"plain"===n||"text"===n?"ascii":"unicode"===n||"native"===n||"utf8"===n||"utf-8"===n?"unicode":truthy(e.AEGIS_ASCII)||"0"===e.AEGIS_UNICODE?"ascii":truthy(e.AEGIS_UNICODE)?"unicode":"auto"}function resolveGlyphs(e,n){const r=String(e.AEGIS_STAR||"").trim().toLowerCase(),t=/^(native|wide)$/.test(r)?"native":/^(narrow|ascii)$/.test(r)?"narrow":null,o=artMode(e);return"ascii"===o?{glyphs:"ascii",face:"edges",star:"narrow",reason:"AEGIS_ART=ascii"}:"unicode"===o?{glyphs:"unicode",face:"native",star:t||"native",reason:"AEGIS_ART=unicode"}:{glyphs:"unicode",face:"native",star:t||"native",reason:"uniform default on every platform"+(t?` (AEGIS_STAR=${r})`:"")}}function resolveBackground(e=process.env,n=null){const r=String(e.AEGIS_BACKGROUND||e.AEGIS_THEME_BACKGROUND||"").trim().toLowerCase();if("light"===r)return{background:"light",known:!0,reason:"AEGIS_BACKGROUND=light"};if("dark"===r)return{background:"dark",known:!0,reason:"AEGIS_BACKGROUND=dark"};const t=String(e.TERM_BACKGROUND||"").trim().toLowerCase();if("light"===t||"dark"===t)return{background:t,known:!0,reason:`TERM_BACKGROUND=${t}`};const o=String(e.COLORFGBG||"").trim();if(o){const e=o.split(/[;:]/),n=Number(e[e.length-1]);if(Number.isInteger(n)&&n>=0&&n<=15)return{background:7===n||n>=11?"light":"dark",known:!0,reason:`COLORFGBG=${o}`}}return!n||"light"!==n.background&&"dark"!==n.background?{background:"dark",known:!1,reason:"no terminal background reported (dark default)"}:{background:n.background,known:!0,reason:n.reason||`osc11 ${n.background}`}}const PROBE_TIMEOUT_MS=120,OSC11_QUERY="]11;?",OSC11_REPLY=/\x1b\]11;([^\x07\x1b]*)(?:\x07|\x1b\\)/;function colorChannel(e){const n=parseInt(e,16);return Math.round(n/(Math.pow(16,e.length)-1)*255)}function parseBackgroundReply(e){const n=OSC11_REPLY.exec(String(null==e?"":e));if(!n)return null;const r=n[1].trim(),t=/^rgba?:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})/i.exec(r);if(t)return{r:colorChannel(t[1]),g:colorChannel(t[2]),b:colorChannel(t[3])};const o=/^#?([0-9a-f]{6})$/i.exec(r);if(o){const e=o[1];return{r:parseInt(e.slice(0,2),16),g:parseInt(e.slice(2,4),16),b:parseInt(e.slice(4,6),16)}}return null}function relativeLuminance({r:e,g:n,b:r}){const t=e=>{const n=e/255;return n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4)};return.2126*t(e)+.7152*t(n)+.0722*t(r)}const LIGHT_LUMINANCE=.5;function hexOf({r:e,g:n,b:r}){return"#"+[e,n,r].map((e=>e.toString(16).padStart(2,"0"))).join("")}function probeBackground({stdin:e=process.stdin,stdout:n=process.stdout,timeoutMs:r=PROBE_TIMEOUT_MS,onLeftover:t=null}={}){return new Promise((o=>{if(!(e&&n&&e.isTTY&&n.isTTY&&"function"==typeof e.setRawMode))return void o(null);const s=!!e.isRaw;let u="",a=!1,c=null;const i=(n,r)=>{if(!a){a=!0,c&&clearTimeout(c),e.pause(),e.removeListener("data",l);try{s||e.setRawMode(!1)}catch{}if(r)if("function"==typeof t)try{t(r)}catch{}else try{e.unshift(Buffer.from(r,"latin1"))}catch{}o(n)}},l=e=>{u+=e.toString("latin1");const n=parseBackgroundReply(u);n?i({background:relativeLuminance(n)>LIGHT_LUMINANCE?"light":"dark",rgb:n,reason:`osc11 ${hexOf(n)}`},u.replace(OSC11_REPLY,"")):u.length>512&&i(null,u)};c=setTimeout((()=>i(null,u)),r);try{e.setRawMode(!0),e.resume(),e.on("data",l),n.write(OSC11_QUERY)}catch{i(null,"")}}))}async function probeTerminalBackground({env:e=process.env,stdin:n=process.stdin,stdout:r=process.stdout,platform:t=process.platform,timeoutMs:o=PROBE_TIMEOUT_MS,onLeftover:s=null}={}){const u=resolveBackground(e),a=resolveBackground(e,u.known||"0"===String(e.AEGIS_BACKGROUND_PROBE||"").trim()?null:await probeBackground({stdin:n,stdout:r,timeoutMs:o,onLeftover:s})),c=axes();c.background=a.background,c.backgroundKnown=a.known,c.reasons&&(c.reasons.background=a.reason);for(const e of listeners)try{e(c)}catch{}return a}function resolveDepth(e){if(null!=e.NO_COLOR&&""!==e.NO_COLOR)return{depth:0,reason:"NO_COLOR"};const n=String(e.FORCE_COLOR||"").trim();if("0"===n)return{depth:0,reason:"FORCE_COLOR=0"};if(/^[123]$/.test(n))return{depth:"3"===n?24:"2"===n?8:4,reason:`FORCE_COLOR=${n}`};const r=String(e.AEGIS_COLOR||"").trim();return/^[0-3]$/.test(r)?{depth:"0"===r?0:"1"===r?4:"2"===r?8:24,reason:`AEGIS_COLOR=${r}`}:"0"===e.AEGIS_FORCE_TRUECOLOR?{depth:8,reason:"AEGIS_FORCE_TRUECOLOR=0"}:{depth:24,reason:"uniform default: truecolor on every platform"}}function resolveVt(e){const n=String(null==e.AEGIS_VT?"":e.AEGIS_VT).trim();return"0"===n?{vt:!1,reason:"AEGIS_VT=0"}:"1"===n||/^(true|yes|on)$/i.test(n)?{vt:!0,reason:"AEGIS_VT=1"}:{vt:!0,reason:"uniform default: ansi on every platform"}}function resolveSize(e,n){const r=parseInt(e.AEGIS_WIDTH||"",10),t=parseInt(e.COLUMNS||"",10),o=n&&Number.isFinite(n.columns)&&n.columns>0?n.columns:0,s=n&&Number.isFinite(n.rows)&&n.rows>0?n.rows:0,u=r>0?r:o||(t>0?t:80);return{cols:Math.max(20,Math.min(400,u)),rows:Math.max(5,s||24),reason:r>0?"AEGIS_WIDTH":o?"stdout.columns":t>0?"COLUMNS":"default 80"}}function resolveWideRunes(e){const n=new Map;for(const r of String(e.AEGIS_WIDE_RUNES||""))r.trim()&&n.set(r,2);return n}function detect(e=process.env,n=process.stdout,r=process.platform,t=null){const o=!(!n||!n.isTTY),s=resolveGlyphs(e,r),u=resolveDepth(e),a=resolveVt(e),c=resolveSize(e,n),i=resolveBackground(e,t),l="win32"===r?modernWindows(e):null;return{platform:r,isTTY:o,term:String(e.TERM||""),termProgram:String(e.TERM_PROGRAM||""),locale:localeOf(e),windowsHost:l?l.name:"",glyphs:s.glyphs,face:s.face,star:s.star,depth:u.depth,color:u.depth>0,background:i.background,backgroundKnown:i.known,vt:a.vt,cols:c.cols,rows:c.rows,eol:"\n",wideRunes:resolveWideRunes(e),reasons:{glyphs:s.reason,depth:u.reason,vt:a.reason,size:c.reason,background:i.reason}}}let cached=null,sizePinned=!1,sizeEnv=null;const listeners=[];function axes(){return cached||(cached=detect()),cached}function caps(){const e=axes();if(!sizePinned){const n=resolveSize(sizeEnv||process.env,process.stdout);e.cols=n.cols,e.rows=n.rows,e.reasons.size=n.reason}return e.pinned=sizePinned,e}function setCaps(e=null,n=process.env,r=process.stdout){cached=Object.assign(detect(n,r),e||{}),sizeEnv=n||process.env,sizePinned=!(!e||null==e.cols&&null==e.rows),e&&null!=e.cols&&cached.reasons&&(cached.reasons.size="pinned (override)");for(const e of listeners)try{e(cached)}catch{}return cached}function resetCaps(){cached=null,sizePinned=!1,sizeEnv=null}function onCapsChange(e){return listeners.push(e),()=>{const n=listeners.indexOf(e);n>=0&&listeners.splice(n,1)}}function cellWidth(e){const n=axes();if(n.wideRunes&&n.wideRunes.size){const r=n.wideRunes.get(e);if(null!=r)return r}return RE_ZERO.test(e)?0:RE_WIDE.test(e)?2:1}function cells(e){let n=0;for(const r of String(e))n+=cellWidth(r);return n}function padCells(e,n){const r=n-cells(e);return r>0?e+" ".repeat(r):e}function rgbTo256(e,n,r){if(e===n&&n===r)return e<8?16:e>248?231:232+Math.round((e-8)/247*24);const t=e=>Math.round(e/255*5);return 16+36*t(e)+6*t(n)+t(r)}function rgbTo16(e,n,r){const t=[[0,0,0,30],[205,0,0,31],[0,205,0,32],[205,205,0,33],[0,0,238,34],[205,0,205,35],[0,205,205,36],[229,229,229,37]];let o=t[7],s=1/0;for(const u of t){const t=(e-u[0])**2+(n-u[1])**2+(r-u[2])**2;t<s&&(s=t,o=u)}return o[3]}function rgb(e,n,r){const t=caps().depth;return t>=24?`[38;2;${e};${n};${r}m`:t>=8?`[38;5;${rgbTo256(e,n,r)}m`:t>=4?`[${rgbTo16(e,n,r)}m`:""}function bg(e,n,r){const t=caps().depth;return t>=24?`[48;2;${e};${n};${r}m`:t>=8?`[48;5;${rgbTo256(e,n,r)}m`:t>=4?`[${rgbTo16(e,n,r)+10}m`:""}function describe(e=caps()){const n=[e.platform,e.isTTY?"":"(no tty)"].filter(Boolean).join(" ");return[["platform",e.windowsHost?`${n} — ${e.windowsHost}`:n],["terminal",e.termProgram||e.term||"unknown"],["locale",e.locale||"unset"],["background",`${e.background} (${e.reasons.background})`],["mark","ascii"===e.glyphs?"ascii":"edges"===e.face?"unicode (edges stencilled)":"unicode"],["star",e.star],["color",0===e.depth?"none":e.depth>=24?"truecolor":e.depth>=8?"256":"16"],["control",e.vt?"ansi":"plain"],["size",`${e.cols}x${e.rows} (${e.reasons.size})`],["eol","\\n"],["why",`${e.reasons.glyphs}; ${e.reasons.depth}`]]}module.exports={detect:detect,caps:caps,setCaps:setCaps,resetCaps:resetCaps,onCapsChange:onCapsChange,cellWidth:cellWidth,cells:cells,padCells:padCells,rgb:rgb,bg:bg,rgbTo256:rgbTo256,rgbTo16:rgbTo16,describe:describe,resolveGlyphs:resolveGlyphs,resolveDepth:resolveDepth,resolveBackground:resolveBackground,resolveVt:resolveVt,resolveSize:resolveSize,MODERN_WINDOWS:MODERN_WINDOWS,probeBackground:probeBackground,probeTerminalBackground:probeTerminalBackground,parseBackgroundReply:parseBackgroundReply,relativeLuminance:relativeLuminance,PROBE_TIMEOUT_MS:PROBE_TIMEOUT_MS,LIGHT_LUMINANCE:LIGHT_LUMINANCE,OSC11_QUERY:OSC11_QUERY};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";const{getSize:getSize,span:span,padLine:padLine,paint:paint,w:w,wrapBlock:wrapBlock,hideCursor:hideCursor,showCursor:showCursor,moveTo:moveTo,clearScreen:clearScreen,enterAltScreen:enterAltScreen,leaveAltScreen:leaveAltScreen,enableBracketedPaste:enableBracketedPaste,disableBracketedPaste:disableBracketedPaste,enableMouseTracking:enableMouseTracking,disableMouseTracking:disableMouseTracking,selectionRange:selectionRange,selectionText:selectionText,applySelection:applySelection}=require("./screen.js"),{KEY:KEY,STREAM_END:STREAM_END,attachKeyStream:attachKeyStream,nextKey:nextKey,nextKeyTimeout:nextKeyTimeout,requeueKeys:requeueKeys,resetKeyStream:resetKeyStream,markSessionStart:markSessionStart,isKeyStreamSuspended:isKeyStreamSuspended}=require("./events.js"),{GLYPH:GLYPH,VERBS:VERBS,DONE_VERBS:DONE_VERBS,BOLD:BOLD,BOLD_OFF:BOLD_OFF,themeOf:themeOf,RGB:RGB}=require("./theme.js"),{LineEditor:LineEditor}=require("./input.js"),{renderMarkdown:renderMarkdown}=require("./markdown.js"),overlays=require("./overlays.js"),models=require("./models.js"),{resolveShared:resolveShared}=require("./sharedpaths.js"),{validateApiKey:validateApiKey}=require(resolveShared(require("node:path").join("client","credentials.js"))),claudePro=require(resolveShared(require("node:path").join("desktop","lib","local","claude-pro.js"))),fuzzy=require("./fuzzy.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,fmtElapsed:fmtElapsed,fmtUsageSplit:fmtUsageSplit,displayTokens:displayTokens,pathName:pathName,feeBillable:feeBillable}=require("./format.js"),{editPreview:editPreview}=require("./diff.js"),{renderDiffBlock:renderDiffBlock,defaultOpen:defaultOpen}=require("./diffview.js"),{copyToClipboard:copyToClipboard,describeCopy:describeCopy,readClipboardText:readClipboardText,readClipboardImage:readClipboardImage}=require("./clipboard.js"),{transcriptToMarkdown:transcriptToMarkdown}=require("./export.js"),fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir,loadConfig:loadConfig}=require("./config.js"),{effortRung:effortRung}=require("./engine.js"),{usageBuckets:usageBuckets,estimateTokensFromCells:estimateTokensFromCells}=require("./tokens.js"),{pingTurn:pingTurn}=require("./ping.js"),SUGGESTIONS=["edit <filepath> to...","refactor <filepath>","how do I log an error?","write a test for <filepath>","create a util logging.py that..."],{TITLE_SPIN:TITLE_SPIN,titleText:titleText,topicFrom:topicFrom,adoptTopic:adoptTopic,titleEnabled:titleEnabled,writeTitle:writeTitle}=require("./title.js"),{GENERIC_TITLE:GENERIC_TITLE,isGenericTitle:isGenericTitle}=require("./naming.js"),FRAME_MS=33;function isShellTool(e){return"exec"===e||"Bash"===e}function isAgentTool(e){return"task"===e||"Task"===e}function toolLabel(e,t){const n=isShellTool(e)?"shell command":isAgentTool(e)?"subagent":`${String(e).toLowerCase()} command`;return t>1?n+"s":n}function resolveToolDone(e,t){let n=-1;if(void 0!==t.id)for(let r=e.length-1;r>=0;r--){const o=e[r];if("tool"===o.role&&"run"===o.phase&&o.id===t.id){n=r;break}}if(-1===n)for(let r=e.length-1;r>=0;r--){const o=e[r];if("tool"===o.role&&"run"===o.phase&&o.name===t.name&&o.agent===t.agent){n=r;break}}if(-1===n)return null;const r=e[n],o=e.filter(((e,r)=>"tool"===e.role&&e.name===t.name&&e.agent===t.agent&&r<=n)).length;return r.phase="done",r.elapsed=t.elapsed,r.ok=t.ok,r.label=`Ran ${o} ${r.agent?`${r.agent} ▸ `:""}${toolLabel(t.name,o)}`,r}const MUTATING_FILES=new Set(["Edit","Write","MultiEdit","NotebookEdit","editFile","writeFile"]);function summarizeTurnTools(e,{maxNames:t=3}={}){const n=[],r=[];let o=0;for(const t of e||[]){if(!t)continue;!1===t.ok&&(o+=1);const e=t.args;if(!e||"object"!=typeof e)continue;const s=MUTATING_FILES.has(t.name)?e.file_path||e.path||e.notebook_path:null;"string"==typeof s&&s&&!n.includes(s)&&n.push(s);const i=e.command;if("string"==typeof i&&i.trim()){const e=pathName(i.trim().split(/\s+/)[0]);e&&!r.includes(e)&&r.push(e)}}return{tools:(e||[]).length,failed:o,files:n,names:n.slice(0,t).map((e=>pathName(e))),more:Math.max(0,n.length-t),commands:r}}function finalizeTurnText(e,{aborted:t,error:n,reasoned:r}={}){let o=String(null==e?"":e);if(n&&!t&&"stopped"!==n){const e=`(backend error: ${n})`;o=o.trim()?`${o.trimEnd()}\n\n${e}`:e}return t&&(o=o.trim()?`${o.trimEnd()} (stopped)`:"(stopped)"),o.trim()||(o=r?"(no answer — the model used its whole budget on hidden reasoning before writing one; retry, or raise the budget with /effort)":"(no response)"),o}function historyPairs(e){return e.filter((e=>"user"===e.role||"assistant"===e.role)).map((e=>({role:e.role,content:e.text})))}const PRO_ALIAS_KEYWORDS=Object.freeze(["opus","haiku","sonnet","fable"]);function overrideAnthropicByokWithPro(e,t={}){if(!e||"byok"!==e.cls)return{row:e,message:null};const n=String(e.id||""),r=n.indexOf(":");if(r<0||"anthropic"!==n.slice(0,r).trim().toLowerCase())return{row:e,message:null};if(!t.needsKey)return{row:e,message:null};if(!t.proLoggedIn)return{row:e,message:null};if(!0!==t.proEnabled)return{row:e,message:null};const o=n.slice(r+1).toLowerCase(),s=Array.isArray(t.proModels)&&t.proModels.length?t.proModels:[{id:"default",label:"Default",note:""}],i=PRO_ALIAS_KEYWORDS.find((e=>o.includes(e)))||"default",a=s.find((e=>e.id===i))||s[0];return{row:{id:a.id,label:a.label,note:a.note,cls:"pro"},message:`${n} has no Anthropic console key on this machine, but Claude Code Pro is signed in — using the subscription instead (claude --model ${a.id}). Add a real console key any time with /byok-key anthropic <key> to run this row directly.`}}function paletteQuery(e){const t=String(e||"").trim();return t.includes(" ")?t.split(/\s+/)[0]:t}function headerLine(e,t,n){const r=themeOf(n),o=` AEGIS Code v${e} `,s=Math.max(0,t-[...o].length-2),i=Math.floor(s/2);return[span(r.coral,`╭${"─".repeat(i)}${o}${"─".repeat(s-i)}╮`)]}const separatorLine=(e,t)=>[span(themeOf(t).dim,"─".repeat(e))];function effortLine(e,t){const n=themeOf(e),r=`● ${effortRung(e.effort)} · /effort`,o=" ".repeat(Math.max(0,t-[...r].length-4));return[span(n.gray,o+r)]}const SPINNER_TINT=RGB(235,159,127);function spinnerLine(e,t){const n=themeOf(t),r=Math.max(1,Math.round((e.elapsedMs||0)/1e3)),o=[...e.verb||VERBS[0]],s=Math.floor((e.frame||0)/2)%3,i=o.map(((e,t)=>span((t+s)%3==0?n.coral:SPINNER_TINT,e))),a=t&&t.thinking?span(n.gray,` (${r}s · thinking)`):span(n.gray,` (${r}s · ↓${e.streamedFloor?"≥":""}${fmtTokens(e.streamed||0)} tokens)`),l=GLYPH.spin[(e.frame||0)%GLYPH.spin.length];return[span(n.coral,l),...i,span(n.white,"… "),a]}function statusLine(e,t,n){const r=themeOf(n);let o;return o=e.inputPrompt?[span(r.gray,"enter to confirm · esc to cancel")]:e.working?[span(r.gray,` ${GLYPH.bullet} esc to interrupt`)]:e.streamJob?[span(r.gray,`${GLYPH.bullet} esc to stop`)]:e.keyNotice?[span(r.gray,` ${GLYPH.bullet} no AEGIS key: ${e.keyNotice} ${GLYPH.bullet} /key register to retry`)]:e.yolo?[span(r.gray,`${GLYPH.bullet} automode on ${GLYPH.bullet} ${autoContinueLimit()} rounds then it asks ${GLYPH.bullet} ? for shortcuts ${GLYPH.bullet} ${GLYPH.rightarrow} for manual mode`)]:[span(r.gray,`${GLYPH.pause} manual mode on ${GLYPH.bullet} ? for shortcuts ${GLYPH.bullet} ${GLYPH.rightarrow} for auto mode`)],padLine(o,t)}function shortcutsGrid(e,t){const n=themeOf(t),r=(e,t,r,o)=>[span(""," "),span(n.white,e),span(n.gray," "+t),span(""," "),span(n.white,r),span(n.gray," "+o)];return[r("/","for commands","?","for shortcuts"),r("ctrl + c","to quit","ctrl + o","for permissions"),r("alt + p","to switch model","alt + t","to toggle thinking"),r("shift + ↑/↓","pins as it moves","shift + enter","runs the row"),r("esc","to interrupt a turn","ctrl + l","to clear the screen"),r("ctrl + t","to show tokens","ctrl + r","to resume a session"),r("↑ / ↓","for history","tab","to complete a command")]}const APPROVE_ONCE="once",APPROVE_SESSION="session",DENY_TOKEN="deny",APPROVAL_CHOICES=["Yes","Yes, allow for this session","No"],APPROVAL_DECISIONS=["once","session","deny"];function confirmLines(e,t,n){const r=themeOf(n),o=[];o.push([span(r.gray,"─".repeat(Math.min(Math.max(10,t-4),80)))]),o.push([span(r.white,`${isShellTool(e.name)?"shell":e.name} command`)]),o.push([span("","")]);const s=isShellTool(e.name)?String(e.args&&e.args.command||""):String(e.args&&(e.args.file_path||e.args.pattern)||"");for(const e of wrapBlock(s,Math.max(8,t-4)))o.push([span(r.gray,e)]);o.push([span("","")]),o.push([span(r.white,"Do you want to proceed?")]);const i=e.name||"this tool";return APPROVAL_CHOICES.forEach(((t,n)=>{const s=1===n?`Yes, and allow ${i} for this session`:t;o.push(((t,n)=>{const o=e.sel===t;return[o?span(r.lavender,GLYPH.cursor):span(""," "),span(r.gray,` ${t+1}. `),span(o?r.lavender:r.white,n)]})(n,s))})),o.push([span("","")]),o.push([span(r.gray,"Esc to cancel")]),o}const AUTO_CONTINUE_LIMIT=3;function autoContinueLimit(e=process.env){const t=Number.parseInt(e&&e.AEGIS_AUTO_CONTINUE_MAX,10);return Number.isFinite(t)&&t>0?t:AUTO_CONTINUE_LIMIT}function autoContinuePlan({on:e=!1,used:t=0,limit:n=autoContinueLimit()}={}){const r=Number.isFinite(n)&&n>0?Math.floor(n):AUTO_CONTINUE_LIMIT,o=Number.isFinite(t)&&t>0?Math.floor(t):0;return e?o>=r?{auto:!1,used:0,cap:r}:{auto:!0,used:o+1,cap:r}:{auto:!1,used:o,cap:r}}function roundsLines(e,t,n){const r=themeOf(n),o=[];o.push([span(r.gray,"─".repeat(Math.min(Math.max(10,t-4),80)))]),o.push([span(r.white,`${e.spent}-round tool limit reached`)]),o.push([span("","")]);for(const e of wrapBlock("The turn is still working — it ended its last round on a tool call instead of an answer.",Math.max(8,t-4)))o.push([span(r.gray,e)]);o.push([span("","")]);const s=(t,n)=>{const o=e.sel===t;return[o?span(r.lavender,GLYPH.cursor):span(""," "),span(r.gray,` ${t+1}. `),span(o?r.lavender:r.white,n)]};return o.push(s(0,`Yes, continue with ${e.size} more rounds`)),o.push(s(1,"No, stop here and answer with what I have")),o.push([span("","")]),o.push([span(r.gray,`extension ${e.extensions} of ${e.max} · Esc to stop`)]),o}function metaBits(e,t,{omitMs:n=!1}={}){const r=[];e.model&&r.push(span(t.blue,e.model));const o=fmtUsageSplit(e);if(o)r.push(span(t.white,o.output));else{const n=displayTokens(e);null!=n&&r.push(span(t.white,`${fmtTokens(n)} tokens`))}return null!=e.eur&&feeBillable()&&r.push(span(e.eur>0?t.coral:t.green,fmtEur(e.eur))),null==e.ms||n||r.push(span(t.gray,fmtElapsed(e.ms))),e.calls>1&&r.push(span(t.gray,`${e.calls} calls`)),r}function joinBits(e,t){const n=[];return e.forEach(((e,r)=>{r&&n.push(span(t.dim,` ${GLYPH.bullet} `)),n.push(e)})),n}const DIR_MAX=40;function shortDir(e){let t=String(null==e?"":e).trim().replace(/\/+$/,"");if(!t)return"";const n=String(process.env.HOME||process.env.USERPROFILE||"").replace(/\/+$/,"");return n&&(t===n||t.startsWith(`${n}/`))&&(t=`~${t.slice(n.length)}`),t.length>DIR_MAX&&(t=`${GLYPH.ellipse}${t.slice(-(DIR_MAX-1))}`),t}function rowLines(e,t,n,r=Date.now()){const o=themeOf(n),s=[];if("tool"===e.role){const i=String(e.label||"").replace(/(?:…|\.\.\.)+$/,""),a=e.cwd?` · ${shortDir(e.cwd)}`:"";if("run"===e.phase){const t=e.start?Math.max(1,Math.round((r-e.start)/1e3)):0;s.push([span(o.gray,`${i}${GLYPH.ellipse} · ${t}s${a}`)])}else s.push([span(o.gray,`${i}${a}`)]);if(e.diff){for(const r of renderDiffBlock(e.diff,n,t,{open:!!e.diffOpen}))s.push([span("",r)]);return s}const l="string"==typeof e.args?e.args:e.args&&"object"==typeof e.args?e.args.command??e.args.file_path??e.args.description??Object.values(e.args).find((e=>"string"==typeof e))??"":"";return l&&s.push([span(o.gray,` ${GLYPH.hook} $ ${String(l)}`)]),s}if("note"===e.role)return s.push([span(o.gray,`· ${e.text}`)]),s;if("tip"===e.role){for(const n of wrapBlock(String(e.text),t))s.push([span(o.gray,n)]);return s}if("done"===e.role){const t=[span(o.gray,GLYPH.bloom),span(o.gray,` ${e.text}`)];if(e.meta){const n=metaBits(e.meta,o,{omitMs:!0});n.length&&t.push(span(o.dim," "),...joinBits(n,o))}return s.push(t),s}if("summary"===e.role){const t=e.counts||{};if(!t.tools)return s;const n=[span(o.dim,GLYPH.hook),span(""," ")],r=[span(o.white,String(t.tools)),span(o.gray," "+(1===t.tools?"command":"commands"))];if(t.files&&t.files.length&&(r.push(span(o.gray,` ${GLYPH.bullet} `)),r.push(span(o.white,String(t.files.length)),span(o.gray," "+(1===t.files.length?"file changed":"files changed")))),t.failed&&(r.push(span(o.gray,` ${GLYPH.bullet} `)),r.push(span(o.coral,`${t.failed} failed`))),t.names&&t.names.length){const e=t.more?` +${t.more}`:"";r.push(span(o.dim,` ${t.names.join(", ")}${e}`))}return n.push(...r),s.push(n),s}if("meta"===e.role){const t=metaBits(e.meta||{},o);return t.length&&s.push([span(o.dim,`${GLYPH.hook} `),...joinBits(t,o)]),s}if("panel"===e.role){for(const n of e.lines||[])s.push(padLine(n,t));return s.push([span("","")]),s}if("error"===e.role)return s.push([span(o.red,`✗ ${e.text}`)]),s;if("user"===e.role)return wrapBlock(String(e.text),Math.max(8,t-2)).forEach(((e,t)=>{0===t?s.push([span(o.gray,GLYPH.cursor),span(""," "),span(o.white,e)]):s.push([span(""," "),span(o.white,e)])})),s;const i="assistant"===e.role?renderMarkdown(String(null==e.text?"":e.text),t,n):wrapBlock(String(null==e.text?"":e.text),t).map((e=>[span(o.white,e)])),a=i.length?i:[[span("","")]];for(let e=0;e<a.length;e++){const t=a[e].slice();0===e&&t.unshift(span(o.white,GLYPH.block),span(""," ")),s.push(t)}return s}function transcriptLines(e,t,n,r=Date.now(),o=null){const{cols:s,rows:i}=t,a=Math.max(1,i-6),l=[],u=[];for(const t of e){const e=o||null,i="assistant"===t.role&&t.streaming||"tool"===t.role&&"run"===t.phase;if(!e||i)for(const e of rowLines(t,s,n,r))l.push(e),u.push(t);else{const o=e.get(t);if(o&&o.text===t.text&&o.cols===s&&o.diffOpen===t.diffOpen){for(const e of o.segment)l.push(e),u.push(t);continue}const i=rowLines(t,s,n,r);e.set(t,{text:t.text,cols:s,diffOpen:t.diffOpen,segment:i});for(const e of i)l.push(e),u.push(t)}}let c=t.scroll||0,p=null==t.anchorEnd?null:t.anchorEnd;const d=l.length,f=Math.max(0,d-a);let m;c>f&&(c=f),0===c?(p=null,m=d):(null===p&&(p=Math.max(0,d-c)),m=Math.min(p,d)),d<=a&&(c=0,p=null,m=d);const h=Math.max(0,m-a);return{lines:l.slice(h,m),owners:u.slice(h,m),scroll:c,anchorEnd:p}}function inputPreviewText(e){const t=e.indexOf("\n");if(-1===t)return e;const n=e.split("\n").length-1;return`${e.slice(0,t)} … (+${n} line${1===n?"":"s"})`}const inputRowCells=e=>Math.max(1,e-3),bufCells=e=>[...e].reduce(((e,t)=>e+w(t)),0);function cursorCells(e,t){const n=[...e];let r=0;for(let e=0;e<Math.min(t,n.length);e++)r+=w(n[e]);return r}function inputScroll(e,t,n){const r=inputRowCells(n),o=bufCells(e);if(o<=r)return 0;const s=r-1;return Math.max(0,Math.min(cursorCells(e,t)-s,o-s))}function inputStart(e,t){const n=[...e];let r=0;for(let e=0;e<n.length;e++){if(r>=t)return e;r+=w(n[e])}return n.length}function inputLine(e,t,n){const r=themeOf(n),o=[span(r.gray,GLYPH.cursor),span(""," ")];if(e.inputPrompt){o.push(span(r.white,`${e.inputPrompt.title}: `));for(const t of[...e.inputPrompt.buf])o.push(span(r.white,t));const n=Math.min(3+w(e.inputPrompt.title)+2+w(e.inputPrompt.buf),t);return{line:padLine(o,t),cursorCol:n}}if(e.working)return{line:padLine(o,t),cursorCol:3};const s=e.buf||"";if(!s.length){if(e.insertMode)return{line:padLine(o,t),cursorCol:3};const n=SUGGESTIONS[(e.suggestionIdx||0)%SUGGESTIONS.length];return o.push(span(r.white+BOLD,`Try "${n}"`),span(BOLD_OFF,"")),{line:padLine(o,t),cursorCol:3}}if(s.includes("\n")){const e=inputPreviewText(s);for(const t of[...e])o.push(span(r.white,t));return{line:padLine(o,t),cursorCol:Math.min(3+w(e),t)}}const i=inputScroll(s,e.cursor,t),a=inputStart(s,i);i>0&&o.push(span(r.dim,"…"));const l=[...s];for(let e=a;e<l.length;e++)o.push(span(r.white,l[e]));const u=l.slice(a,Math.min(e.cursor,l.length)).join(""),c=Math.min(3+(i>0?1:0)+w(u),t);return{line:padLine(o,t),cursorCol:c}}async function runSession(e){const t=e.ctx,n=new LineEditor,r=e.transcript,o=new WeakMap;let s=null;function i(t){const n=paletteQuery(null==t?s&&s.query||"":t);return fuzzy.fuzzyRankWithAliases(n,e.visibleCommands(),(e=>e.name),(e=>e.aliases||[]))}let a=0,l=!1,u=null,c=0,p=null,d=0,f=VERBS[0],m=0,h=0,g=[],y=0,E=0,S=null;const T=new Map;let v=null,L=null,C=[],b=!1,k=0,P="",$=null,x=null,O=0,Y=null,I="",K="",R=!1,M=!0;try{M=titleEnabled(process.env,e.loadConfig?e.loadConfig():e.config||{})}catch{M=!0}let A=!1,_=0;const N=e=>{if(!M)return;const t=e?TITLE_SPIN[Math.floor(c/2)%TITLE_SPIN.length]:null;writeTitle(titleText({topic:I,frame:t}),process.stdout)},D=t=>{if("function"!=typeof e.nameConversation)return;let n;R=!0;try{n=Promise.resolve(e.nameConversation(t,{signal:u?u.signal:null}))}catch{return}n.then((e=>{const t=String(e||"").trim();t&&(K=t,I=t,N(!!l),B())})).catch((()=>{}))},G=e=>{P=e,k=Date.now()+2500,setTimeout((()=>{Date.now()>=k&&B()}),2600),B()},B=()=>{if(isKeyStreamSuspended())return;const i=getSize().cols,{lines:a,inputCol:u,rows:p,inputRow:m}=(()=>{const{cols:s,rows:i}=getSize(),a=[];a.push(headerLine(e.version,s,t));const u=Math.max(1,i-6),p=transcriptLines(r,{cols:s,rows:i,scroll:E,anchorEnd:S},t,Date.now(),o);E=p.scroll,S=p.anchorEnd,T.clear();for(let e=0;e<p.lines.length;e++)T.set(1+e,p.owners[e]);for(const e of p.lines)a.push(e);for(;a.length<u+1;)a.push([span("","")]);const m=themeOf(t);if(l)a.push(spinnerLine({verb:f,frame:c,elapsedMs:Date.now()-d,streamed:estimateTokensFromCells(W())+V,streamedFloor:V>0},t));else if(Date.now()<k)a.push([span(m.gray,` ${P}`)]);else if(x){const e=Math.max(1,Math.round((Date.now()-O)/1e3));a.push([span(m.gray,` ${x.label||"running"}… (${e}s · esc to stop)`)])}else a.push(effortLine(t,s));a.push(separatorLine(s,t));const h=inputLine({buf:n.buf,cursor:n.cursor,working:l,insertMode:b,suggestionIdx:y,inputPrompt:$},s,t);return a.push(h.line),a.push(separatorLine(s,t)),a.push(statusLine({working:l,inputPrompt:$,streamJob:x,yolo:e.isYolo&&e.isYolo(),keyNotice:e.keyNotice&&e.keyNotice()},s,t)),{lines:a,inputCol:h.cursorCol,rows:i,inputRow:i-2}})();s&&j(a,p,i),C=a,paint(v?applySelection(a,selectionRange(v.anchor,v.head),i):a),_=Date.now(),s?hideCursor():$||!l?(moveTo(m,u),showCursor()):hideCursor()},H=()=>{if(A)return;A=!0;const e=Math.max(0,33-(Date.now()-_));setTimeout((()=>{A=!1,B()}),e)},j=(n,r,o)=>{if(!s)return;let i=null;if("palette"===s.type?i=overlays.renderPalette(e.visibleCommands(),{query:paletteQuery(s.query),sel:s.sel},o,r):"model"===s.type?i=overlays.renderModelPicker(s.items||[],s.sel||0,o,r,s.current,s.cls||t.modelClass,"function"==typeof e.classLabel?e.classLabel:null):"effort"===s.type?i=overlays.renderEffortPicker(s.sel||0,o,t.effort):"class"===s.type?i=overlays.renderClassPicker(s.items||[],s.sel||0,o,s.current||t.modelClass,"function"==typeof e.classLabel?e.classLabel:null):"provider"===s.type?i=overlays.renderProviderPicker(s.items||[],s.sel||0,o,s.current,s.hint):"resume"===s.type?i=overlays.renderResumeList(s.items||[],s.sel||0,o,r):"shortcuts"===s.type?i=shortcutsGrid(o,t):"confirm"===s.type?i=confirmLines(s,o,t):"rounds"===s.type?i=roundsLines(s,o,t):"panel"===s.type&&(i=s.lines||[]),!i)return;if("shortcuts"===s.type){const e=Math.max(2,r-i.length-1);for(let t=0;t<i.length;t++)n[e+t]=padLine(i[t],o);return void hideCursor()}const a=Math.max(2,Math.floor((r-i.length)/2));for(let e=0;e<i.length;e++)n[a+e]=padLine(i[e],o);hideCursor()},q=(e,t)=>(r.push(e),t&&!1===t.follow||(E=0,S=null),e),F=(e,t)=>{const n=t?r.indexOf(t):-1;return n<0?r.push(e):r.splice(n,0,e),e},U=e=>q({role:"note",text:e},{follow:!1});let z=0,V=0;const W=()=>z,Q=async t=>{l=!0,c=0,d=Date.now(),z=0,V=0,h=0,g=[],f=VERBS[m%VERBS.length],I=K||adoptTopic(I,t),(e=>{K?isGenericTitle(K)&&D(e):R||D(e)})(t),u=new AbortController,p=setInterval((()=>{c++,N(!0),c%3==0&&B()}),100),p.unref&&p.unref(),N(!0),q({role:"user",text:t});const n=q({role:"assistant",text:"",streaming:!0});let o=!1;const i={text:e=>{n.text+=e,z+=w(e),H()},reasoning:e=>{o=!0,z+=w(e)},thinkingTokens:e=>{o=!0,V+=e,H()},tool:e=>{if(e&&void 0!==e.id){const t=g.findIndex((t=>t&&void 0!==t.id&&t.id===e.id));t>=0?g[t]=e:g.push(e)}else g.push(e);if("run"===e.phase){const t=++h,r=e.agent?`${e.agent} ▸ `:"",o=editPreview(e.name,e.args,{cwd:e.cwd});F({role:"tool",phase:"run",name:e.name,args:e.args,agent:e.agent,id:e.id,label:`Running ${t} ${r}${toolLabel(e.name,t)}…`,start:Date.now(),diff:o,diffOpen:defaultOpen(o)},n)}else if(!resolveToolDone(r,e)){const t=++h,r=editPreview(e.name,e.args,{cwd:e.cwd});F({role:"tool",phase:"done",name:e.name,args:e.args,agent:e.agent,id:e.id,ok:e.ok,label:`Ran ${t} ${e.agent?`${e.agent} ▸ `:""}${toolLabel(e.name,t)}`,diff:r,diffOpen:defaultOpen(r)},n)}H()},approval:e=>(e=>new Promise((t=>{s={type:"confirm",name:e.tool||e.name||"tool",args:e.args||{},sel:0,info:e},B(),(async()=>{const e=e=>{s=null,B(),t(e)};for(;;){const t=await nextKey();if(t.name===KEY.UP||t.name===KEY.DOWN||t.name===KEY.TAB){const e=t.name===KEY.UP?-1:1;s.sel=(s.sel+e+APPROVAL_CHOICES.length)%APPROVAL_CHOICES.length,B()}else{if(t.name===KEY.ENTER)return void e(APPROVAL_DECISIONS[s.sel]||"deny");if(t.name===KEY.ESC||t.name===KEY.CTRL_C)return void e("deny");if("char"===t.name){const n=String(t.ch).trim(),r=Number(n)-1;if(Number.isInteger(r)&&r>=0&&r<APPROVAL_DECISIONS.length)return void e(APPROVAL_DECISIONS[r])}}}})()})))(e),rounds:t=>(t=>new Promise((n=>{const r=Boolean(e.isYolo&&e.isYolo()),o=autoContinuePlan({on:r,used:a});if(a=o.used,o.auto)return U(`auto: ${t.spent}-round limit reached — continuing automatically (${o.used}/${o.cap}, then it asks).`),B(),void n(!0);r&&(U(`auto: ${o.cap} automatic continuations used — asking you now (answering restarts the block).`),B()),s={type:"rounds",spent:Number(t.spent)||0,extensions:Number(t.extensions)||1,max:Number(t.max)||8,size:Number(t.size)||Number(t.spent)||0,sel:1},B(),(async()=>{const e=e=>{s=null,B(),n(e)};for(;;){const t=await nextKey();if(t.name===KEY.UP||t.name===KEY.DOWN||t.name===KEY.TAB)s.sel=1-s.sel,B();else{if(t.name===KEY.ENTER)return void e(0===s.sel);if(t.name===KEY.ESC||t.name===KEY.CTRL_C)return void e(!1);if("char"===t.name){const n=String(t.ch).trim();if("1"===n)return void e(!0);if("2"===n)return void e(!1)}}}})()})))(t)};let S=null;try{S=await e.ask(t,{history:historyPairs(r),presenter:i,signal:u.signal})}catch(e){S={error:e&&e.message||String(e)}}finally{n.streaming=!1,!String(n.text||"").trim()&&S&&"string"==typeof S.text&&S.text.trim()&&(n.text=S.text),l=!1,clearInterval(p),p=null,N(!1);const r=Math.max(1,Math.round((Date.now()-d)/1e3)),s=!(!u||!u.signal.aborted);n.text=finalizeTurnText(n.text,{aborted:s,error:S&&S.error,reasoned:o}),q({role:"done",text:`${h>0?DONE_VERBS[1]:DONE_VERBS[0]} for ${r}s`},{follow:!1}),y=m+1,m++,u=null;try{const e=loadConfig(),t=pingTurn({stream:process.stdout,mode:e.ping,minSeconds:e.pingMinSeconds,elapsedMs:Date.now()-d,isTTY:!!process.stdout.isTTY,aborted:s});t&&q({role:"note",text:t},{follow:!1})}catch{}e.recordTurn(S);let i=null;try{const t=await e.refreshSpend();i=t?t.lastCost:null}catch{}e.persistTurn&&e.persistTurn(t,S,s?"stopped":S&&S.error?"error":"done",i);const a=S&&S.usage,c=e.tokensFor?e.tokensFor(a):null,f=a?usageBuckets(a):null;q({role:"meta",meta:{model:S&&S.model,tokens:c,input:f?f.input:null,output:f?f.output:null,eur:i,ms:S&&S.ms,calls:S&&S.calls||1}},{follow:!1});const w=summarizeTurnTools(g);w.tools>0&&q({role:"summary",counts:w},{follow:0===E}),B()}},X=e=>{let r=null;if(e.name===KEY.PAGE_UP)r=5;else if(e.name===KEY.PAGE_DOWN)r=-5;else if("wheel"===e.name)r="up"===e.dir?3:-3;else{if("click"===e.name||"drag"===e.name||"release"===e.name)return!(e=>{const t={col:e.col-1,row:e.row-1};if("click"===e.name)return L=t,!1;if("drag"===e.name)return v?v.head=t:v={anchor:L||t,head:t},L=null,!0;const n=L;L=null;const r=v?selectionRange(v.anchor,v.head):null,o=!(!r||r.startRow===r.endRow&&r.startCol===r.endCol);if(v=null,!o)return(e=>{const t=T.get(e);return!(!t||!t.diff||(t.diffOpen=!t.diffOpen,0))})((n||t).row);const s=selectionText(C,r);if(!s)return!0;const i=copyToClipboard(s,{stdout:process.stdout,env:process.env}),a=s.split("\n").length;return P=describeCopy(i,`Marked ${a} line${1===a?"":"s"}`),k=Date.now()+2500,setTimeout((()=>{Date.now()>=k&&B()}),2600),!0})(e)||(H(),!0);"char"!==e.name||!t.vim||b||n.buf||("j"===e.ch?r=1:"k"===e.ch&&(r=-1))}return null!==r&&(E=Math.max(0,E+r),S=null,H(),!0)},J=()=>s?"palette"===s.type?fuzzy.fuzzyRankWithAliases(paletteQuery(s.query),e.visibleCommands(),(e=>e.name),(e=>e.aliases||[])).length:"model"===s.type||"resume"===s.type||"class"===s.type||"provider"===s.type?(s.items||[]).length:"effort"===s.type?overlays.EFFORT_VALUES.length:0:0,Z=async n=>{if(n){{const t=models.modelKeyPlan(n,{hasStored:!!e.hasProviderKey&&!!e.hasProviderKey("anthropic")}),{row:r,message:o}=overrideAnthropicByokWithPro(n,{needsKey:!(!t||!t.needed),proLoggedIn:models.claudeProLoggedIn(),proEnabled:(()=>{try{return!0===loadConfig().proEnabled}catch{return!1}})(),proModels:claudePro.PRO_MODELS});n=r,o&&U(o)}n.cls&&"aegis"!==n.cls&&t.modelClass!==n.cls&&await re(`/class ${n.cls}`),t.model=n.id,e.updateConfig({model:n.id,currentModelId:n.id,modelClass:t.modelClass}),U(`model: ${n.id}${"byok"===n.cls?" (byok)":"pro"===n.cls?" (Claude Code Pro)":""}`),await(async t=>{const n=models.modelKeyQueue(t,{accountConfigured:!!e.accountConfigured&&!!e.accountConfigured(),hasStoredFor:t=>!!e.hasProviderKey&&!!e.hasProviderKey(t)});if(!n.length)return;let r=null;try{r=e.makeCommandContext()}catch{r=null}if(r&&"function"==typeof r.readSecret)for(const e of n){const n="account"===e.role?"AEGIS account key":"claude-pro"===e.role?"Claude Code OAuth token (`claude setup-token` mints one)":`${e.provider} key`,o=String(await r.readSecret(`${n} → ${e.env} (kept off screen, Enter to skip): `)||"").trim();if(!o){U(`no key given — ${e.env} is still unset, so ${t.id} will fail until it is.`);continue}const s="account"===e.role?"AEGIS":"claude-pro"===e.role?"Claude Code OAuth":e.provider||"that provider",i=validateApiKey(o,{label:s});if(!i.ok){U(`not saved — ${i.message}. ${e.env} is still unset.`);continue}const a=models.storeModelKey(t,i.key,{env:e.env});a.ok?U(a.changed?a.foreign?`${e.env} saved to ${a.file} (0600) — read only by the Claude Code Pro transport, never exported.`:`${e.env} saved to ${a.file} (0600) — both hosts read that file; nothing to export.`:`${e.env} was already set in ${a.file}.`):U(`could not save the key: ${a.error||"unknown error"}`)}else{const e=n.map((e=>`${e.env}: ${e.why}`)).join(" · ");U(`${t.id} has no key: ${e}. Set the ones above and pick it again.`)}})(n)}},ee=async e=>{e&&e.class&&await re(`/class ${e.class}`)},te=n=>{const r=overlays.EFFORT_VALUES[n||0];s=null,t.effort=r||"high",e.updateConfig({effort:t.effort}),U(`effort: ${t.effort}`),B()},ne=async o=>{if(o)if(s)await(async t=>{const n=s.type;if(t.name===KEY.ESC||t.name===KEY.CTRL_C)return s=null,void B();if("shortcuts"===n||"panel"===n)return s=null,void B();if(t.name!==KEY.TAB||"palette"!==n)if(t.name!==KEY.TAB||"model"!==n&&"effort"!==n&&"class"!==n&&"provider"!==n){if(t.name===KEY.ENTER){if("palette"===n){const e=i()[s.sel||0],t=String(s.query||"").trim().split(/\s+/).slice(1).join(" ");return s=null,B(),void(e&&await re(t?`/${e.name} ${t}`:`/${e.name}`))}if("model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await Z(e),void B()}if("effort"===n)return void te(s.sel||0);if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ee(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await re(`/${t} ${e.id}`))}if("resume"===n){const t=(s.items||[])[s.sel||0];return s=null,B(),void(t&&e.resumeSession&&await e.resumeSession(t))}return s=null,void B()}if(t.name===KEY.SHIFT_UP||t.name===KEY.SHIFT_DOWN){const e=t.name===KEY.SHIFT_UP?-1:1,r=Math.max(0,J()-1);if(s.sel=Math.min(r,Math.max(0,(s.sel||0)+e)),"model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await Z(e),void B()}if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ee(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await re(`/${t} ${e.id}`))}return"effort"===n?void te(s.sel||0):void B()}if(t.name===KEY.SHIFT_ENTER){if("palette"===n){const e=i()[s.sel||0];return s=null,B(),void(e&&await re(`/${e.name}`))}if("model"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await Z(e),void B()}if("class"===n){const e=(s.items||[])[s.sel||0];return s=null,B(),await ee(e),void B()}if("provider"===n){const e=(s.items||[])[s.sel||0],t=s.command||"byok-key";return s=null,B(),void(e&&e.id&&await re(`/${t} ${e.id}`))}return"effort"===n?void te(s.sel||0):void 0}if(t.name===KEY.UP||t.name===KEY.DOWN){const e=(s.items||[]).length||J(),n=t.name===KEY.UP?-1:1;return s.sel=Math.min(Math.max(0,e-1),Math.max(0,(s.sel||0)+n)),void B()}if("char"===t.name){if("palette"===n)return s.query=(s.query||"")+t.ch,s.sel=0,void B();if("model"===n){const e=parseInt(t.ch,10),n=s.items||[];return void(Number.isFinite(e)&&e>=1&&e<=n.length&&(s.sel=e-1,B()))}if("effort"===n||"resume"===n||"class"===n||"provider"===n){const e=parseInt(t.ch,10),n=J();return void(Number.isFinite(e)&&e>=1&&e<=n&&(s.sel=e-1,B()))}}t.name===KEY.BACKSPACE&&"palette"===n&&(s.query=String(s.query||"").slice(0,-1),B())}else{const e="model"===n||"class"===n||"provider"===n?(s.items||[]).length:overlays.EFFORT_VALUES.length;e&&(s.sel=((s.sel||0)+1)%e,B())}else{const e=i()[s.sel||0];e&&(s.query=e.name,s.sel=0,B())}})(o);else{if("char"===o.name&&!n.buf){if("/"===o.ch)return s={type:"palette",query:"",sel:0},void B();if("?"===o.ch)return s={type:"shortcuts"},void B()}if(!t.vim||b||n.buf||"char"!==o.name){if(t.vim&&b&&o.name===KEY.ESC)return b=!1,n.cursor>0&&n.cursor--,void B()}else{const e=o.ch;if("i"===e||"a"===e||"o"===e||"s"===e||"S"===e)return"s"===e&&n.substChar(),"S"===e&&n.substLine(),"a"===e&&n.right(),b=!0,void B();if("h"===e)return n.left(),void B();if("l"===e)return n.right(),void B();if("0"===e)return n.home(),void B();if("$"===e)return n.end(),void B();if("x"===e)return n.delete(),void B();if("D"===e)return n.killToEnd(),void B();if("A"===e)return n.end(),b=!0,void B();if(X(o))return}if(o.name===KEY.ENTER){const e=n.submit();return Y=null,b=!1,e?void await re(e):void B()}if(o.name!==KEY.CTRL_V)if(o.name!==KEY.CTRL_B){if("paste"===o.name)return t.vim&&(b=!0),n.insert(String(o.text)),void B();if("char"===o.name)return t.vim&&!b||n.insert(o.ch),void B();if(o.name===KEY.BACKSPACE)return n.backspace(),void B();if(o.name===KEY.DELETE)return n.delete(),void B();if(o.name===KEY.LEFT||o.name===KEY.CTRL_LEFT)return o.name===KEY.CTRL_LEFT?n.wordBack():n.left(),void B();if(o.name!==KEY.RIGHT||n.buf){if(o.name===KEY.RIGHT||o.name===KEY.CTRL_RIGHT)return n.right(),void B();if(o.name===KEY.HOME||o.name===KEY.CTRL_A)return n.home(),void B();if(o.name===KEY.END||o.name===KEY.CTRL_E)return n.end(),void B();if(o.name===KEY.UP)return n.historyUp(),void B();if(o.name===KEY.DOWN)return n.historyDown(),void B();if(o.name===KEY.TAB)return(()=>{const t=n.buf;if(!t.startsWith("/")||t.includes(" "))return!1;const r=t.slice(1),o=e.visibleCommands().flatMap((e=>[e.name,...e.aliases||[]])).filter((e=>e.startsWith(r))).sort();return!!o.length&&(Y&&Y.q===r||(Y={q:r,i:-1}),Y.i=(Y.i+1)%o.length,n.buf="/"+o[Y.i],n.end(),!0)})()||(P=n.buf?"Tab completes commands":"Use alt+t to toggle thinking",k=Date.now()+2500,setTimeout((()=>{Date.now()>=k&&B()}),2600)),void B();if(o.name===KEY.CTRL_U)return n.buf="",n.cursor=0,void B();if(o.name===KEY.CTRL_K)return n.killToEnd(),void B();if(o.name===KEY.CTRL_W)return n.wordBack(),void B();if(o.name===KEY.CTRL_L)return clearScreen(),void B();if(o.name===KEY.CTRL_T)return U(e.tokenSummary?e.tokenSummary():"no token usage yet this session"),void B();if(o.name!==KEY.CTRL_R)if(o.name!==KEY.CTRL_O)if("click"!==o.name&&"drag"!==o.name&&"release"!==o.name)if(o.name!==KEY.PAGE_UP&&o.name!==KEY.PAGE_DOWN&&"wheel"!==o.name)if("alt"!==o.name||"p"!==o.ch){if("alt"===o.name&&"t"===o.ch){const n=!(!0===t.thinking);return t.thinking=n,e.updateConfig({thinking:n}),U("Thinking blocks: "+(n?"expanded":"collapsed")),void B()}if(o.name!==KEY.ESC)return o.name===KEY.CTRL_C?n.buf?(n.buf="",n.cursor=0,void B()):void await ie():void(o.name!==KEY.CTRL_D||n.buf||await ie());n.buf&&(n.buf="",n.cursor=0,B())}else await re("/model");else X(o);else X(o);else await re("/permissions");else await re("/resume")}else await re(e.isYolo&&e.isYolo()?"/automode off":"/automode on")}else(()=>{if(!r.length)return void G("Nothing to copy yet");const e=copyToClipboard(transcriptToMarkdown(r),{stdout:process.stdout,env:process.env});G(describeCopy(e,"Copied the conversation"))})();else(()=>{const e=readClipboardImage({env:process.env});if(e.ok)try{const t=path.join(aegisDir(),"clipboard");fs.mkdirSync(t,{recursive:!0});const r="image/jpeg"===e.mime?"jpg":"png",o=path.join(t,`pasted-${(new Date).toISOString().replace(/[:.]/g,"-")}.${r}`);fs.writeFileSync(o,e.data,{mode:384});const s=n.buf&&!/\s$/.test(n.buf)?" ":"";return n.insert(s+o),void G(`Pasted image → ${o}`)}catch(e){return void G(`Could not save the pasted image: ${e&&e.message||e}`)}const t=readClipboardText({env:process.env});if(t.ok&&t.text)return n.insert(t.text),void G(`Pasted ${t.text.length} character${1===t.text.length?"":"s"} from the clipboard`);G(t.ok?"Clipboard is empty — nothing to paste":`Cannot read the clipboard here (${t.error}) — use your terminal's own paste shortcut instead`)})()}},re=async t=>{const r=String(t||"").trim();if("?"===r)return s={type:"shortcuts"},void B();(!1===await(async(e,t)=>{try{return await((e,t)=>{const n=[];let r,o,i=!1;return e.then((e=>{i=!0,r=e}),(e=>{i=!0,o=e})),(async()=>{for(;!i;){if(!l||s&&"confirm"===s.type){await new Promise((e=>setTimeout(e,60)));continue}const e=await nextKeyTimeout(120);if(null!==e)if(e.name===KEY.ESC||e.name===KEY.CTRL_C){const e=t&&t();e&&e.abort()}else X(e)||n.push(e)}if(requeueKeys(n),o)throw o;return r})()})(e(),(()=>u))}catch(e){return q({role:"note",text:`Error: ${e&&e.message||String(e)}`},{follow:!1}),void B()}})((async()=>{if(r.startsWith("/")){const t=(()=>{const t=e.makeCommandContext();return Object.assign(t,{push:(e,t)=>{q(e,t),B()},note:e=>{q({role:"note",text:e}),B()},panel:e=>{q({role:"panel",lines:e||[]}),B()},render:()=>B(),openOverlay:e=>{s=e,B()},closeOverlay:()=>{s=null,showCursor(),B()},askInput:e=>(e=>new Promise((t=>{$={title:e,buf:""},B(),(async()=>{for(;;){const e=await nextKey();if(!$)return void t(null);if(e.name===KEY.ESC||e.name===KEY.CTRL_C||e.name===KEY.CTRL_D)return $=null,B(),void t(null);if(e.name===KEY.ENTER){const e=$.buf;return $=null,B(),void t(e)}e.name===KEY.BACKSPACE?$.buf=[...$.buf].slice(0,-1).join(""):"char"===e.name?$.buf+=e.ch:"paste"===e.name&&($.buf+=String(e.text).replace(/\n/g," ")),B()}})()})))(e),withWorking:e=>(async e=>{const t=u;l=!0,c=0,d=Date.now(),f=VERBS[m%VERBS.length],u=new AbortController,p=setInterval((()=>{c++,N(!0),c%3==0&&B()}),100),p.unref&&p.unref(),N(!0);try{return await e(u.signal)}finally{l=!1,clearInterval(p),p=null,u=t,N(!1),B()}})(e),runPrompt:async e=>{await Q(e)},state:()=>e.buildState(),setInput:e=>{n.buf=String(null==e?"":e),n.end(),B()},exit:()=>e.requestExit(),openStream:e=>{x=e||null,O=Date.now(),B()},closeStream:e=>{e&&x!==e||(x=null),B()},showThemePicker:()=>{e.showThemePicker&&e.showThemePicker(),B()}}),t})();return e.dispatchLine(r,t)}return await Q(r),!0}))||e.wantsExit())&&await ie()};let oe=!1,se=null;const ie=()=>{oe||(oe=!0,se&&se(0))},ae=()=>{hideCursor(),paint([]);try{process.stdout.write("[0m")}catch{}try{M&&writeTitle("",process.stdout)}catch{}try{process.stdin.setRawMode(!1)}catch{}disableBracketedPaste(),disableMouseTracking(),leaveAltScreen()};let le=!1;const ue=()=>{if(!le){le=!0;try{ae()}catch{}}};process.once("exit",ue);const ce=e.stdin||process.stdin;markSessionStart(),attachKeyStream(ce),enableBracketedPaste(),enableMouseTracking(),enterAltScreen(),clearScreen(),hideCursor(),N(!1);const pe=()=>B();"win32"!==process.platform?process.on("SIGWINCH",pe):process.stdout.on("resize",pe);const de=()=>{l&&u?u.abort():ie()};process.on("SIGINT",de);const fe=e=>{ae();try{process.stderr.write(`\nAEGIS Code hit an unexpected error. Your transcript is saved; rerun to continue.\n${e&&e.stack||e}\n`)}catch{}process.exit(1)};process.on("uncaughtException",fe),process.on("unhandledRejection",fe),B();try{return await new Promise((e=>{se=e,(async()=>{for(;!oe;){const e=await nextKey();if(oe)break;if(e===STREAM_END||!e){ie();break}try{await ne(e)}catch(e){q({role:"note",text:`Error: ${e&&e.message||String(e)}`},{follow:!1}),B()}}})()}))}finally{oe=!0,process.off("SIGINT",de),"win32"!==process.platform?process.off("SIGWINCH",pe):process.stdout.off("resize",pe),process.off("uncaughtException",fe),process.off("unhandledRejection",fe),process.off("exit",ue),ue(),resetKeyStream()}}module.exports={SUGGESTIONS:SUGGESTIONS,TITLE_SPIN:TITLE_SPIN,FRAME_MS:33,toolLabel:toolLabel,resolveToolDone:resolveToolDone,summarizeTurnTools:summarizeTurnTools,finalizeTurnText:finalizeTurnText,historyPairs:historyPairs,overrideAnthropicByokWithPro:overrideAnthropicByokWithPro,paletteQuery:paletteQuery,headerLine:headerLine,separatorLine:separatorLine,effortLine:effortLine,spinnerLine:spinnerLine,statusLine:statusLine,shortcutsGrid:shortcutsGrid,confirmLines:confirmLines,APPROVAL_CHOICES:APPROVAL_CHOICES,APPROVAL_DECISIONS:APPROVAL_DECISIONS,roundsLines:roundsLines,autoContinuePlan:autoContinuePlan,autoContinueLimit:autoContinueLimit,AUTO_CONTINUE_LIMIT:AUTO_CONTINUE_LIMIT,rowLines:rowLines,transcriptLines:transcriptLines,inputPreviewText:inputPreviewText,inputRowCells:inputRowCells,inputScroll:inputScroll,inputStart:inputStart,inputLine:inputLine,runSession:runSession};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{ensurePrivateDir:ensurePrivateDir,writePrivateFile:writePrivateFile}=require("./securefs.js"),CHECKPOINT_LIMIT=8;function checkpointsPath(t){return path.join(aegisDir(),"checkpoints",`${t}.jsonl`)}function snapshotCheckpoint(t,e){try{ensurePrivateDir(path.dirname(checkpointsPath(t)));const r={ts:(new Date).toISOString(),depth:e.length,words:e.reduce(((t,e)=>t+(e.text||"").split(/\s+/).length),0),transcript:e},n=checkpointsPath(t),i=[...fs.existsSync(n)?fs.readFileSync(n,"utf8").split("\n").filter(Boolean):[],JSON.stringify(r)],s=i.slice(Math.max(0,i.length-8));return writePrivateFile(n,s.join("\n")+"\n"),i.length-1}catch{return-1}}function listCheckpoints(t){try{return fs.readFileSync(checkpointsPath(t),"utf8").split("\n").filter(Boolean).map(((t,e)=>{try{const r=JSON.parse(t);return{idx:e,ts:r.ts,depth:r.depth||0,words:r.words||0}}catch{return null}})).filter(Boolean).reverse()}catch{return[]}}function loadCheckpoint(t,e){try{const r=fs.readFileSync(checkpointsPath(t),"utf8").split("\n").filter(Boolean),n=JSON.parse(r[e]);return n&&Array.isArray(n.transcript)?n.transcript:null}catch{return null}}module.exports={CHECKPOINT_LIMIT:8,checkpointsPath:checkpointsPath,snapshotCheckpoint:snapshotCheckpoint,listCheckpoints:listCheckpoints,loadCheckpoint:loadCheckpoint};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";const{spawnSync:spawnSync}=require("node:child_process"),fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{writePrivateFile:writePrivateFile}=require("./securefs.js"),ESC="",realPlatform=()=>process.platform;function clipboardCandidates(e,{platform:t=realPlatform(),env:r=process.env}={}){const n="linux"===t,o="darwin"===t,i="win32"===t,a=!!(r||{}).WAYLAND_DISPLAY;return"write"===e?[o&&{name:"pbcopy",cmd:"pbcopy",args:[],env:"any"},i&&{name:"clip",cmd:"clip",args:[],env:"any"},...n?a?[{name:"wl-copy",cmd:"wl-copy",args:[],env:"wayland"},{name:"xclip",cmd:"xclip",args:["-selection","clipboard"],env:"x11"},{name:"xsel",cmd:"xsel",args:["--clipboard","--input"],env:"x11"}]:[{name:"xclip",cmd:"xclip",args:["-selection","clipboard"],env:"x11"},{name:"xsel",cmd:"xsel",args:["--clipboard","--input"],env:"x11"},{name:"wl-copy",cmd:"wl-copy",args:[],env:"wayland"}]:[]].filter(Boolean):"text"===e?[o&&{name:"pbpaste",cmd:"pbpaste",args:[],env:"any"},i&&{name:"powershell",cmd:"powershell",args:["-NoProfile","-Command","Get-Clipboard"],env:"any",winNewline:!0},...n?[{name:"wl-paste",cmd:"wl-paste",args:["--no-newline"],env:"wayland"},{name:"xclip",cmd:"xclip",args:["-selection","clipboard","-o"],env:"x11"},{name:"xsel",cmd:"xsel",args:["--clipboard","--output"],env:"x11"}]:[]].filter(Boolean):[o&&{name:"pngpaste",cmd:"pngpaste",args:["-"],env:"any"},...n?[{name:"wl-paste",cmd:"wl-paste",args:["--type","image/png"],env:"wayland",mime:"image/png"},{name:"wl-paste",cmd:"wl-paste",args:["--type","image/jpeg"],env:"wayland",mime:"image/jpeg"},{name:"xclip",cmd:"xclip",args:["-selection","clipboard","-t","image/png","-o"],env:"x11",mime:"image/png"}]:[]].filter(Boolean)}function dirIsTrusted(e,{platform:t=realPlatform()}={}){try{const r=fs.statSync(e);return!(!r.isDirectory()||"win32"!==t&&(18&r.mode||"function"==typeof process.getuid&&0!==r.uid&&r.uid!==process.getuid()))}catch{return!1}}const WIN_EXTS=["",".exe",".cmd",".bat",".com"];function joinFor(e,t,r){return r&&(/\\/.test(e)||/^[A-Za-z]:/.test(e))?path.win32.join(e,t):path.join(e,t)}function resolveTrustedTool(e,{platform:t=realPlatform(),env:r=process.env}={}){const n=r||{},o="0"!==n.AEGISCODE_TRUST_PATH,i="win32"===t,a=i?path.win32:path,s=String((null!=n.PATH?n.PATH:process.env.PATH)||"").split(i?";":path.delimiter),c=o||i;for(const r of s){const n=String(r).trim().replace(/^"|"$/g,"");if(n&&(i||a.isAbsolute(n))&&(!c||dirIsTrusted(n,{platform:t})))for(const r of i?WIN_EXTS:[""]){const o=joinFor(n,e+r,i);let a,s;try{a=fs.realpathSync(o)}catch{continue}try{s=fs.statSync(a)}catch{continue}if(s.isFile()){if(!i){if(!(73&s.mode))continue;if(c){if(18&s.mode)continue;if("function"==typeof process.getuid&&0!==s.uid&&s.uid!==process.getuid())continue;if(!dirIsTrusted(path.dirname(a),{platform:t}))continue}}return a}}}return null}const base64=e=>Buffer.from(String(e),"utf8").toString("base64"),OSC52_MAX=1e5;function osc52Sequence(e,t=process.env){const r=`${ESC}]52;c;${base64(e)}`,n=t||{};return n.TMUX?`${ESC}Ptmux;${ESC}${r.split(ESC).join(ESC+ESC)}${ESC}\\`:n.STY?`${ESC}P${r}${ESC}\\`:r}function writeOsc52(e,{stdout:t=process.stdout,env:r=process.env}={}){const n=r||{};if("1"===n.AEGISCODE_NO_OSC52)return!1;if(!t||!t.isTTY||"function"!=typeof t.write)return!1;const o=String(e);if(!o||o.length>OSC52_MAX)return!1;try{return t.write(osc52Sequence(o,n)),!0}catch{return!1}}function copyToClipboard(e,t={}){const{stdout:r=process.stdout,env:n=process.env,platform:o=realPlatform(),spawn:i=spawnSync}=t,a=n||{};if("1"!==a.AEGISCODE_NO_CLIPBOARD){for(const t of clipboardCandidates("write",{platform:o,env:a})){const r=resolveTrustedTool(t.cmd,{platform:o,env:a});if(!r)continue;const n=i(r,t.args,{input:String(e),encoding:"utf8",timeout:4e3,windowsHide:!0});if(!n.error&&0===n.status)return{ok:!0,via:`tool:${t.name}`}}if(writeOsc52(e,{stdout:r,env:a}))return{ok:!0,via:"osc52:"+(a.TMUX?"tmux":a.STY?"screen":"terminal")}}try{const t=path.join(aegisDir(),"clipboard.txt");return writePrivateFile(t,String(e),{atomic:!1}),{ok:!0,via:"file",path:t}}catch{return{ok:!1,via:"none"}}}function describeCopy(e,t="Copied"){if(!e||!e.ok)return"Clipboard unavailable; nothing copied.";if("file"===e.via)return`${t} — no clipboard tool on this host; the text is in ${e.path}`;const[r,n]=String(e.via).split(":");return"osc52"===r?"terminal"===n?`${t} to the clipboard via the terminal.`:`${t} to the clipboard (through ${n}).`:`${t} to the clipboard (${n}).`}const PNG_MAGIC=Buffer.from([137,80,78,71,13,10,26,10]),JPEG_MAGIC=Buffer.from([255,216,255]);function sniffImage(e){return!e||e.length<8?null:e.subarray(0,8).equals(PNG_MAGIC)?"image/png":e.subarray(0,3).equals(JPEG_MAGIC)?"image/jpeg":null}function readClipboardText(e={}){const{env:t=process.env,platform:r=realPlatform(),spawn:n=spawnSync}=e,o=t||{};if("1"===o.AEGISCODE_NO_CLIPBOARD)return{ok:!1,via:"none",error:"clipboard disabled"};for(const e of clipboardCandidates("text",{platform:r,env:o})){const t=resolveTrustedTool(e.cmd,{platform:r,env:o});if(!t)continue;const i=n(t,e.args,{encoding:"utf8",timeout:4e3,maxBuffer:16777216,windowsHide:!0});if(!i.error&&0===i.status&&null!=i.stdout)return{ok:!0,text:e.winNewline?String(i.stdout).replace(/\r\n/g,"\n").replace(/\n$/,""):String(i.stdout),via:`tool:${e.name}`}}return{ok:!1,via:"none",error:"no clipboard reader available"}}function readClipboardImage(e={}){const{env:t=process.env,platform:r=realPlatform(),spawn:n=spawnSync}=e,o=t||{};if("1"===o.AEGISCODE_NO_CLIPBOARD)return{ok:!1,via:"none",error:"clipboard disabled"};for(const e of clipboardCandidates("image",{platform:r,env:o})){const t=resolveTrustedTool(e.cmd,{platform:r,env:o});if(!t)continue;const i=n(t,e.args,{timeout:5e3,maxBuffer:67108864,windowsHide:!0});if(i.error||0!==i.status||!i.stdout)continue;const a=Buffer.isBuffer(i.stdout)?i.stdout:Buffer.from(String(i.stdout),"utf8"),s=sniffImage(a);if(s)return{ok:!0,data:a,mime:s,via:`tool:${e.name}`}}return{ok:!1,via:"none",error:"no image on the clipboard"}}function clipboardCapabilities({platform:e=realPlatform(),env:t=process.env}={}){const r=r=>clipboardCandidates(r,{platform:e,env:t}).some((r=>!!resolveTrustedTool(r.cmd,{platform:e,env:t})));return{canWrite:r("write"),canReadText:r("text"),canReadImage:r("image")}}module.exports={copyToClipboard:copyToClipboard,describeCopy:describeCopy,readClipboardText:readClipboardText,readClipboardImage:readClipboardImage,sniffImage:sniffImage,clipboardCandidates:clipboardCandidates,clipboardCapabilities:clipboardCapabilities,osc52Sequence:osc52Sequence,writeOsc52:writeOsc52,resolveTrustedTool:resolveTrustedTool,dirIsTrusted:dirIsTrusted};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{historyPath:historyPath,appendHistoryEntries:appendHistoryEntries,readHistoryEntries:readHistoryEntries,readSessionTranscript:readSessionTranscript}=require("./history.js"),{estimateTokens:estimateTokens}=require("./tokens.js"),SOURCE="aegiscode-cli",SYNC_FILE="sync-state.json",DEFAULT_LIMIT=50;function syncStatePath(){return path.join(aegisDir(),SYNC_FILE)}function loadState(){try{const t=JSON.parse(fs.readFileSync(syncStatePath(),"utf8"));if(t&&"object"==typeof t)return{sessions:t.sessions&&"object"==typeof t.sessions?t.sessions:{},lastPushAt:t.lastPushAt||null,lastPullAt:t.lastPullAt||null,importedRemoteAt:t.importedRemoteAt||{},importedRemoteCount:t.importedRemoteCount||{},quota:t.quota&&"object"==typeof t.quota?t.quota:null}}catch{}return{sessions:{},lastPushAt:null,lastPullAt:null,importedRemoteAt:{},importedRemoteCount:{},quota:null}}function readQuota(t){if(!t||"object"!=typeof t)return null;const e=null!=t.tokensUsed?t.tokensUsed:t.tokens_used,s=null!=t.tokenLimit?t.tokenLimit:t.token_limit;if(null==e||null==s)return null;const n=Number(e),o=Number(s);return Number.isFinite(n)&&Number.isFinite(o)?{used:n,limit:o}:null}function recordQuota(t,e,s){const n=Number(e),o=Number(s);return!t||!Number.isFinite(n)||!Number.isFinite(o)||o<=0?null:(t.quota={used:n,limit:o,over:n>=o,at:Date.now()},t.quota)}function saveState(t){try{fs.mkdirSync(aegisDir(),{recursive:!0});const e=syncStatePath()+".tmp";return fs.writeFileSync(e,JSON.stringify(t,null,2)+"\n"),fs.renameSync(e,syncStatePath()),!0}catch(t){return process.env.AEGIS_HIST_DEBUG&&console.error("[cloudsync] write failed:",t),!1}}function localSessions({limit:t=DEFAULT_LIMIT}={}){const e=new Map;for(const t of readHistoryEntries()){if(!t||!t.sessionId)continue;const s=e.get(t.sessionId)||{id:t.sessionId,cwd:t.cwd||"",firstPrompt:"",updatedAt:"",exchanges:0};s.exchanges+=1,!s.firstPrompt&&t.prompt&&(s.firstPrompt=String(t.prompt)),String(t.ts||"")>String(s.updatedAt||"")&&(s.updatedAt=t.ts||""),e.set(t.sessionId,s)}return[...e.values()].sort(((t,e)=>String(t.updatedAt)<String(e.updatedAt)?1:-1)).slice(0,Math.max(1,t))}function titleFor(t){return String(t&&t.firstPrompt||"").replace(/\s+/g," ").trim().slice(0,80)}function buildTranscript(t,e={}){const s=(e.transcript||readSessionTranscript(t.id)).filter((t=>t&&("user"===t.role||"assistant"===t.role))).map((t=>({role:t.role,content:String(null==t.text?"":t.text)})));return{session_id:t.id,title:null!=e.title?e.title:titleFor(t),messages:s,source:e.source||SOURCE}}function isPending(t,e){const s=e.sessions[t.id];return!s||!s.syncedAt||String(t.updatedAt||"")>String(s.localUpdatedAt||"")}function listPending(t={}){const e=t.state||loadState(),s=localSessions({...t,limit:Number.MAX_SAFE_INTEGER}).filter((t=>isPending(t,e))).reverse();return t.limit?s.slice(0,t.limit):s}function markSynced(t,e,s={}){const n=t.sessions[e]||{};return t.sessions[e]={...n,syncedAt:Date.now(),localUpdatedAt:s.localUpdatedAt||n.localUpdatedAt||"",remoteUpdatedAt:s.remoteUpdatedAt||n.remoteUpdatedAt||null,lastError:null},t.sessions[e]}function markFailed(t,e,s){const n=t.sessions[e]||{};return t.sessions[e]={...n,lastError:s,failedAt:Date.now()},t.sessions[e]}function entriesFromRemote(t,e,s=0){const n=[],o=Array.isArray(t.messages)?t.messages:[],i=s>0&&s<=o.length?o.slice(s):o;let r=null;const a=(s,o)=>{null==s&&null==o||n.push({ts:t.updated_at||e,sessionId:t.session_id,cwd:"",prompt:null==s?"":String(s),reply:null==o?"":String(o),status:"done",imported:!0,importedFrom:String(t.source||"cloud"),tokens:{input:estimateTokens(String(s||"")),output:estimateTokens(String(o||"")),cacheRead:0,cacheWrite:0,real:!1}})};for(const t of i){const e=t&&t.role,s=t&&(null!=t.content?t.content:t.text);"user"===e?(null!=r&&a(r,null),r=null==s?"":s):"assistant"!==e&&"system"!==e||(a(r,s),r=null)}return null!=r&&a(r,null),n}function describeError(t){const e=t&&(t.status||t.response&&t.response.status),s=t&&t.message||String(t);if(402===e){const n=t&&t.data||{},o=null!=n.tokensUsed?n.tokensUsed:n.sessionsUsed,i=null!=n.tokenLimit?n.tokenLimit:n.freeSessionLimit;return{kind:"quota",status:e,message:s,used:null!=o?Number(o):null,limit:null!=i?Number(i):null,hint:"the plan’s synced-token ceiling is reached — everything already stored stays readable, only NEW writes pause: /cloud memory shows the quota, /cloud memory off stops syncing"}}return 401===e?{kind:"auth",status:e,message:s,hint:"the memory token was refused — run /key <api_key> to re-exchange it"}:{kind:"error",status:e||null,message:s,hint:null}}async function push(t,e={}){const s=e.state||loadState(),n=e.limit||DEFAULT_LIMIT,o=e.sessionIds?e.sessionIds.map((t=>localSessions({limit:Number.MAX_SAFE_INTEGER,state:s}).find((e=>e.id===t)))).filter(Boolean):listPending({...e,limit:n,state:s}),i=[],r=[],a=[];for(const n of o){const o=buildTranscript(n,{});if(o.messages.length)try{const r=await t.conversationSyncPush(o),a=r&&(r.session_id||r.id)||n.id;markSynced(s,n.id,{localUpdatedAt:n.updatedAt,remoteUpdatedAt:r&&r.updated_at||(new Date).toISOString()});const l=readQuota(r);i.push({id:n.id,remoteId:a,messages:o.messages.length,title:o.title,quota:l}),l&&recordQuota(s,l.used,l.limit),"function"==typeof e.onProgress&&e.onProgress({phase:"push",id:n.id})}catch(t){const e=describeError(t);if(markFailed(s,n.id,e.message),r.push({id:n.id,...e}),"quota"!==e.kind||recordQuota(s,e.used,e.limit)||(s.quota={used:null,limit:null,over:!0,at:Date.now()}),"quota"===e.kind||"auth"===e.kind)break}else a.push({id:n.id,reason:"no messages"})}return i.length&&(s.lastPushAt=Date.now()),saveState(s),{pushed:i,failed:r,skipped:a,pending:listPending({state:s}).length}}async function pull(t,e={}){const s=e.state||loadState(),n=!1!==e.import;let o;try{o=await t.conversationSyncPull()}catch(t){return{ok:!1,sessions:[],imported:0,failed:[describeError(t)]}}const i=o&&o.sessions||[],r=[],a=(new Date).toISOString(),l=[];for(const t of i){const e=t&&t.session_id;if(!e)continue;const o=s.importedRemoteAt[e],i=Array.isArray(t.messages)?t.messages.length:0,u=Number((s.importedRemoteCount||{})[e]||0),d=!o||o!==t.updated_at||i!==u;if(n&&d){const n=entriesFromRemote(t,a,i>=u?u:0);n.length&&l.push(...n),s.importedRemoteAt[e]=t.updated_at||a,s.importedRemoteCount={...s.importedRemoteCount||{},[e]:i}}markSynced(s,e,{localUpdatedAt:t.updated_at||a,remoteUpdatedAt:t.updated_at||a}),r.push({id:e,title:t.title||"",messages:(t.messages||[]).length,source:t.source||"",updatedAt:t.updated_at||null,imported:n&&d})}const u=l.length?appendHistoryEntries(l):0;return s.lastPullAt=Date.now(),saveState(s),{ok:!0,sessions:r,remote:i.length,imported:u,failed:[]}}async function syncNow(t,e={}){const s=e.state||loadState(),n={ok:!0,push:null,pull:null};try{n.push=await push(t,{...e,state:s})}catch(t){n.ok=!1,n.push={pushed:[],failed:[describeError(t)],skipped:[]}}try{n.pull=await pull(t,{...e,state:s}),n.pull&&!1===n.pull.ok&&(n.ok=!1)}catch(t){n.ok=!1,n.pull={ok:!1,sessions:[],imported:0,failed:[describeError(t)]}}return n}function status(){const t=loadState(),e=localSessions({limit:Number.MAX_SAFE_INTEGER}),s=e.filter((e=>isPending(e,t))),n=e.filter((e=>t.sessions[e.id]&&t.sessions[e.id].lastError)).map((e=>({id:e.id,error:t.sessions[e.id].lastError}))),o=t.quota||null,i=Boolean(o&&o.over);return{local:e.length,pending:s.length,synced:e.length-s.length,lastPushAt:t.lastPushAt,lastPullAt:t.lastPullAt,importedRemote:Object.keys(t.importedRemoteAt||{}).length,errors:n,quota:o,overQuota:i,paused:i&&s.length>0,path:syncStatePath(),historyPath:historyPath()}}module.exports={SOURCE:SOURCE,syncStatePath:syncStatePath,loadState:loadState,saveState:saveState,localSessions:localSessions,titleFor:titleFor,buildTranscript:buildTranscript,isPending:isPending,listPending:listPending,markSynced:markSynced,markFailed:markFailed,entriesFromRemote:entriesFromRemote,describeError:describeError,recordQuota:recordQuota,readQuota:readQuota,push:push,pull:pull,syncNow:syncNow,status:status};
|