aegisone 1.0.64 → 1.0.66
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/aegis.js +1 -1
- package/package.json +1 -1
- package/scripts/bump.mjs +1 -1
- package/scripts/bundle.js +1 -1
- package/scripts/postinstall.mjs +1 -1
- package/scripts/predist.mjs +1 -1
- package/src/child.js +1 -1
- package/src/dispatch.js +1 -1
- package/src/doctor.js +1 -1
- package/src/probes.js +1 -1
- package/src/productupdate.js +1 -1
- package/src/protocol.js +1 -1
- package/src/release.js +1 -1
- package/src/selfhost.js +1 -1
- package/vendor/cli/bin/aegiscode.js +47 -5
- package/vendor/cli/package.json +1 -1
- package/vendor/cli/scripts/check.mjs +1 -1
- package/vendor/cli/scripts/demo.mjs +1 -1
- package/vendor/cli/scripts/postinstall.mjs +1 -1
- package/vendor/cli/scripts/predist.mjs +1 -1
- package/vendor/cli/scripts/runtests.mjs +1 -1
- package/vendor/cli/src/app.js +1 -1
- package/vendor/cli/src/art.js +1 -1
- package/vendor/cli/src/autonomous.js +574 -10
- package/vendor/cli/src/chatflow.js +1 -1
- package/vendor/cli/src/checkpoint.js +1 -1
- package/vendor/cli/src/clipboard.js +1 -1
- package/vendor/cli/src/cloudsync.js +1 -1
- package/vendor/cli/src/commands.js +2 -2
- package/vendor/cli/src/config.js +1 -1
- package/vendor/cli/src/connect.js +1 -1
- package/vendor/cli/src/devrun.js +1 -1
- package/vendor/cli/src/diff.js +1 -1
- package/vendor/cli/src/diffview.js +1 -1
- package/vendor/cli/src/dream-cmd.js +3 -0
- package/vendor/cli/src/dream.js +1 -1
- package/vendor/cli/src/engine.js +1 -1
- package/vendor/cli/src/events.js +1 -1
- package/vendor/cli/src/export.js +1 -1
- package/vendor/cli/src/fingerprint.js +1 -1
- package/vendor/cli/src/format.js +1 -1
- package/vendor/cli/src/fuzzy.js +1 -1
- package/vendor/cli/src/history.js +1 -1
- package/vendor/cli/src/init.js +1 -1
- package/vendor/cli/src/limits.js +1 -1
- package/vendor/cli/src/markdown.js +1 -1
- package/vendor/cli/src/models.js +1 -1
- package/vendor/cli/src/overlays.js +1 -1
- package/vendor/cli/src/panels.js +1 -1
- package/vendor/cli/src/ping.js +1 -1
- package/vendor/cli/src/presence.js +1 -1
- package/vendor/cli/src/provenance.lock.json +3 -3
- package/vendor/cli/src/render.js +1 -1
- package/vendor/cli/src/screen.js +1 -1
- package/vendor/cli/src/screens.js +1 -1
- package/vendor/cli/src/secret.js +1 -1
- package/vendor/cli/src/securefs.js +1 -1
- package/vendor/cli/src/settings.js +1 -1
- package/vendor/cli/src/signup.js +1 -1
- package/vendor/cli/src/summarize.js +1 -1
- package/vendor/cli/src/sysdiag.js +1 -1
- package/vendor/cli/src/theme.js +1 -1
- package/vendor/cli/src/title.js +1 -1
- package/vendor/cli/src/todos.js +1 -1
- package/vendor/cli/src/tokens.js +1 -1
- package/vendor/cli/src/topup.js +1 -1
- package/vendor/cli/src/update.js +1 -1
- package/vendor/cli/vendor/client/aegis.js +1 -1
- package/vendor/cli/vendor/client/attest.js +1 -1
- package/vendor/cli/vendor/client/authorship-key.js +1 -1
- package/vendor/cli/vendor/client/auto-provision.js +1 -1
- package/vendor/cli/vendor/client/brain-catalog.js +1 -1
- package/vendor/cli/vendor/client/byok-catalog.js +1 -1
- package/vendor/cli/vendor/client/catalog-client.js +1 -1
- package/vendor/cli/vendor/client/conversation-export.js +1 -1
- package/vendor/cli/vendor/client/credentials.js +1 -1
- package/vendor/cli/vendor/client/credits.js +1 -1
- package/vendor/cli/vendor/client/drive-connect.js +1 -1
- package/vendor/cli/vendor/client/env-file.js +1 -1
- package/vendor/cli/vendor/client/fingerprint.js +1 -1
- package/vendor/cli/vendor/client/foreign-memory.js +1 -1
- package/vendor/cli/vendor/client/foreign-sessions.js +1 -1
- package/vendor/cli/vendor/client/google-signin.js +1 -1
- package/vendor/cli/vendor/client/hooks.js +1 -1
- package/vendor/cli/vendor/client/model-discovery.js +1 -1
- package/vendor/cli/vendor/client/model-sync.js +1 -1
- package/vendor/cli/vendor/client/naming.js +1 -1
- package/vendor/cli/vendor/client/platform.js +1 -1
- package/vendor/cli/vendor/client/prefs.js +1 -1
- package/vendor/cli/vendor/client/presence.js +1 -1
- package/vendor/cli/vendor/client/record-vault.js +2 -2
- package/vendor/cli/vendor/client/session-search.js +1 -1
- package/vendor/cli/vendor/client/session-store.js +1 -1
- package/vendor/cli/vendor/client/skills.js +1 -1
- package/vendor/cli/vendor/client/topup.js +1 -1
- package/vendor/cli/vendor/client/touch.js +1 -1
- package/vendor/cli/vendor/client/update.js +1 -1
- package/vendor/cli/vendor/client/user-models.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/attachments.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/context.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/local.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/perm-rules.js +5 -0
- package/vendor/cli/vendor/desktop/lib/local/perm-store.js +5 -0
- package/vendor/cli/vendor/desktop/lib/local/perm-write.js +5 -0
- package/vendor/cli/vendor/desktop/lib/local/pro-sessions.js +3 -1
- package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/repeat-guard.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/spill.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/verify-stop.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -1
- package/vendor/cli/vendor/desktop/lib/settings.js +1 -1
- package/vendor/cli/vendor/desktop/main.js +82 -1
- package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/cli/vendor/hosts/install.js +1 -1
- package/vendor/cli/vendor/hosts/openai-shim.js +1 -1
- package/vendor/cli/vendor/hosts/spec.js +1 -1
- package/vendor/cli/vendor/hosts/targets.js +1 -1
- package/vendor/cli/vendor/mcp/admission.js +1 -1
- package/vendor/cli/vendor/mcp/server.js +1 -1
- package/vendor/cli/vendor/mcp/tools.js +1 -1
- package/vendor/cli/vendor/one/src/child.js +1 -1
- package/vendor/cli/vendor/one/src/protocol.js +1 -1
- package/vendor/cli/vendor/one/src/selfhost.js +1 -1
- package/vendor/desktop/bin/aegis.js +1 -1
- package/vendor/desktop/lib/auto.js +1 -1
- package/vendor/desktop/lib/avatar/companion.js +1 -1
- package/vendor/desktop/lib/avatar/cosmetics.js +1 -1
- package/vendor/desktop/lib/avatar/holder-turn.js +1 -1
- package/vendor/desktop/lib/avatar/holders.js +1 -1
- package/vendor/desktop/lib/avatar/identity.js +1 -1
- package/vendor/desktop/lib/avatar/level.js +1 -1
- package/vendor/desktop/lib/avatar/mirror.js +1 -1
- package/vendor/desktop/lib/avatar/persona.js +1 -1
- package/vendor/desktop/lib/avatar/profile.js +1 -1
- package/vendor/desktop/lib/avatar/register.js +1 -1
- package/vendor/desktop/lib/avatar/store.js +1 -1
- package/vendor/desktop/lib/avatar/transfer.js +1 -1
- package/vendor/desktop/lib/avatar/turn.js +1 -1
- package/vendor/desktop/lib/avatar/voice.js +1 -1
- package/vendor/desktop/lib/avatar/xp.js +1 -1
- package/vendor/desktop/lib/deep-link.js +1 -1
- package/vendor/desktop/lib/local/attachments.js +1 -1
- package/vendor/desktop/lib/local/autonomous.js +1 -1
- package/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/desktop/lib/local/cli-face.js +1 -1
- package/vendor/desktop/lib/local/context.js +1 -1
- package/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/lib/local/entitlement.js +1 -1
- package/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/lib/local/local.js +1 -1
- package/vendor/desktop/lib/local/perm-rules.js +5 -0
- package/vendor/desktop/lib/local/perm-store.js +5 -0
- package/vendor/desktop/lib/local/perm-write.js +5 -0
- package/vendor/desktop/lib/local/pro-sessions.js +3 -1
- package/vendor/desktop/lib/local/prompt.js +1 -1
- package/vendor/desktop/lib/local/pty-host.js +1 -1
- package/vendor/desktop/lib/local/queue.js +1 -1
- package/vendor/desktop/lib/local/repeat-guard.js +1 -1
- package/vendor/desktop/lib/local/session-rounds.js +1 -1
- package/vendor/desktop/lib/local/spill.js +1 -1
- package/vendor/desktop/lib/local/telemetry.js +1 -1
- package/vendor/desktop/lib/local/turn-guard.js +1 -1
- package/vendor/desktop/lib/local/verify-stop.js +1 -1
- package/vendor/desktop/lib/local/worktree-lock.js +1 -1
- package/vendor/desktop/lib/provider-key-mirror.js +1 -1
- package/vendor/desktop/lib/quick-launcher.js +1 -1
- package/vendor/desktop/lib/settings.js +1 -1
- package/vendor/desktop/lib/skills-host.js +1 -1
- package/vendor/desktop/lib/speech-host.js +1 -1
- package/vendor/desktop/lib/sync/memory-store.js +1 -1
- package/vendor/desktop/lib/sync/persist-gate.js +1 -1
- package/vendor/desktop/lib/window-state.js +1 -1
- package/vendor/desktop/main.js +82 -1
- package/vendor/desktop/package.json +1 -1
- package/vendor/desktop/preload.js +3 -1
- package/vendor/desktop/renderer/app.js +3 -3
- package/vendor/desktop/renderer/avatar/assemble.js +1 -1
- package/vendor/desktop/renderer/avatar/avatar.js +1 -1
- package/vendor/desktop/renderer/avatar/cards.js +1 -1
- package/vendor/desktop/renderer/avatar/hud.js +1 -1
- package/vendor/desktop/renderer/avatar/pane.js +1 -1
- package/vendor/desktop/renderer/avatar/parts.js +1 -1
- package/vendor/desktop/renderer/commands.js +1 -1
- package/vendor/desktop/renderer/companion.js +1 -1
- package/vendor/desktop/renderer/composer-triggers.js +1 -1
- package/vendor/desktop/renderer/dictation.js +1 -1
- package/vendor/desktop/renderer/diff.js +1 -1
- package/vendor/desktop/renderer/diffview.js +1 -1
- package/vendor/desktop/renderer/fingerprint.js +2 -2
- package/vendor/desktop/renderer/index.html +10 -4
- package/vendor/desktop/renderer/library.js +1 -1
- package/vendor/desktop/renderer/markdown.js +1 -1
- package/vendor/desktop/renderer/palette-filter.js +1 -1
- package/vendor/desktop/renderer/provider-toolbar.js +1 -1
- package/vendor/desktop/renderer/providers.js +1 -1
- package/vendor/desktop/renderer/pty-frame.css +35 -0
- package/vendor/desktop/renderer/pty-frame.html +47 -0
- package/vendor/desktop/renderer/pty-panel.js +1 -1
- package/vendor/desktop/renderer/pty-window.html +72 -0
- package/vendor/desktop/renderer/pty-window.js +3 -0
- package/vendor/desktop/renderer/quick.js +1 -1
- package/vendor/desktop/renderer/settings-skills.js +1 -1
- package/vendor/desktop/renderer/shortcuts.js +1 -1
- package/vendor/desktop/renderer/stream-policy.js +1 -1
- package/vendor/desktop/renderer/style.css +77 -3
- package/vendor/desktop/renderer/transcript-view.js +1 -1
- package/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/desktop/renderer/welcome-rows.js +1 -1
- package/vendor/desktop/vendor/aegis.js +1 -1
- package/vendor/desktop/vendor/attest.js +1 -1
- package/vendor/desktop/vendor/authorship-key.js +1 -1
- package/vendor/desktop/vendor/auto-provision.js +1 -1
- package/vendor/desktop/vendor/brain-catalog.js +1 -1
- package/vendor/desktop/vendor/byok-catalog.js +1 -1
- package/vendor/desktop/vendor/catalog-client.js +1 -1
- package/vendor/desktop/vendor/conversation-export.js +1 -1
- package/vendor/desktop/vendor/credentials.js +1 -1
- package/vendor/desktop/vendor/credits.js +1 -1
- package/vendor/desktop/vendor/drive-connect.js +1 -1
- package/vendor/desktop/vendor/env-file.js +1 -1
- package/vendor/desktop/vendor/faces/cli/bin/aegiscode.js +2 -2
- package/vendor/desktop/vendor/faces/cli/package.json +1 -1
- package/vendor/desktop/vendor/faces/cli/scripts/check.mjs +1 -1
- package/vendor/desktop/vendor/faces/cli/scripts/demo.mjs +1 -1
- package/vendor/desktop/vendor/faces/cli/scripts/postinstall.mjs +1 -1
- package/vendor/desktop/vendor/faces/cli/scripts/predist.mjs +1 -1
- package/vendor/desktop/vendor/faces/cli/scripts/runtests.mjs +1 -1
- package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/art.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/autonomous.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/caps.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/chatflow.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/checkpoint.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/clipboard.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/cloudsync.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/commands.js +2 -2
- package/vendor/desktop/vendor/faces/cli/src/config.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/connect.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/devrun.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/diff.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/diffview.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/dream-cmd.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/dream.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/engine.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/events.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/export.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/fingerprint.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/format.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/fuzzy.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/history.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/init.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/limits.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/markdown.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/mcp.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/models.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/overlays.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/panels.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/permissions.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/ping.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/presence.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/provenance.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/provenance.lock.json +3 -3
- package/vendor/desktop/vendor/faces/cli/src/render.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/screen.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/screens.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/secret.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/securefs.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/settings.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/signup.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/summarize.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/sysdiag.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/theme.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/title.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/todos.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/tokens.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/topup.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/update.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/aegis.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/attest.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/authorship-key.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/auto-provision.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/brain-catalog.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/catalog-client.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/conversation-export.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/credentials.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/credits.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/drive-connect.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/env-file.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/fingerprint.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-memory.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-sessions.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/google-signin.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/hooks.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/model-discovery.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/model-sync.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/platform.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/presence.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/record-vault.js +2 -2
- package/vendor/desktop/vendor/faces/cli/vendor/client/session-search.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/session-store.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/skills.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/topup.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/touch.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/update.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/user-models.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/attachments.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/autonomous.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/context.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/entitlement.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/exec-plan.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/local.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-rules.js +2 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-store.js +3 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-write.js +2 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/pro-sessions.js +3 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/queue.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/repeat-guard.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/session-rounds.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/shell.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/spill.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/turn-guard.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/verify-stop.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/worktree-lock.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +3 -3
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/hosts/install.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/hosts/openai-shim.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/hosts/spec.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/hosts/targets.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/admission.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/server.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/tools.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/child.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/protocol.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/selfhost.js +1 -1
- package/vendor/desktop/vendor/fingerprint.js +1 -1
- package/vendor/desktop/vendor/foreign-memory.js +1 -1
- package/vendor/desktop/vendor/foreign-sessions.js +1 -1
- package/vendor/desktop/vendor/google-signin.js +1 -1
- package/vendor/desktop/vendor/hooks.js +1 -1
- package/vendor/desktop/vendor/model-discovery.js +1 -1
- package/vendor/desktop/vendor/model-sync.js +1 -1
- package/vendor/desktop/vendor/naming.js +1 -1
- package/vendor/desktop/vendor/platform.js +1 -1
- package/vendor/desktop/vendor/prefs.js +1 -1
- package/vendor/desktop/vendor/presence.js +1 -1
- package/vendor/desktop/vendor/protocol.js +1 -1
- package/vendor/desktop/vendor/record-vault.js +2 -2
- package/vendor/desktop/vendor/selfhost.js +1 -1
- package/vendor/desktop/vendor/session-search.js +1 -1
- package/vendor/desktop/vendor/session-store.js +1 -1
- package/vendor/desktop/vendor/skills.js +1 -1
- package/vendor/desktop/vendor/topup.js +1 -1
- package/vendor/desktop/vendor/touch.js +1 -1
- package/vendor/desktop/vendor/update.js +1 -1
- package/vendor/desktop/vendor/user-models.js +1 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const crypto=require("node:crypto"),fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),fp=require("./fingerprint.js"),KEY_FILE_MODE=384,DIR_MODE=448,GROUP_OTHER_BITS=63,KEY_BYTES=32,SECRET_ENV="AEGIS_FINGERPRINT_SECRET",HOME_ENV="AEGIS_HOME",KEY_FILENAME="authorship.key",isWin="win32"===process.platform;function dataDir(e=process.env){const r=e[HOME_ENV];return r&&String(r).trim()?path.resolve(String(r).trim()):path.join(os.homedir(),".aegiscode")}function defaultKeyPath(e=process.env){return path.join(dataDir(e),"keys",KEY_FILENAME)}function modeOf(e){return 511&fs.statSync(e).mode}function modeString(e){return e.toString(8).padStart(3,"0")}function assertPrivate(e){if(isWin)return;const r=modeOf(e);if(r
|
|
3
|
+
"use strict";const crypto=require("node:crypto"),fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),fp=require("./fingerprint.js"),KEY_FILE_MODE=384,DIR_MODE=448,GROUP_OTHER_BITS=63,KEY_BYTES=32,SECRET_ENV="AEGIS_FINGERPRINT_SECRET",HOME_ENV="AEGIS_HOME",KEY_FILENAME="authorship.key",isWin="win32"===process.platform;function dataDir(e=process.env){const r=e[HOME_ENV];return r&&String(r).trim()?path.resolve(String(r).trim()):path.join(os.homedir(),".aegiscode")}function defaultKeyPath(e=process.env){return path.join(dataDir(e),"keys",KEY_FILENAME)}function modeOf(e){return 511&fs.statSync(e).mode}function modeString(e){return e.toString(8).padStart(3,"0")}function assertPrivate(e){if(isWin)return;const r=modeOf(e);if(63&r)throw new Error(`authorship-key: ${e} is mode ${modeString(r)} — a secret file must not be group/other readable. chmod 600 ${e}`)}function readSecretFile(e){const r=fs.readFileSync(e,"utf8").replace(/\r?\n$/,"");if(!r.trim())throw new Error(`authorship-key: ${e} is empty`);if(/\s/.test(r.trim()))throw new Error(`authorship-key: ${e} holds more than one line — not a key file`);return r.trim()}function flag(e,r,t=null){const i="--secret"===r?["--secret","--secret-file"]:[r];for(const r of i){const t=e.indexOf(r);if(-1!==t&&void 0!==e[t+1]&&!e[t+1].startsWith("--"))return e[t+1]}return t}function hasFlag(e,r){return("--secret"===r?["--secret","--secret-file"]:[r]).some(r=>e.includes(r))}function resolveKey(e={}){const r=e.argv||[],t=e.env||process.env,i=flag(r,"--secret");if(i){if(!fs.existsSync(i))throw new Error(`authorship-key: no such secret file: ${i}`);return assertPrivate(i),{secret:readSecretFile(i),source:i,public:!1,path:i}}if(hasFlag(r,"--public")){const e=flag(r,"--covenant");if(!e)throw new Error("authorship-key: --public requires --covenant <file> — the public key IS the covenant document's hash, so it cannot be assumed");if(!fs.existsSync(e))throw new Error(`authorship-key: no such covenant file: ${e}`);return{secret:crypto.createHash("sha256").update(fs.readFileSync(e)).digest("hex"),source:`covenant (public): ${e}`,public:!0,path:null}}const o=t[SECRET_ENV];if(o&&String(o).trim())return{secret:String(o).trim(),source:SECRET_ENV,public:!1,path:null};const n=defaultKeyPath(t);return fs.existsSync(n)?(assertPrivate(n),{secret:readSecretFile(n),source:n,public:!1,path:n}):{secret:null,source:null,public:!1,path:null}}function writeSecret(e,r){try{fs.mkdirSync(path.dirname(e),{recursive:!0,mode:448}),fs.writeFileSync(e,r+"\n",{mode:384})}catch(r){const t=r&&r.code,i=path.dirname(e);if("EACCES"===t||"EPERM"===t)throw new Error(`authorship-key: cannot write ${e} — ${i} is not writable by this user (${t}). Fix it with: chmod u+rwx ${i}`);if("EROFS"===t)throw new Error(`authorship-key: cannot write ${e} — ${i} is on a read-only filesystem (EROFS). Point --out (or $AEGIS_HOME) at a writable location.`);if("ENOSPC"===t)throw new Error(`authorship-key: cannot write ${e} — the disk is full (ENOSPC).`);throw r}}function keygen(e={}){const r=e.argv||[],t=e.env||process.env,i=path.resolve(flag(r,"--out")||defaultKeyPath(t)),o=hasFlag(r,"--force")||!0===e.force,n=fs.existsSync(i);if(n&&!o)throw new Error(`authorship-key: ${i} already exists — pass --force to replace it`);n&&!isWin&&assertPrivate(i);const s=crypto.randomBytes(32).toString("base64url");if(writeSecret(i,s),fs.chmodSync(i,384),!isWin){const e=modeOf(i);if(384!==e)throw new Error(`authorship-key: ${i} landed mode ${modeString(e)}, expected 600 — refusing to report success for a key another user may be able to read`)}if(readSecretFile(i)!==s)throw new Error(`authorship-key: ${i} does not read back as written`);return{out:i,created:!n,replaced:n,keyFingerprint:fp.keyFingerprint(s),bytes:32,secretPrinted:!1,mode:isWin?"n/a":modeString(modeOf(i))}}function git(e,r){try{return execFileSync("git",e,{cwd:r,encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return null}}function insideGitTree(e){return"true\n"===git(["rev-parse","--is-inside-work-tree"],e)}function backup(e={}){const r=e.argv||[],t=e.env||process.env,i=flag(r,"--to");if(!i)throw new Error("authorship-key: backup requires --to DIR");const o=flag(r,"--secret")||defaultKeyPath(t);if(!fs.existsSync(o))throw new Error(`authorship-key: no key at ${o} — run keygen first`);assertPrivate(o);const n=path.resolve(i),s=flag(r,"--name")||path.basename(o),a=path.join(n,s);if(insideGitTree(n)&&!hasFlag(r,"--allow-git")&&!e.allowGit&&null===git(["check-ignore","-q",a],n))throw new Error(`authorship-key: ${a} is inside a git working tree and is not gitignored — a committed key cannot be un-published. Add it to .gitignore, choose another --to, or pass --allow-git if you know the destination is protected`);const c=readSecretFile(o);if(writeSecret(a,c),fs.chmodSync(a,384),!isWin&&384!==modeOf(a))throw new Error(`authorship-key: ${a} landed mode ${modeString(modeOf(a))}, expected 600`);if(readSecretFile(a)!==c)throw new Error(`authorship-key: ${a} does not read back as the same key`);return{from:o,to:a,keyFingerprint:fp.keyFingerprint(c),matchesSource:!0,secretPrinted:!1}}module.exports={KEY_FILE_MODE:384,DIR_MODE:448,GROUP_OTHER_BITS:63,KEY_BYTES:32,SECRET_ENV:SECRET_ENV,HOME_ENV:HOME_ENV,KEY_FILENAME:KEY_FILENAME,dataDir:dataDir,defaultKeyPath:defaultKeyPath,assertPrivate:assertPrivate,readSecretFile:readSecretFile,flag:flag,hasFlag:hasFlag,resolveKey:resolveKey,keygen:keygen,backup:backup,modeString:modeString};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const{machineFingerprint:machineFingerprint}=require("./device-fingerprint.js"),DEVICE_REGISTER_TIMEOUT_MS=8e3,DEVICE_REGISTER_RETRY_DELAYS_MS=[1e3,3e3];function isTransientRegisterError(e){const r=e&&e.status;return!r||408===r||r>=500}function provisionFailureText(e){const r=e&&e.error;return r?429===r.status?"too many sign-ups from this network — try again later":r.status>=500?`aegiscloud.org failed to register this device: ${r.message}`:isTransientRegisterError(r)?"could not reach aegiscloud.org":`the server refused the request (HTTP ${r.status})`:"the server returned no account key"}function trialOutcomeNote(e){return e&&e.reusedAccount?". This machine was already registered, so it got its existing account back — the welcome trial is granted once per machine, ever, and was not granted again. A fresh trial needs a new sign-up, not a new key.":e&&!1===e.trialGranted?". The welcome trial was withheld this hour (too many new devices from this network)":""}async function autoProvisionApiKey(e,r,t={}){if(Array.isArray(t))throw new TypeError("autoProvisionApiKey takes { app, retryDelaysMs }; a bare retry array is no longer accepted");if(e.apiKey)return{ok:!0,key:e.apiKey};const{app:i,retryDelaysMs:n=DEVICE_REGISTER_RETRY_DELAYS_MS}=t;let o=null;for(let t=0;t<=n.length;t++){t>0&&await new Promise(
|
|
3
|
+
"use strict";const{machineFingerprint:machineFingerprint}=require("./device-fingerprint.js"),DEVICE_REGISTER_TIMEOUT_MS=8e3,DEVICE_REGISTER_RETRY_DELAYS_MS=[1e3,3e3];function isTransientRegisterError(e){const r=e&&e.status;return!r||408===r||r>=500}function provisionFailureText(e){const r=e&&e.error;return r?429===r.status?"too many sign-ups from this network — try again later":r.status>=500?`aegiscloud.org failed to register this device: ${r.message}`:isTransientRegisterError(r)?"could not reach aegiscloud.org":`the server refused the request (HTTP ${r.status})`:"the server returned no account key"}function trialOutcomeNote(e){return e&&e.reusedAccount?". This machine was already registered, so it got its existing account back — the welcome trial is granted once per machine, ever, and was not granted again. A fresh trial needs a new sign-up, not a new key.":e&&!1===e.trialGranted?". The welcome trial was withheld this hour (too many new devices from this network)":""}async function autoProvisionApiKey(e,r,t={}){if(Array.isArray(t))throw new TypeError("autoProvisionApiKey takes { app, retryDelaysMs }; a bare retry array is no longer accepted");if(e.apiKey)return{ok:!0,key:e.apiKey};const{app:i,retryDelaysMs:n=DEVICE_REGISTER_RETRY_DELAYS_MS}=t;let o=null;for(let t=0;t<=n.length;t++){t>0&&await new Promise(e=>setTimeout(e,n[t-1]));const a=new AbortController,s=setTimeout(()=>a.abort(),8e3);try{const t=await e.registerDevice(machineFingerprint(),{app:i,signal:a.signal}),n=t&&"string"==typeof t.api_key?t.api_key.trim():"";if(!n)return{ok:!1,key:""};const o=r.saveApiKey(n);return e.setApiKey(n),{ok:!!o.ok,key:n,trialGranted:t.trial_granted,reusedAccount:!0===t.reused_account}}catch(e){if(o=e,!isTransientRegisterError(e))break}finally{clearTimeout(s)}}return{ok:!1,key:"",error:o}}module.exports={autoProvisionApiKey:autoProvisionApiKey,provisionFailureText:provisionFailureText,trialOutcomeNote:trialOutcomeNote,DEVICE_REGISTER_TIMEOUT_MS:8e3,DEVICE_REGISTER_RETRY_DELAYS_MS:DEVICE_REGISTER_RETRY_DELAYS_MS};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const NEXUS_BRAIN_IDS=Object.freeze(["nexus-brain","aegis-brain"]),AEGIS_CLOUD_MODEL_IDS=Object.freeze(["nexus-brain","aegis-brain","nexus-brain-smart","aegis-brain-smart","nexus-brain-neo","aegis-brain-neo"]),AEGIS_CLOUD_MODEL_RE=/^(?:nexus|aegis)-brain(?:-(?:smart|neo))?$/,NEXUS_LABEL="Nexus",AUTO_MODEL_ID="nexus";function isAutoModelId(e){return"nexus"===String(null==e?"":e).trim().toLowerCase()}const AUTO_LABEL="Nexus — auto-route",AUTO_NOTE="server picks fast/smart/neo from the ask";function aliasOfEntry(e){if(!e||"object"!=typeof e)return null;for(const i of[e.alias_of,e.aliasOf])if("string"==typeof i&&i.trim())return i.trim();return null}function isHiddenEntry(e){return Boolean(e)&&!0===e.hidden}function selectBrainEntry(e){const i=Array.isArray(e)?e.filter(Boolean):[];return i.find(
|
|
3
|
+
"use strict";const NEXUS_BRAIN_IDS=Object.freeze(["nexus-brain","aegis-brain"]),AEGIS_CLOUD_MODEL_IDS=Object.freeze(["nexus-brain","aegis-brain","nexus-brain-smart","aegis-brain-smart","nexus-brain-neo","aegis-brain-neo"]),AEGIS_CLOUD_MODEL_RE=/^(?:nexus|aegis)-brain(?:-(?:smart|neo))?$/,NEXUS_LABEL="Nexus",AUTO_MODEL_ID="nexus";function isAutoModelId(e){return"nexus"===String(null==e?"":e).trim().toLowerCase()}const AUTO_LABEL="Nexus — auto-route",AUTO_NOTE="server picks fast/smart/neo from the ask";function aliasOfEntry(e){if(!e||"object"!=typeof e)return null;for(const i of[e.alias_of,e.aliasOf])if("string"==typeof i&&i.trim())return i.trim();return null}function isHiddenEntry(e){return Boolean(e)&&!0===e.hidden}function selectBrainEntry(e){const i=Array.isArray(e)?e.filter(Boolean):[];return i.find(e=>NEXUS_BRAIN_IDS.includes(e.id)&&!isHiddenEntry(e)&&null===aliasOfEntry(e))||i.find(e=>NEXUS_BRAIN_IDS.includes(e.id))||i.find(e=>NEXUS_BRAIN_IDS.includes(aliasOfEntry(e)))||null}function filterAegisCatalog(e){const i=selectBrainEntry(e);if(!i)return[];const{hidden:t,alias_of:n,aliasOf:r,...s}=i;return[{...s,label:"Nexus"}]}function isAegisCloudModel(e){const i="string"==typeof e?e.trim():e&&"object"==typeof e&&"string"==typeof e.id?e.id.trim():"";return!!AEGIS_CLOUD_MODEL_IDS.includes(i)||!!AEGIS_CLOUD_MODEL_RE.test(i)||NEXUS_BRAIN_IDS.includes(aliasOfEntry(e))}function omitAegisCloudModels(e){return(Array.isArray(e)?e:[]).filter(e=>{if(!e)return!1;if("string"==typeof e)return!isAegisCloudModel(e);const i="string"==typeof e.id?e.id.trim():"";return Boolean(i)&&!isAegisCloudModel(e)})}function offerableCatalog(e){const i=Array.isArray(e)?e.filter(Boolean):[];if(!i.length)return[];const t=selectBrainEntry(i),n=[],r=new Set;if(t){const{hidden:e,alias_of:i,aliasOf:s,...o}=t;n.push({...o,label:"Nexus"});for(const e of NEXUS_BRAIN_IDS)r.add(e);"string"==typeof t.id&&r.add(t.id)}const s=new Set(i.map(e=>"string"==typeof e.id?e.id.trim():"").filter(Boolean)),o=new Set(i.map(e=>aliasOfEntry(e)).filter(e=>e&&s.has(e)));for(const e of i){const i="string"==typeof e.id?e.id.trim():"";i&&!r.has(i)&&(aliasOfEntry(e)&&o.has(aliasOfEntry(e))||(r.add(i),n.push(e)))}return n}module.exports={NEXUS_BRAIN_IDS:NEXUS_BRAIN_IDS,NEXUS_LABEL:"Nexus",AUTO_MODEL_ID:"nexus",AUTO_LABEL:AUTO_LABEL,AUTO_NOTE:AUTO_NOTE,isAutoModelId:isAutoModelId,AEGIS_CLOUD_MODEL_IDS:AEGIS_CLOUD_MODEL_IDS,isAegisCloudModel:isAegisCloudModel,omitAegisCloudModels:omitAegisCloudModels,selectBrainEntry:selectBrainEntry,filterAegisCatalog:filterAegisCatalog,offerableCatalog:offerableCatalog};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const BYOK_MODEL_ADDITIONS=Object.freeze({}),WIRE_MODEL_ALIASES=Object.freeze({deepseek:Object.freeze({"deepseek-v4.1-flash":"deepseek-flash","deepseek-flash-41":"deepseek-flash","deepseek-flash-0731":"deepseek-flash","deepseek-v4-flash-0731":"deepseek-flash","deepseek-pro":"deepseek-v4-pro","deepseek-v4-pro-latest":"deepseek-v4-pro","deepseek-v4.1-flash-1017":"deepseek-flash","deepseek-v4-pro-0813":"deepseek-v4-pro"})}),SNAPSHOT_SUFFIX_RE=/-(?:\d{4}|\d{8})$/;function knownWireId(e,r){return Object.prototype.hasOwnProperty.call(e,r)?e[r]:Object.values(e).includes(r)?r:""}function canonicalModelId(e,r){const o="string"==typeof r?r.trim():"";if(!o)return o;const s="string"==typeof e?e.trim():"",n=s?WIRE_MODEL_ALIASES[s]:null;if(!n)return o;const t=knownWireId(n,o);if(t)return t;const i=o.replace(SNAPSHOT_SUFFIX_RE,"");if(i!==o){const e=knownWireId(n,i);if(e)return e}return o}function addedModelsFor(e){const r="string"==typeof e?e.trim():"",o=r?BYOK_MODEL_ADDITIONS[r]:null;return Array.isArray(o)?o.slice():[]}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map(
|
|
3
|
+
"use strict";const BYOK_MODEL_ADDITIONS=Object.freeze({}),WIRE_MODEL_ALIASES=Object.freeze({deepseek:Object.freeze({"deepseek-v4.1-flash":"deepseek-flash","deepseek-flash-41":"deepseek-flash","deepseek-flash-0731":"deepseek-flash","deepseek-v4-flash-0731":"deepseek-flash","deepseek-pro":"deepseek-v4-pro","deepseek-v4-pro-latest":"deepseek-v4-pro","deepseek-v4.1-flash-1017":"deepseek-flash","deepseek-v4-pro-0813":"deepseek-v4-pro"})}),SNAPSHOT_SUFFIX_RE=/-(?:\d{4}|\d{8})$/;function knownWireId(e,r){return Object.prototype.hasOwnProperty.call(e,r)?e[r]:Object.values(e).includes(r)?r:""}function canonicalModelId(e,r){const o="string"==typeof r?r.trim():"";if(!o)return o;const s="string"==typeof e?e.trim():"",n=s?WIRE_MODEL_ALIASES[s]:null;if(!n)return o;const t=knownWireId(n,o);if(t)return t;const i=o.replace(SNAPSHOT_SUFFIX_RE,"");if(i!==o){const e=knownWireId(n,i);if(e)return e}return o}function addedModelsFor(e){const r="string"==typeof e?e.trim():"",o=r?BYOK_MODEL_ADDITIONS[r]:null;return Array.isArray(o)?o.slice():[]}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map(e=>"string"==typeof e?e:e&&e.id).map(e=>"string"==typeof e?e.trim():"").filter(Boolean)}function withByokAdditions(e){const r=Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null;if(!r)return[];const o=[];for(const e of r){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.id?e.id.trim():"",s=r?BYOK_MODEL_ADDITIONS[r]:null;if(!Array.isArray(s)||!s.length){o.push(e);continue}const n=new Set(modelIdsOf(e)),t=s.filter(e=>!n.has(e));if(!t.length){o.push(e);continue}const i=Array.isArray(e.models)?e.models:[];o.push({...e,models:[...i,...t]})}return o}const NEXUS_ELIGIBLE_PROVIDERS=Object.freeze(["deepseek","openai","groq","gemini","openrouter","together","grok","xai","mistral","cerebras","fireworks"]),NEXUS_POOLED_PROVIDER_ID=Object.freeze({xai:"grok"});function nexusFallbackProvider(e){const r="string"==typeof e?e.trim().toLowerCase():"";return r&&NEXUS_ELIGIBLE_PROVIDERS.includes(r)?NEXUS_POOLED_PROVIDER_ID[r]||r:""}function nexusFallbackModel({provider:e,providerKey:r,aegisKey:o,providerKeyRefused:s}={}){return r||s?"":o?nexusFallbackProvider(e):""}function nexusFallbackNotice(e){const r=e&&e.pooled_from;return r?`no ${r} key — answered through your AEGIS account${e.pooled_model?` (${e.pooled_model})`:""}`:""}module.exports={BYOK_MODEL_ADDITIONS:BYOK_MODEL_ADDITIONS,WIRE_MODEL_ALIASES:WIRE_MODEL_ALIASES,NEXUS_ELIGIBLE_PROVIDERS:NEXUS_ELIGIBLE_PROVIDERS,NEXUS_POOLED_PROVIDER_ID:NEXUS_POOLED_PROVIDER_ID,addedModelsFor:addedModelsFor,canonicalModelId:canonicalModelId,nexusFallbackModel:nexusFallbackModel,nexusFallbackNotice:nexusFallbackNotice,nexusFallbackProvider:nexusFallbackProvider,withByokAdditions:withByokAdditions};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const fs=require("fs"),path=require("path"),credentials=require("./credentials.js"),CATALOG_FILE="catalog.json",STALE_AFTER_MS=864e5;function catalogDir(e){return e&&e.dir||credentials.aegisHome(e&&e.env)}function catalogPath(e){return path.join(catalogDir(e),CATALOG_FILE)}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map(
|
|
3
|
+
"use strict";const fs=require("fs"),path=require("path"),credentials=require("./credentials.js"),CATALOG_FILE="catalog.json",STALE_AFTER_MS=864e5;function catalogDir(e){return e&&e.dir||credentials.aegisHome(e&&e.env)}function catalogPath(e){return path.join(catalogDir(e),CATALOG_FILE)}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map(e=>"string"==typeof e?e:e&&e.id).map(e=>"string"==typeof e?e.trim():"").filter(Boolean)}function providerArray(e){return Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null}function indexCatalog(e){const t=Object.create(null),r=Array.isArray(e&&e.models)?e.models:[];for(const e of r){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.provider_id?e.provider_id.trim():"",o="string"==typeof e.model_id?e.model_id.trim():"";r&&o&&"active"===("string"==typeof e.status?e.status.toLowerCase():"active")&&(t[r]||(t[r]=[])).push(o)}return t}function read(e){const t=catalogPath(e);let r,o;try{r=fs.readFileSync(t,"utf8")}catch(e){return null}try{o=JSON.parse(r)}catch(e){return null}if(!o||"object"!=typeof o||!Array.isArray(o.providers))return null;let n=null;const a=o.snapshot&&(o.snapshot.fetched_at||o.snapshot.fetchedAt);if("string"==typeof a&&a){const e=Date.parse(a);Number.isNaN(e)||(n=e)}if(null===n)try{n=fs.statSync(t).mtimeMs}catch(e){n=null}const s=null===n?null:Math.max(0,Date.now()-n);let i=null;const l=o.snapshot&&o.snapshot.revalidated_at;if("string"==typeof l&&l){const e=Date.parse(l);Number.isNaN(e)||(i=e)}const d=null!==i&&(null===n||i>n)?i:n;return{data:o,fetchedAt:n,revalidatedAt:i,ageMs:s,stale:null===d||Date.now()-d>864e5,path:t}}function write(e,t){const r=catalogPath(t);fs.mkdirSync(path.dirname(r),{recursive:!0});const o=`${r}.${process.pid}.tmp`;return fs.writeFileSync(o,JSON.stringify(e),"utf8"),fs.renameSync(o,r),r}function withCatalog(e,t,r){const o=providerArray(e);if(!o)return[];let n=t;if(void 0===n){const e=read(r);n=e?e.data:null}const a=indexCatalog(n);if(!Object.keys(a).length)return o.slice();const s=[];for(const e of o){if(!e||"object"!=typeof e)continue;const t="string"==typeof e.id?e.id.trim():"",r=t?a[t]:null;if(!r||!r.length){s.push(e);continue}const o=new Set(modelIdsOf(e)),n=r.filter(e=>!o.has(e));if(!n.length){s.push(e);continue}const i=Array.isArray(e.models)?e.models:[];s.push({...e,models:[...i,...n]})}return s}function addedModelsFor(e,t,r,o){const n="string"==typeof e?e.trim():"";if(!n)return[];let a=r;if(void 0===a){const e=read(o);a=e?e.data:null}const s=indexCatalog(a)[n]||[],i=(providerArray(t)||[]).find(e=>e&&"string"==typeof e.id&&e.id.trim()===n),l=new Set(modelIdsOf(i));return s.filter(e=>!l.has(e))}const MAX_PAGES=200;async function refresh(e,t){const r=t||{},o=r.limit||500,n=r.maxPages||200,a=read(r),s=a&&a.data||null,i=[];let l=null,d=0,c=r.etag||null,u=null,f=!1;try{for(;;){const t=await e({cursor:l,limit:o,etag:c});if(!t||t.notModified){f=!0;break}0===d&&t.etag&&(u=t.etag);const r=Array.isArray(t.models)?t.models:[];for(const e of r)e&&"object"==typeof e&&i.push(e);if(d+=1,!t.has_more||!t.next_cursor)break;if(d>=n)return _refreshResult({ok:!1,changed:!1,pages:d,models:i.length,providers:0,staleKept:Boolean(s),reason:`stopped after ${d} pages; cache left untouched`});l=t.next_cursor,c=null}}catch(e){return _refreshResult({ok:!1,changed:!1,pages:d,models:0,providers:0,staleKept:Boolean(s),reason:e&&e.message||String(e)})}if(f){let e=null;if(s)try{const t="function"==typeof r.now?r.now():Date.now();e=write({...s,snapshot:{...s.snapshot||{},revalidated_at:new Date(t).toISOString(),...u?{etag:u}:{}}},r)}catch{e=null}return _refreshResult({ok:!0,changed:!1,pages:0,models:0,providers:0,staleKept:!e,written:e,reason:"not-modified"})}if(!i.length)return _refreshResult({ok:!1,changed:!1,pages:d,models:0,providers:0,staleKept:Boolean(s),reason:"empty catalog; cache left untouched"});const p=s&&Array.isArray(s.providers)?s.providers:[],h="function"==typeof r.now?r.now():Date.now(),g={schema_version:s&&s.schema_version||1,providers:p,models:i,snapshot:{fetched_at:new Date(h).toISOString(),models_seen:i.length,providers_seen:p.length,source:"catalog-api",...u?{etag:u}:{}}};let m=null;try{m=write(g,r)}catch(e){return _refreshResult({ok:!1,changed:!1,pages:d,models:i.length,providers:p.length,staleKept:Boolean(s),reason:e&&e.message||String(e)})}return _refreshResult({ok:!0,changed:!0,pages:d,models:i.length,providers:p.length,staleKept:!1,written:m})}function _refreshResult(e){return{ok:Boolean(e.ok),changed:Boolean(e.changed),written:e.written||null,pages:e.pages||0,models:e.models||0,providers:e.providers||0,staleKept:Boolean(e.staleKept),...e.reason?{reason:e.reason}:{}}}module.exports={CATALOG_FILE:CATALOG_FILE,STALE_AFTER_MS:864e5,MAX_PAGES:200,catalogDir:catalogDir,catalogPath:catalogPath,indexCatalog:indexCatalog,read:read,write:write,refresh:refresh,withCatalog:withCatalog,addedModelsFor:addedModelsFor};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const SCOPE_CONVERSATION="conversation",SCOPE_MEMORY="memory",SCOPE_TEXT={
|
|
3
|
+
"use strict";const SCOPE_CONVERSATION="conversation",SCOPE_MEMORY="memory",SCOPE_TEXT={[SCOPE_CONVERSATION]:"one conversation",[SCOPE_MEMORY]:"the whole memory base"};function keyTag(e){const n="string"==typeof e?e.trim():"";return n?`φ_${n}`:null}function authorLine(e){return keyTag(e)||"no key — this copy is unsigned"}function safeFileName(e,n){return String(e||n||"aegis-export").normalize("NFKD").replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"aegis-export"}function stamp({scope:e,keyFingerprint:n=null,email:t=null,exportedAt:o=null,subject:r=null,count:i=null}={}){const a=keyTag(n),s=[];return r&&s.push(`**What this is:** ${r}`),s.push(`**Scope:** ${SCOPE_TEXT[e]||String(e||"unknown")} (${e||"unknown"})`),s.push(`**Author:** ${authorLine(n)}`),s.push(`**Account:** ${t||"not reported by the server"}`),null!=i&&s.push(`**Entries:** ${i}`),s.push(`**Exported:** ${o||"timestamp not recorded"}`),s.push(a?`**Sealed by:** ${a} — this is a key tag, not the key. It proves the same machine wrote it.`:"**Sealed by:** nothing — no authorship key is set on this machine, so this copy cannot prove it came from you."),`${s.join("\n")}\n\n`}function conversationMarkdown(e,n={}){return`# ${e&&(e.title||e.id)||"Untitled conversation"}\n\n${stamp({scope:"conversation",subject:null,keyFingerprint:n.keyFingerprint,email:n.email,exportedAt:n.exportedAt,count:void 0===n.count?null:n.count})}---\n\n${n.transcript||""}`}function memoryMarkdown(e,n={}){return`${stamp({scope:"memory",subject:null,keyFingerprint:n.keyFingerprint,email:n.email,exportedAt:n.exportedAt,count:void 0===n.count?null:n.count})}---\n\n${e||""}`}function conversationFileName(e,n){const t=String(n||"").replace(/[:.]/g,"-").replace(/[^\w-]+/g,""),o=safeFileName(e&&(e.title||e.id),"conversation");return t?`${o}-${t}.md`:`${o}.md`}module.exports={SCOPE_CONVERSATION:"conversation",SCOPE_MEMORY:"memory",SCOPE_TEXT:SCOPE_TEXT,keyTag:keyTag,authorLine:authorLine,safeFileName:safeFileName,stamp:stamp,conversationMarkdown:conversationMarkdown,memoryMarkdown:memoryMarkdown,conversationFileName:conversationFileName};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),KEY_ENV="AEGIS_API_KEY",MEMORY_ENV="AEGIS_MEMORY_TOKEN",HOME_ENV="AEGISCODE_HOME",CREDENTIALS_FILE="credentials.json",CONFIG_FILE="config.json",FILE_MODE=384,DIR_MODE=448;function aegisHome(e){const r=e||process.env,n=r&&r[HOME_ENV];return n&&String(n).trim()?path.resolve(String(n).trim()):path.join(os.homedir(),".aegiscode")}function credentialsPath(e){return path.join(e||aegisHome(),CREDENTIALS_FILE)}function configPath(e){return path.join(e||aegisHome(),CONFIG_FILE)}function normalizeApiKey(e){let r=String(null==e?"":e).trim();if(!r)return"";r=r.replace(/^export\s+/i,"").trim();const n=/^[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.+)$/s.exec(r);return n&&(r=n[1].trim()),r=r.replace(/^["']|["']$/g,"").trim(),r=r.replace(/^Bearer\s+/i,"").trim(),r}function validateApiKey(e,r={}){const n=String(r.label||"AEGIS"),t=normalizeApiKey(e);return t?/\s/.test(t)?{ok:!1,key:t,reason:"whitespace",message:"that looks like more than one word — paste just the key"}:t.length<16?{ok:!1,key:t,reason:"too short",message:`that key is ${t.length} characters — ${n} keys are longer than that`}:{ok:!0,key:t,reason:null,message:null}:{ok:!1,key:t,reason:"empty",message:"no key given"}}function readCredentials(e){try{const r=JSON.parse(fs.readFileSync(credentialsPath(e),"utf8"));if(r&&"object"==typeof r)return r}catch{}return{}}function writeCredentials(e,r){const n=credentialsPath(r),t={...readCredentials(r),...e,version:1};try{fs.mkdirSync(path.dirname(n),{recursive:!0,mode:
|
|
3
|
+
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),KEY_ENV="AEGIS_API_KEY",MEMORY_ENV="AEGIS_MEMORY_TOKEN",HOME_ENV="AEGISCODE_HOME",CREDENTIALS_FILE="credentials.json",CONFIG_FILE="config.json",FILE_MODE=384,DIR_MODE=448;function aegisHome(e){const r=e||process.env,n=r&&r[HOME_ENV];return n&&String(n).trim()?path.resolve(String(n).trim()):path.join(os.homedir(),".aegiscode")}function credentialsPath(e){return path.join(e||aegisHome(),CREDENTIALS_FILE)}function configPath(e){return path.join(e||aegisHome(),CONFIG_FILE)}function normalizeApiKey(e){let r=String(null==e?"":e).trim();if(!r)return"";r=r.replace(/^export\s+/i,"").trim();const n=/^[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.+)$/s.exec(r);return n&&(r=n[1].trim()),r=r.replace(/^["']|["']$/g,"").trim(),r=r.replace(/^Bearer\s+/i,"").trim(),r}function validateApiKey(e,r={}){const n=String(r.label||"AEGIS"),t=normalizeApiKey(e);return t?/\s/.test(t)?{ok:!1,key:t,reason:"whitespace",message:"that looks like more than one word — paste just the key"}:t.length<16?{ok:!1,key:t,reason:"too short",message:`that key is ${t.length} characters — ${n} keys are longer than that`}:{ok:!0,key:t,reason:null,message:null}:{ok:!1,key:t,reason:"empty",message:"no key given"}}function readCredentials(e){try{const r=JSON.parse(fs.readFileSync(credentialsPath(e),"utf8"));if(r&&"object"==typeof r)return r}catch{}return{}}function writeCredentials(e,r){const n=credentialsPath(r),t={...readCredentials(r),...e,version:1};try{fs.mkdirSync(path.dirname(n),{recursive:!0,mode:448});const e=n+".tmp";fs.writeFileSync(e,JSON.stringify(t,null,2)+"\n",{mode:384}),fs.renameSync(e,n);try{fs.chmodSync(n,384)}catch{}}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[credentials] write failed:",e),{ok:!1,error:e,credentials:t}}return{ok:!0,credentials:t}}function readLegacyConfig(e){try{const r=JSON.parse(fs.readFileSync(configPath(e),"utf8"));if(!r||"object"!=typeof r)return{};const n=r.aegiscloud&&"object"==typeof r.aegiscloud?r.aegiscloud:{},t=r.memory&&"object"==typeof r.memory?r.memory:{};return{apiKey:normalizeApiKey(n.api_key),memoryToken:String(t.token||"").trim(),syncConversations:!0===n.syncConversations||void 0,lastVerified:n.lastVerified||null,memorySubscribed:!0===t.subscribed||void 0}}catch{return{}}}function legacyKeyOnDisk(e){return!!readLegacyConfig(e).apiKey}function adoptLegacy(e){const r=readLegacyConfig(e),n=readCredentials(e),t={};return r.apiKey&&!n.aegisApiKey&&(t.aegisApiKey=r.apiKey),r.memoryToken&&!n.memoryToken&&(t.memoryToken=r.memoryToken),Object.keys(t).length&&writeCredentials({...t,adoptedFrom:configPath(e)},e).ok?{adopted:Object.keys(t)}:{adopted:[]}}function fromEnvFile(e,r,n){try{const t=require("./env-file.js");return"function"==typeof t.isFromEnvFile&&t.isFromEnvFile(e,r,n?{env:n}:void 0)}catch{return!1}}function resolveApiKey(e={}){const r=e.env||process.env,n=e.dir,t=normalizeApiKey(r&&r[KEY_ENV]);if(t&&!fromEnvFile(KEY_ENV,r&&r[KEY_ENV],r))return{key:t,source:"env",from:KEY_ENV};const o=normalizeApiKey(readCredentials(n).aegisApiKey);if(o)return{key:o,source:"credentials",from:credentialsPath(n)};if(t)return{key:t,source:"envfile",from:envFileLabel(r,n)};const i=readLegacyConfig(n).apiKey;return i?{key:i,source:"config",from:configPath(n)}:{key:"",source:"none",from:""}}function hasApiKey(e={}){return!!resolveApiKey(e).key}function saveApiKey(e,r){const n=validateApiKey(e);if(!n.ok)return{ok:!1,key:n.key,path:credentialsPath(r),message:n.message};const t=writeCredentials({aegisApiKey:n.key,savedAt:(new Date).toISOString()},r);return t.ok?{ok:!0,key:n.key,path:credentialsPath(r)}:{ok:!1,key:n.key,path:credentialsPath(r),error:t.error,message:`could not write ${credentialsPath(r)}`}}function clearApiKey(e){return{cleared:!!normalizeApiKey(readCredentials(e).aegisApiKey),ok:writeCredentials({aegisApiKey:"",adoptedFrom:""},e).ok,path:credentialsPath(e)}}function resolveMemoryToken(e={}){const r=e.env||process.env,n=e.dir,t=String(r&&r[MEMORY_ENV]||"").trim();if(t)return{token:t,source:"env"};const o=readCredentials(n),i=String(o.memoryToken||"").trim();if(i)return{token:i,source:"credentials"};const a=readLegacyConfig(n).memoryToken;return a?{token:a,source:"config"}:{token:"",source:"none"}}function saveMemoryToken(e,r={},n){return writeCredentials({memoryToken:String(e||"").trim(),...r},n)}function clearMemoryToken(e){return writeCredentials({memoryToken:"",memorySubscribed:!1},e)}function keyStatus(e={}){const r=e.dir,{key:n,source:t,from:o}=resolveApiKey(e),i=readCredentials(r);let a=null;try{a=511&fs.statSync(credentialsPath(r)).mode}catch{}return{configured:!!n,key:n,source:t,from:o,path:credentialsPath(r),fileMode:null==a?null:"0"+a.toString(8),stored:!!normalizeApiKey(i.aegisApiKey),legacyPlaintext:legacyKeyOnDisk(r),verifiedAt:i.verifiedAt||null,account:i.account||null,memoryToken:!!resolveMemoryToken(e).token,memorySource:resolveMemoryToken(e).source}}function clientOptions(e={}){const{key:r}=resolveApiKey(e),{token:n}=resolveMemoryToken(e),t={};return t.apiKey=r,t.memoryToken=n,e.channel&&(t.channel=e.channel),t}const SOURCE_LABEL={env:`${KEY_ENV}`,credentials:"saved key file",envfile:`~/.aegiscode/.env (${KEY_ENV})`,config:"config.json (aegis CLI)",none:"not set"};function envFileLabel(e,r){try{const e=require("./env-file.js");if("function"==typeof e.envFileFor)return e.envFileFor(r)}catch{}return envFileForFallback(r)}function envFileForFallback(e){return path.join(e||aegisHome(),".env")}function sourceLabel(e){return SOURCE_LABEL[e]||SOURCE_LABEL.none}function preferNewest(e,r,n={}){const t=normalizeApiKey(e),o=Date.parse(r||"")||0,i=readCredentials(n.dir),a=normalizeApiKey(i.aegisApiKey),s=Date.parse(i.savedAt||"")||0;return a?t?t===a?{key:t,source:"host",sharedAt:s,hostAt:o}:s>o?{key:a,source:"shared",sharedAt:s,hostAt:o}:{key:t,source:"host",sharedAt:s,hostAt:o}:{key:a,source:"shared",sharedAt:s,hostAt:o}:{key:t,source:t?"host":"none",sharedAt:s,hostAt:o}}const HOW_TO_SET="run `aegiscode login` (or /key inside a session) to save one";module.exports={KEY_ENV:KEY_ENV,MEMORY_ENV:MEMORY_ENV,HOME_ENV:HOME_ENV,CREDENTIALS_FILE:CREDENTIALS_FILE,CONFIG_FILE:CONFIG_FILE,aegisHome:aegisHome,credentialsPath:credentialsPath,configPath:configPath,normalizeApiKey:normalizeApiKey,validateApiKey:validateApiKey,readCredentials:readCredentials,writeCredentials:writeCredentials,readLegacyConfig:readLegacyConfig,legacyKeyOnDisk:legacyKeyOnDisk,adoptLegacy:adoptLegacy,resolveApiKey:resolveApiKey,hasApiKey:hasApiKey,fromEnvFile:fromEnvFile,envFileForFallback:envFileForFallback,saveApiKey:saveApiKey,clearApiKey:clearApiKey,resolveMemoryToken:resolveMemoryToken,saveMemoryToken:saveMemoryToken,clearMemoryToken:clearMemoryToken,keyStatus:keyStatus,clientOptions:clientOptions,preferNewest:preferNewest,sourceLabel:sourceLabel,HOW_TO_SET:HOW_TO_SET};
|
|
@@ -42,4 +42,4 @@
|
|
|
42
42
|
* fonts: [{ name, copyright, url, licence }],
|
|
43
43
|
* missing: [id…]
|
|
44
44
|
* }
|
|
45
|
-
*/function buildCredits(t){const e={};for(const n of Array.isArray(t)?t:[])n&&n.id&&(e[n.id]=n);const n=e.vendor||null,r=e.fonts||null,i=e.licensing||null,s=i?extractNotice(i.text):"Copyright (C) 2026 Niklas Borneklint";return{program:{licence:LICENCE_ID,name:LICENCE_NAME,url:LICENCE_URL,source:SOURCE_URL,copyright:COPYRIGHT,notice:s},documents:DOCUMENTS.map(
|
|
45
|
+
*/function buildCredits(t){const e={};for(const n of Array.isArray(t)?t:[])n&&n.id&&(e[n.id]=n);const n=e.vendor||null,r=e.fonts||null,i=e.licensing||null,s=i?extractNotice(i.text):"Copyright (C) 2026 Niklas Borneklint";return{program:{licence:LICENCE_ID,name:LICENCE_NAME,url:LICENCE_URL,source:SOURCE_URL,copyright:COPYRIGHT,notice:s},documents:DOCUMENTS.map(t=>({id:t.id,title:t.title,applies:t.applies,found:Boolean(e[t.id]),path:e[t.id]?e[t.id].path:null})),code:n?parseAttributions(n.text):[],fonts:r?parseFonts(r.text):[],missing:DOCUMENTS.filter(t=>!e[t.id]).map(t=>t.id)}}function extractNotice(t){const e=String(t||""),n=e.indexOf("## Notice to apply to the program");if(-1===n)return"Copyright (C) 2026 Niklas Borneklint";const r=/```([\s\S]*?)```/.exec(e.slice(n));return r&&r[1].trim()||"Copyright (C) 2026 Niklas Borneklint"}function creditsFromDisk(t){const e=[];for(const n of DOCUMENTS){const r=t&&"function"==typeof t.readText?t.readText(n.file):readDocument(n);r&&e.push(r)}return buildCredits(e)}module.exports={LICENCE_ID:LICENCE_ID,LICENCE_NAME:LICENCE_NAME,LICENCE_URL:LICENCE_URL,SOURCE_URL:SOURCE_URL,COPYRIGHT:COPYRIGHT,DOCUMENTS:DOCUMENTS,buildCredits:buildCredits,creditsFromDisk:creditsFromDisk,parseAttributions:parseAttributions,parseFonts:parseFonts,unwrapBullets:unwrapBullets,readDocument:readDocument,extractNotice:extractNotice};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";function driveConnectUrl(e){return`${String(e||"").replace(/\/+$/,"")}/connect/drive`}async function driveStatus(e){const n=await e.driveToken(),o=Boolean(n&&n.connected),t=n&&n.google_linked;return{connected:o,googleLinked:o||!0===t,googleLinkedKnown:"boolean"==typeof t||o,email:n&&n.email||null}}async function waitForDriveConnected(e,n={}){const o=Number(n.timeoutMs)>0?Number(n.timeoutMs):18e4,t=Number(n.pollMs)>0?Number(n.pollMs):2e3,r=n.signal||null,i=Date.now()+o;for(;;){const n=await driveStatus(e);if(n.connected)return n;if(r&&r.aborted){const e=new Error("cancelled");throw e.name="AbortError",e}if(Date.now()>=i)throw new Error(`timed out after ${Math.round(o/1e3)}s waiting for Google Drive to connect`);await new Promise(
|
|
3
|
+
"use strict";function driveConnectUrl(e){return`${String(e||"").replace(/\/+$/,"")}/connect/drive`}async function driveStatus(e){const n=await e.driveToken(),o=Boolean(n&&n.connected),t=n&&n.google_linked;return{connected:o,googleLinked:o||!0===t,googleLinkedKnown:"boolean"==typeof t||o,email:n&&n.email||null}}async function waitForDriveConnected(e,n={}){const o=Number(n.timeoutMs)>0?Number(n.timeoutMs):18e4,t=Number(n.pollMs)>0?Number(n.pollMs):2e3,r=n.signal||null,i=Date.now()+o;for(;;){const n=await driveStatus(e);if(n.connected)return n;if(r&&r.aborted){const e=new Error("cancelled");throw e.name="AbortError",e}if(Date.now()>=i)throw new Error(`timed out after ${Math.round(o/1e3)}s waiting for Google Drive to connect`);await new Promise(e=>setTimeout(e,t))}}module.exports={driveConnectUrl:driveConnectUrl,driveStatus:driveStatus,waitForDriveConnected:waitForDriveConnected};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const fs=require("node:fs"),path=require("node:path"),credentials=require("./credentials.js"),platform=require("./platform.js"),ENV_FILE=".env",SECRETS_FILE="secrets.env",FOREIGN_SECRET_PREFIXES=Object.freeze(["STRIPE_"]),FOREIGN_SECRET_NAMES=Object.freeze(["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_PRODUCT","STRIPE_PRO_PRICE_ID","STRIPE_S_PRICE_ID","STRIPE_MEMORY_PRICE_ID","PYPI_API_TOKEN","TWINE_PASSWORD","CLAUDE_CODE_OAUTH_TOKEN"]);function isForeignSecret(e){const r=String(null==e?"":e).trim();return!!r&&(!!FOREIGN_SECRET_NAMES.includes(r)||FOREIGN_SECRET_PREFIXES.some((e=>r.startsWith(e))))}const SECRET_FILE_MODE=384,SECRET_DIR_MODE=448,ALIASES=Object.freeze({google:"GEMINI_API_KEY",gemini:"GEMINI_API_KEY","google-ai":"GEMINI_API_KEY",xai:"XAI_API_KEY","x-ai":"XAI_API_KEY",grok:"XAI_API_KEY",huggingface:"HF_TOKEN",together:"TOGETHER_API_KEY","together-ai":"TOGETHER_API_KEY",fireworks:"FIREWORKS_API_KEY","azure-openai":"AZURE_OPENAI_API_KEY","voyage-ai":"VOYAGE_API_KEY"}),ACCOUNT_ENV_VAR="AEGIS_API_KEY";function envFileFor(e){return path.join(e||credentials.aegisHome(),ENV_FILE)}function secretEnvFileFor(e){return path.join(e||credentials.aegisHome(),SECRETS_FILE)}function envVarFor(e){const r=String(e||"").trim().toLowerCase();if(!r)return"";const t=r.startsWith("byok:")?r.slice(5).trim():r;if(!t)return"";if(ALIASES[t])return ALIASES[t];const n=t.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"");return n?`${n}_API_KEY`:""}const ENV_TOKENISH=/^[A-Za-z0-9_+/.-]+$/,ENV_WRAP_MIN_VALUE=32;function foldWrappedEnvValue(e,r,t){let n=t;if(n.startsWith('"')||n.startsWith("'"))return{value:n,i:r};for(;r+1<e.length;){const t=e[r+1],o=t.trim();if(!o||o.startsWith("#")||o.includes("="))break;if(!ENV_TOKENISH.test(o))break;if(!/^[ \t]/.test(t)&&(n.length<ENV_WRAP_MIN_VALUE||!ENV_TOKENISH.test(n)))break;n+=o,r+=1}return{value:n,i:r}}function parseEnvText(e){const r={},t=String(null==e?"":e).split(/\r?\n/);for(let e=0;e<t.length;e++){const n=t[e].trim();if(!n||n.startsWith("#"))continue;const o=n.indexOf("=");if(o<=0)continue;let i=n.slice(0,o).trim();if(i.startsWith("export ")&&(i=i.slice(7).trim()),!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i))continue;const s=foldWrappedEnvValue(t,e,n.slice(o+1).trim());let c=s.value;e=s.i;const E=c.startsWith('"')&&c.endsWith('"')&&c.length>=2,a=c.startsWith("'")&&c.endsWith("'")&&c.length>=2;if(E)c=c.slice(1,-1).replace(/\\(["\\])/g,"$1");else if(a)c=c.slice(1,-1);else{const e=c.indexOf(" #");-1!==e&&(c=c.slice(0,e).trim())}r[i]=c}return r}const ENV_SOURCED=new WeakMap;function sourcedFrom(e){let r=ENV_SOURCED.get(e);return r||(r=new Map,ENV_SOURCED.set(e,r)),r}function isFromEnvFile(e,r,t={}){const n=t.env||process.env,o=ENV_SOURCED.get(n);return!(!o||!o.has(e)||void 0!==r&&o.get(e)!==String(r))}function loadEnvFile(e={}){const r=e.env||process.env,t=e.file||envFileFor(e.dir),n=sourcedFrom(r),o={ok:!1,file:t,loaded:[],kept:[],refused:[],reason:"",loose:!1,mode:0};let i;try{i=fs.readFileSync(t,"utf8")}catch(e){return o.reason=e&&"ENOENT"===e.code?"absent":"unreadable",o}try{const e=fs.statSync(t);o.mode=511&e.mode,o.loose=platform.hasPosixModes()&&0!=(63&e.mode)}catch{}const s=parseEnvText(i);for(const[e,t]of Object.entries(s))isForeignSecret(e)?o.refused.push(e):void 0===r[e]||""===r[e]?(r[e]=t,n.set(e,t),o.loaded.push(e)):o.kept.push(e);return o.ok=!0,o}function loadForeignSecrets(e={}){const r=e.env||process.env,t=e.file||secretEnvFileFor(e.dir),n={ok:!1,file:t,loaded:[],reason:"",mode:0,loose:!1},o=Array.isArray(e.only)&&e.only.length?e.only.filter(isForeignSecret):null;let i;try{i=fs.readFileSync(t,"utf8")}catch(e){return n.reason=e&&"ENOENT"===e.code?"absent":"unreadable",n}try{const e=fs.statSync(t);n.mode=511&e.mode,n.loose=platform.hasPosixModes()&&0!=(63&e.mode)}catch{}const s=parseEnvText(i);for(const[e,t]of Object.entries(s))o&&!o.includes(e)||(r[e]=t,n.loaded.push(e));return n.ok=!0,n}function foreignSecretValue(e,r={}){if(!isForeignSecret(e))return"";const t=r.file||secretEnvFileFor(r.dir);try{const r=parseEnvText(fs.readFileSync(t,"utf8"))[String(e)];return"string"==typeof r?r:""}catch{return""}}function resolveForeignSecret(e,r={}){if(!isForeignSecret(e))return"";const t=r.env||process.env,n=t&&t[e];if("string"==typeof n&&n.trim())return n.trim();const o=foreignSecretValue(e,r);if(o&&o.trim())return o.trim();try{const t=parseEnvText(fs.readFileSync(envFileFor(r.dir),"utf8"))[String(e)];return"string"==typeof t?t.trim():""}catch{return""}}function writeSecretFile(e,r){fs.mkdirSync(path.dirname(e),{recursive:!0,mode:SECRET_DIR_MODE});const t=`${e}.tmp-${process.pid}-${Date.now()}`;fs.writeFileSync(t,r,{mode:SECRET_FILE_MODE}),fs.renameSync(t,e),fs.chmodSync(e,SECRET_FILE_MODE)}function setForeignSecret(e,r,t={}){const n=t.file||secretEnvFileFor(t.dir),o={ok:!1,file:n,name:String(e||""),changed:!1,created:!1,replaced:!1,mode:0,tightened:!1,error:""};if(!isWritableName(e))return o.error=`refusing to write "${e}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,o;if(!isForeignSecret(e))return o.error=`refusing to write ${e} to ${SECRETS_FILE} — it is a host credential, not a foreign secret; use setEnvValue (${ENV_FILE}) instead`,o;const i=String(null==r?"":r).trim();if(!i)return o.error=`refusing to write an empty ${e}`,o;if(/[\r\n]/.test(String(r)))return o.error=`refusing to write ${e} — the value contains a line break`,o;let s="",c=0;o.created=!0;try{s=fs.readFileSync(n,"utf8"),o.created=!1;try{c=511&fs.statSync(n).mode}catch{}}catch(e){if(e&&"ENOENT"!==e.code)return o.error=`could not read ${n}: ${e.code||e.message}`,o}const E=String(s).replace(/\r\n/g,"\n");if(!o.created&&parseEnvText(E)[e]===i)return o.ok=!0,o.changed=!1,o.replaced=!0,o.mode=c||SECRET_FILE_MODE,o;const{text:a,replaced:l}=upsertEnvText(E,e,i);try{writeSecretFile(n,a)}catch(e){return o.error=`could not write ${n}: ${e.code||e.message}`,o}return o.ok=!0,o.changed=!0,o.replaced=l,o.mode=SECRET_FILE_MODE,o.tightened=platform.hasPosixModes()&&!o.created&&0!==c&&0!=(63&c),o}function splitForeignSecrets(e={}){const r=e.env||process.env,t=e.file||envFileFor(e.dir),n=e.secretsFile||secretEnvFileFor(e.dir),o=!0===e.apply,i={ok:!1,moved:[],kept:[],envFile:t,secretsFile:n,apply:o};let s;try{s=fs.readFileSync(t,"utf8")}catch(e){return i.reason=e&&"ENOENT"===e.code?"absent":"unreadable",i}const c=parseEnvText(s),E=Object.keys(c).filter(isForeignSecret).sort();if(!E.length)return i.ok=!0,i;let a="";try{a=fs.readFileSync(n,"utf8")}catch{}const l=parseEnvText(a);for(const e of E)Object.prototype.hasOwnProperty.call(l,e)?i.kept.push(e):(a=upsertEnvText(a,e,c[e]).text,i.moved.push(e));if(o){for(const e of E)s=removeEnvText(s,e).text;i.moved.length&&writeSecretFile(n,a),writeSecretFile(t,s);for(const e of E)r[e]===c[e]&&delete r[e]}else i.moved.length&&(i.secretsFile=n);return i.ok=!0,i}const MIN_CREDENTIAL_LEN=8;function credentialLooksUsable(e){return"string"==typeof e&&e.trim().length>=MIN_CREDENTIAL_LEN}function providerKeyFromEnv(e,r){const t=envVarFor(e);if(!t)return{key:"",env:"",rejected:null};const n=(r||process.env)[t],o="string"==typeof n?n.trim():"";return""===o?{key:"",env:t,rejected:null}:credentialLooksUsable(o)?{key:o,env:t,rejected:null}:{key:"",env:t,rejected:`${t} holds ${o.length} character${1===o.length?"":"s"}, which cannot be a credential`}}function isWritableName(e){return"string"==typeof e&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function quoteEnvValue(e){const r=String(e);return""===r?"":/[\s"'#\\]/.test(r)?`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:r}function upsertEnvText(e,r,t){const n=String(null==e?"":e),o=""===n||n.endsWith("\n"),i=""!==n&&""===n.split("\n").slice(-1)[0],s=""===n?[]:n.split("\n");i&&s.pop();const c=new RegExp(`^(\\s*(?:export\\s+)?)${r}\\s*=`),E=[];let a=!1;for(const e of s){const n=c.exec(e);n?a||(E.push(`${n[1]}${r}=${quoteEnvValue(t)}`),a=!0):E.push(e)}a||E.push(`${r}=${quoteEnvValue(t)}`);let l=E.join("\n");return""!==l&&(o||i)&&(l+="\n"),{text:l,replaced:a}}function setEnvValue(e,r,t={}){const n=t.env||process.env,o=t.file||envFileFor(t.dir),i={ok:!1,file:o,name:String(e||""),changed:!1,created:!1,replaced:!1,mode:0,tightened:!1,error:""};if(!isWritableName(e))return i.error=`refusing to write "${e}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,i;if(isForeignSecret(e))return i.error=`refusing to write ${e} to ${ENV_FILE} — it is a production secret, not a host key; put it in ${SECRETS_FILE} (or use loadForeignSecrets)`,i;const s=String(null==r?"":r).trim();if(!s)return i.error=`refusing to write an empty ${e}`,i;if(/[\r\n]/.test(String(r)))return i.error=`refusing to write ${e} — the value contains a line break`,i;let c="",E=0;i.created=!0;try{c=fs.readFileSync(o,"utf8"),i.created=!1;try{E=511&fs.statSync(o).mode}catch{}}catch(e){if(e&&"ENOENT"!==e.code)return i.error=`could not read ${o}: ${e.code||e.message}`,i}const a=String(c).replace(/\r\n/g,"\n");if(!i.created&&parseEnvText(a)[e]===s)return i.ok=!0,i.changed=!1,i.replaced=!0,i.mode=E||SECRET_FILE_MODE,!1!==t.apply&&(n[e]=s,sourcedFrom(n).set(e,s)),i;const{text:l,replaced:d}=upsertEnvText(a,e,s),u=`${o}.tmp-${process.pid}`;try{fs.mkdirSync(path.dirname(o),{recursive:!0,mode:SECRET_DIR_MODE}),fs.writeFileSync(u,l,{encoding:"utf8",mode:SECRET_FILE_MODE}),fs.chmodSync(u,SECRET_FILE_MODE),fs.renameSync(u,o)}catch(e){try{fs.unlinkSync(u)}catch{}return i.error=`could not write ${o}: ${e.code||e.message}`,i}return i.ok=!0,i.changed=!0,i.replaced=d,i.mode=SECRET_FILE_MODE,i.tightened=platform.hasPosixModes()&&!i.created&&0!==E&&0!=(63&E),!1!==t.apply&&(n[e]=s,sourcedFrom(n).set(e,s)),i}function removeEnvText(e,r){const t=String(null==e?"":e),n=""===t||t.endsWith("\n"),o=""!==t&&""===t.split("\n").slice(-1)[0],i=""===t?[]:t.split("\n");o&&i.pop();const s=new RegExp(`^(\\s*(?:export\\s+)?)${r}\\s*=`),c=[];let E=0;for(const e of i)s.test(e)?E+=1:c.push(e);let a=c.join("\n");return""!==a&&(n||o)&&(a+="\n"),{text:a,removed:E,changed:E>0}}function clearEnvValue(e,r={}){const t=r.env||process.env,n=r.file||envFileFor(r.dir),o={ok:!1,file:n,name:String(e||""),changed:!1,removed:0,mode:0,error:""};if(!isWritableName(e))return o.error=`refusing to clear "${e}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,o;let i="",s=!1,c=0;try{i=fs.readFileSync(n,"utf8");try{c=511&fs.statSync(n).mode}catch{}}catch(e){if(!e||"ENOENT"!==e.code)return o.error=`could not read ${n}: ${e.code||e.message}`,o;s=!0}const{text:E,removed:a,changed:l}=s?{text:"",removed:0,changed:!1}:removeEnvText(i,e);if(!l)return o.ok=!0,o.mode=c||SECRET_FILE_MODE,!1!==r.apply&&delete t[String(e)],o;const d=`${n}.tmp-${process.pid}`;try{fs.mkdirSync(path.dirname(n),{recursive:!0,mode:SECRET_DIR_MODE}),fs.writeFileSync(d,E,{encoding:"utf8",mode:SECRET_FILE_MODE}),fs.chmodSync(d,SECRET_FILE_MODE),fs.renameSync(d,n)}catch(e){try{fs.unlinkSync(d)}catch{}return o.error=`could not write ${n}: ${e.code||e.message}`,o}return o.ok=!0,o.changed=!0,o.removed=a,o.mode=SECRET_FILE_MODE,!1!==r.apply&&delete t[String(e)],o}function keyStatus(e,r={}){const t=r.env||process.env,n=r.file||envFileFor(r.dir),o=String(e||""),i={name:o,present:!1,inFile:!1,source:"none"};if(!isWritableName(o))return i;const s=t[o],c="string"==typeof s&&""!==s.trim();let E=!1;try{const e=parseEnvText(fs.readFileSync(n,"utf8"));E="string"==typeof e[o]&&""!==e[o].trim()}catch{}return i.present=c||E,i.inFile=E,i.source=c&&E?"both":c?"shell":E?"file":"none",i}function keyForModelId(e,r){const t=String(null==e?"":e).trim();if("pro"===String(r||"").toLowerCase())return{env:"CLAUDE_CODE_OAUTH_TOKEN",provider:"",vendor:"",pooled:!1,foreign:!0};if(("byok"===String(r||"").toLowerCase()||t.includes(":"))&&t.includes(":")){const e=t.slice(0,t.indexOf(":")).trim();return{env:envVarFor(e),provider:e,vendor:e,pooled:!1}}return{env:"AEGIS_API_KEY",provider:"",vendor:providerForModelId(t,r),pooled:!0}}const VENDOR_SLUGS=Object.freeze(["openai","anthropic","deepseek","google","gemini","groq","mistral","openrouter","together","together-ai","xai","x-ai","grok","huggingface","fireworks","voyage-ai","azure-openai"]),VENDOR_COMPOUNDS=Object.freeze(VENDOR_SLUGS.filter((e=>e.includes("-"))).sort(((e,r)=>r.length-e.length)));function providerForModelId(e,r){const t=String(null==e?"":e).trim().toLowerCase();if(!t)return"";if(t.includes(":"))return t.slice(0,t.indexOf(":")).trim();for(const e of VENDOR_COMPOUNDS)if(t===e||t.startsWith(e+"-"))return e;const n=t.split("-")[0];return VENDOR_SLUGS.includes(n)?n:""}module.exports={ENV_FILE:ENV_FILE,ALIASES:ALIASES,ACCOUNT_ENV_VAR:"AEGIS_API_KEY",SECRET_FILE_MODE:SECRET_FILE_MODE,envFileFor:envFileFor,envVarFor:envVarFor,parseEnvText:parseEnvText,loadEnvFile:loadEnvFile,isFromEnvFile:isFromEnvFile,providerKeyFromEnv:providerKeyFromEnv,MIN_CREDENTIAL_LEN:MIN_CREDENTIAL_LEN,credentialLooksUsable:credentialLooksUsable,providerForModelId:providerForModelId,VENDOR_SLUGS:VENDOR_SLUGS,isWritableName:isWritableName,quoteEnvValue:quoteEnvValue,upsertEnvText:upsertEnvText,removeEnvText:removeEnvText,setEnvValue:setEnvValue,clearEnvValue:clearEnvValue,keyStatus:keyStatus,keyForModelId:keyForModelId,SECRETS_FILE:SECRETS_FILE,FOREIGN_SECRET_NAMES:FOREIGN_SECRET_NAMES,FOREIGN_SECRET_PREFIXES:FOREIGN_SECRET_PREFIXES,isForeignSecret:isForeignSecret,secretEnvFileFor:secretEnvFileFor,loadForeignSecrets:loadForeignSecrets,foreignSecretValue:foreignSecretValue,resolveForeignSecret:resolveForeignSecret,setForeignSecret:setForeignSecret,splitForeignSecrets:splitForeignSecrets};
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),credentials=require("./credentials.js"),platform=require("./platform.js"),ENV_FILE=".env",SECRETS_FILE="secrets.env",FOREIGN_SECRET_PREFIXES=Object.freeze(["STRIPE_"]),FOREIGN_SECRET_NAMES=Object.freeze(["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_PRODUCT","STRIPE_PRO_PRICE_ID","STRIPE_S_PRICE_ID","STRIPE_MEMORY_PRICE_ID","PYPI_API_TOKEN","TWINE_PASSWORD","CLAUDE_CODE_OAUTH_TOKEN"]);function isForeignSecret(e){const r=String(null==e?"":e).trim();return!!r&&(!!FOREIGN_SECRET_NAMES.includes(r)||FOREIGN_SECRET_PREFIXES.some(e=>r.startsWith(e)))}const SECRET_FILE_MODE=384,SECRET_DIR_MODE=448,ALIASES=Object.freeze({google:"GEMINI_API_KEY",gemini:"GEMINI_API_KEY","google-ai":"GEMINI_API_KEY",xai:"XAI_API_KEY","x-ai":"XAI_API_KEY",grok:"XAI_API_KEY",huggingface:"HF_TOKEN",together:"TOGETHER_API_KEY","together-ai":"TOGETHER_API_KEY",fireworks:"FIREWORKS_API_KEY","azure-openai":"AZURE_OPENAI_API_KEY","voyage-ai":"VOYAGE_API_KEY"}),ACCOUNT_ENV_VAR="AEGIS_API_KEY";function envFileFor(e){return path.join(e||credentials.aegisHome(),".env")}function secretEnvFileFor(e){return path.join(e||credentials.aegisHome(),SECRETS_FILE)}function envVarFor(e){const r=String(e||"").trim().toLowerCase();if(!r)return"";const t=r.startsWith("byok:")?r.slice(5).trim():r;if(!t)return"";if(ALIASES[t])return ALIASES[t];const n=t.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"");return n?`${n}_API_KEY`:""}const ENV_TOKENISH=/^[A-Za-z0-9_+/.-]+$/,ENV_WRAP_MIN_VALUE=32;function foldWrappedEnvValue(e,r,t){let n=t;if(n.startsWith('"')||n.startsWith("'"))return{value:n,i:r};for(;r+1<e.length;){const t=e[r+1],o=t.trim();if(!o||o.startsWith("#")||o.includes("="))break;if(!ENV_TOKENISH.test(o))break;if(!/^[ \t]/.test(t)&&(n.length<32||!ENV_TOKENISH.test(n)))break;n+=o,r+=1}return{value:n,i:r}}function parseEnvText(e){const r={},t=String(null==e?"":e).split(/\r?\n/);for(let e=0;e<t.length;e++){const n=t[e].trim();if(!n||n.startsWith("#"))continue;const o=n.indexOf("=");if(o<=0)continue;let i=n.slice(0,o).trim();if(i.startsWith("export ")&&(i=i.slice(7).trim()),!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i))continue;const s=foldWrappedEnvValue(t,e,n.slice(o+1).trim());let c=s.value;e=s.i;const a=c.startsWith('"')&&c.endsWith('"')&&c.length>=2,l=c.startsWith("'")&&c.endsWith("'")&&c.length>=2;if(a)c=c.slice(1,-1).replace(/\\(["\\])/g,"$1");else if(l)c=c.slice(1,-1);else{const e=c.indexOf(" #");-1!==e&&(c=c.slice(0,e).trim())}r[i]=c}return r}const ENV_SOURCED=new WeakMap;function sourcedFrom(e){let r=ENV_SOURCED.get(e);return r||(r=new Map,ENV_SOURCED.set(e,r)),r}function isFromEnvFile(e,r,t={}){const n=t.env||process.env,o=ENV_SOURCED.get(n);return!(!o||!o.has(e)||void 0!==r&&o.get(e)!==String(r))}function loadEnvFile(e={}){const r=e.env||process.env,t=e.file||envFileFor(e.dir),n=sourcedFrom(r),o={ok:!1,file:t,loaded:[],kept:[],refused:[],reason:"",loose:!1,mode:0};let i;try{i=fs.readFileSync(t,"utf8")}catch(e){return o.reason=e&&"ENOENT"===e.code?"absent":"unreadable",o}try{const e=fs.statSync(t);o.mode=511&e.mode,o.loose=platform.hasPosixModes()&&!!(63&e.mode)}catch{}const s=parseEnvText(i);for(const[e,t]of Object.entries(s))isForeignSecret(e)?o.refused.push(e):void 0===r[e]||""===r[e]?(r[e]=t,n.set(e,t),o.loaded.push(e)):o.kept.push(e);return o.ok=!0,o}function loadForeignSecrets(e={}){const r=e.env||process.env,t=e.file||secretEnvFileFor(e.dir),n={ok:!1,file:t,loaded:[],reason:"",mode:0,loose:!1},o=Array.isArray(e.only)&&e.only.length?e.only.filter(isForeignSecret):null;let i;try{i=fs.readFileSync(t,"utf8")}catch(e){return n.reason=e&&"ENOENT"===e.code?"absent":"unreadable",n}try{const e=fs.statSync(t);n.mode=511&e.mode,n.loose=platform.hasPosixModes()&&!!(63&e.mode)}catch{}const s=parseEnvText(i);for(const[e,t]of Object.entries(s))o&&!o.includes(e)||(r[e]=t,n.loaded.push(e));return n.ok=!0,n}function foreignSecretValue(e,r={}){if(!isForeignSecret(e))return"";const t=r.file||secretEnvFileFor(r.dir);try{const r=parseEnvText(fs.readFileSync(t,"utf8"))[String(e)];return"string"==typeof r?r:""}catch{return""}}function resolveForeignSecret(e,r={}){if(!isForeignSecret(e))return"";const t=r.env||process.env,n=t&&t[e];if("string"==typeof n&&n.trim())return n.trim();const o=foreignSecretValue(e,r);if(o&&o.trim())return o.trim();try{const t=parseEnvText(fs.readFileSync(envFileFor(r.dir),"utf8"))[String(e)];return"string"==typeof t?t.trim():""}catch{return""}}function writeSecretFile(e,r){fs.mkdirSync(path.dirname(e),{recursive:!0,mode:448});const t=`${e}.tmp-${process.pid}-${Date.now()}`;fs.writeFileSync(t,r,{mode:384}),fs.renameSync(t,e),fs.chmodSync(e,384)}function setForeignSecret(e,r,t={}){const n=t.file||secretEnvFileFor(t.dir),o={ok:!1,file:n,name:String(e||""),changed:!1,created:!1,replaced:!1,mode:0,tightened:!1,error:""};if(!isWritableName(e))return o.error=`refusing to write "${e}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,o;if(!isForeignSecret(e))return o.error=`refusing to write ${e} to ${SECRETS_FILE} — it is a host credential, not a foreign secret; use setEnvValue (.env) instead`,o;const i=String(null==r?"":r).trim();if(!i)return o.error=`refusing to write an empty ${e}`,o;if(/[\r\n]/.test(String(r)))return o.error=`refusing to write ${e} — the value contains a line break`,o;let s="",c=0;o.created=!0;try{s=fs.readFileSync(n,"utf8"),o.created=!1;try{c=511&fs.statSync(n).mode}catch{}}catch(e){if(e&&"ENOENT"!==e.code)return o.error=`could not read ${n}: ${e.code||e.message}`,o}const a=String(s).replace(/\r\n/g,"\n");if(!o.created&&parseEnvText(a)[e]===i)return o.ok=!0,o.changed=!1,o.replaced=!0,o.mode=c||384,o;const{text:l,replaced:d}=upsertEnvText(a,e,i);try{writeSecretFile(n,l)}catch(e){return o.error=`could not write ${n}: ${e.code||e.message}`,o}return o.ok=!0,o.changed=!0,o.replaced=d,o.mode=384,o.tightened=platform.hasPosixModes()&&!o.created&&0!==c&&!!(63&c),o}function splitForeignSecrets(e={}){const r=e.env||process.env,t=e.file||envFileFor(e.dir),n=e.secretsFile||secretEnvFileFor(e.dir),o=!0===e.apply,i={ok:!1,moved:[],kept:[],envFile:t,secretsFile:n,apply:o};let s;try{s=fs.readFileSync(t,"utf8")}catch(e){return i.reason=e&&"ENOENT"===e.code?"absent":"unreadable",i}const c=parseEnvText(s),a=Object.keys(c).filter(isForeignSecret).sort();if(!a.length)return i.ok=!0,i;let l="";try{l=fs.readFileSync(n,"utf8")}catch{}const d=parseEnvText(l);for(const e of a)Object.prototype.hasOwnProperty.call(d,e)?i.kept.push(e):(l=upsertEnvText(l,e,c[e]).text,i.moved.push(e));if(o){for(const e of a)s=removeEnvText(s,e).text;i.moved.length&&writeSecretFile(n,l),writeSecretFile(t,s);for(const e of a)r[e]===c[e]&&delete r[e]}else i.moved.length&&(i.secretsFile=n);return i.ok=!0,i}const MIN_CREDENTIAL_LEN=8;function credentialLooksUsable(e){return"string"==typeof e&&e.trim().length>=8}function providerKeyFromEnv(e,r){const t=envVarFor(e);if(!t)return{key:"",env:"",rejected:null};const n=(r||process.env)[t],o="string"==typeof n?n.trim():"";return""===o?{key:"",env:t,rejected:null}:credentialLooksUsable(o)?{key:o,env:t,rejected:null}:{key:"",env:t,rejected:`${t} holds ${o.length} character${1===o.length?"":"s"}, which cannot be a credential`}}function isWritableName(e){return"string"==typeof e&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function quoteEnvValue(e){const r=String(e);return""===r?"":/[\s"'#\\]/.test(r)?`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:r}function upsertEnvText(e,r,t){const n=String(null==e?"":e),o=""===n||n.endsWith("\n"),i=""!==n&&""===n.split("\n").slice(-1)[0],s=""===n?[]:n.split("\n");i&&s.pop();const c=new RegExp(`^(\\s*(?:export\\s+)?)${r}\\s*=`),a=[];let l=!1;for(const e of s){const n=c.exec(e);n?l||(a.push(`${n[1]}${r}=${quoteEnvValue(t)}`),l=!0):a.push(e)}l||a.push(`${r}=${quoteEnvValue(t)}`);let d=a.join("\n");return""!==d&&(o||i)&&(d+="\n"),{text:d,replaced:l}}function setEnvValue(e,r,t={}){const n=t.env||process.env,o=t.file||envFileFor(t.dir),i={ok:!1,file:o,name:String(e||""),changed:!1,created:!1,replaced:!1,mode:0,tightened:!1,error:""};if(!isWritableName(e))return i.error=`refusing to write "${e}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,i;if(isForeignSecret(e))return i.error=`refusing to write ${e} to .env — it is a production secret, not a host key; put it in ${SECRETS_FILE} (or use loadForeignSecrets)`,i;const s=String(null==r?"":r).trim();if(!s)return i.error=`refusing to write an empty ${e}`,i;if(/[\r\n]/.test(String(r)))return i.error=`refusing to write ${e} — the value contains a line break`,i;let c="",a=0;i.created=!0;try{c=fs.readFileSync(o,"utf8"),i.created=!1;try{a=511&fs.statSync(o).mode}catch{}}catch(e){if(e&&"ENOENT"!==e.code)return i.error=`could not read ${o}: ${e.code||e.message}`,i}const l=String(c).replace(/\r\n/g,"\n");if(!i.created&&parseEnvText(l)[e]===s)return i.ok=!0,i.changed=!1,i.replaced=!0,i.mode=a||384,!1!==t.apply&&(n[e]=s,sourcedFrom(n).set(e,s)),i;const{text:d,replaced:E}=upsertEnvText(l,e,s),u=`${o}.tmp-${process.pid}`;try{fs.mkdirSync(path.dirname(o),{recursive:!0,mode:448}),fs.writeFileSync(u,d,{encoding:"utf8",mode:384}),fs.chmodSync(u,384),fs.renameSync(u,o)}catch(e){try{fs.unlinkSync(u)}catch{}return i.error=`could not write ${o}: ${e.code||e.message}`,i}return i.ok=!0,i.changed=!0,i.replaced=E,i.mode=384,i.tightened=platform.hasPosixModes()&&!i.created&&0!==a&&!!(63&a),!1!==t.apply&&(n[e]=s,sourcedFrom(n).set(e,s)),i}function removeEnvText(e,r){const t=String(null==e?"":e),n=""===t||t.endsWith("\n"),o=""!==t&&""===t.split("\n").slice(-1)[0],i=""===t?[]:t.split("\n");o&&i.pop();const s=new RegExp(`^(\\s*(?:export\\s+)?)${r}\\s*=`),c=[];let a=0;for(const e of i)s.test(e)?a+=1:c.push(e);let l=c.join("\n");return""!==l&&(n||o)&&(l+="\n"),{text:l,removed:a,changed:a>0}}function clearEnvValue(e,r={}){const t=r.env||process.env,n=r.file||envFileFor(r.dir),o={ok:!1,file:n,name:String(e||""),changed:!1,removed:0,mode:0,error:""};if(!isWritableName(e))return o.error=`refusing to clear "${e}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,o;let i="",s=!1,c=0;try{i=fs.readFileSync(n,"utf8");try{c=511&fs.statSync(n).mode}catch{}}catch(e){if(!e||"ENOENT"!==e.code)return o.error=`could not read ${n}: ${e.code||e.message}`,o;s=!0}const{text:a,removed:l,changed:d}=s?{text:"",removed:0,changed:!1}:removeEnvText(i,e);if(!d)return o.ok=!0,o.mode=c||384,!1!==r.apply&&delete t[String(e)],o;const E=`${n}.tmp-${process.pid}`;try{fs.mkdirSync(path.dirname(n),{recursive:!0,mode:448}),fs.writeFileSync(E,a,{encoding:"utf8",mode:384}),fs.chmodSync(E,384),fs.renameSync(E,n)}catch(e){try{fs.unlinkSync(E)}catch{}return o.error=`could not write ${n}: ${e.code||e.message}`,o}return o.ok=!0,o.changed=!0,o.removed=l,o.mode=384,!1!==r.apply&&delete t[String(e)],o}function keyStatus(e,r={}){const t=r.env||process.env,n=r.file||envFileFor(r.dir),o=String(e||""),i={name:o,present:!1,inFile:!1,source:"none"};if(!isWritableName(o))return i;const s=t[o],c="string"==typeof s&&""!==s.trim();let a=!1;try{const e=parseEnvText(fs.readFileSync(n,"utf8"));a="string"==typeof e[o]&&""!==e[o].trim()}catch{}return i.present=c||a,i.inFile=a,i.source=c&&a?"both":c?"shell":a?"file":"none",i}function keyForModelId(e,r){const t=String(null==e?"":e).trim();if("pro"===String(r||"").toLowerCase())return{env:"CLAUDE_CODE_OAUTH_TOKEN",provider:"",vendor:"",pooled:!1,foreign:!0};if(("byok"===String(r||"").toLowerCase()||t.includes(":"))&&t.includes(":")){const e=t.slice(0,t.indexOf(":")).trim();return{env:envVarFor(e),provider:e,vendor:e,pooled:!1}}return{env:"AEGIS_API_KEY",provider:"",vendor:providerForModelId(t,r),pooled:!0}}const VENDOR_SLUGS=Object.freeze(["openai","anthropic","deepseek","google","gemini","groq","mistral","openrouter","together","together-ai","xai","x-ai","grok","huggingface","fireworks","voyage-ai","azure-openai"]),VENDOR_COMPOUNDS=Object.freeze(VENDOR_SLUGS.filter(e=>e.includes("-")).sort((e,r)=>r.length-e.length));function providerForModelId(e,r){const t=String(null==e?"":e).trim().toLowerCase();if(!t)return"";if(t.includes(":"))return t.slice(0,t.indexOf(":")).trim();for(const e of VENDOR_COMPOUNDS)if(t===e||t.startsWith(e+"-"))return e;const n=t.split("-")[0];return VENDOR_SLUGS.includes(n)?n:""}module.exports={ENV_FILE:".env",ALIASES:ALIASES,ACCOUNT_ENV_VAR:"AEGIS_API_KEY",SECRET_FILE_MODE:384,envFileFor:envFileFor,envVarFor:envVarFor,parseEnvText:parseEnvText,loadEnvFile:loadEnvFile,isFromEnvFile:isFromEnvFile,providerKeyFromEnv:providerKeyFromEnv,MIN_CREDENTIAL_LEN:8,credentialLooksUsable:credentialLooksUsable,providerForModelId:providerForModelId,VENDOR_SLUGS:VENDOR_SLUGS,isWritableName:isWritableName,quoteEnvValue:quoteEnvValue,upsertEnvText:upsertEnvText,removeEnvText:removeEnvText,setEnvValue:setEnvValue,clearEnvValue:clearEnvValue,keyStatus:keyStatus,keyForModelId:keyForModelId,SECRETS_FILE:SECRETS_FILE,FOREIGN_SECRET_NAMES:FOREIGN_SECRET_NAMES,FOREIGN_SECRET_PREFIXES:FOREIGN_SECRET_PREFIXES,isForeignSecret:isForeignSecret,secretEnvFileFor:secretEnvFileFor,loadForeignSecrets:loadForeignSecrets,foreignSecretValue:foreignSecretValue,resolveForeignSecret:resolveForeignSecret,setForeignSecret:setForeignSecret,splitForeignSecrets:splitForeignSecrets};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const crypto=require("node:crypto"),fs=require("node:fs"),{signatureFromMedians:signatureFromMedians,MIN_STROKES:TOUCH_MIN_STROKES}=require("./touch.js"),FP_VERSION=4,FP_ALGO="sha256",FP_PREFIX="φ_",KEY_FP_LENGTH=12,SIG_LENGTH=16,ATTEST_LENGTH=32,LEAK_HEX_RUN=24,MAX_LABEL=40,MAX_FIELD=64,MAX_TOOLS=64,MAX_OBSERVATIONS=4096,MAX_DEPTH=8,CODE_LEN=SIG_LENGTH,MAX_CODE_FILES=4096,MAX_PATH=200,ATTESTED_FIELDS_V1=Object.freeze(["v","algo","keyFingerprint","label","account","model","tools","behaviour","behaviourSamples","createdAt"]),BEHAVIOUR_PURPOSE="aegiscode-behaviour-v2",AI_PURPOSE="aegiscode-ai-v1",ATTESTED_FIELDS_V2=Object.freeze(["v","algo","keyFingerprint","label","account","model","tools","behaviour","behaviourSamples","touch","touchSamples","createdAt"]),ATTESTED_FIELDS_V3=Object.freeze(["v","algo","keyFingerprint","label","account","model","tools","behaviour","behaviourSamples","touch","touchSamples","code","codeFiles","codeDirty","createdAt"]),ATTESTED_FIELDS_V4=Object.freeze(["v","algo","keyFingerprint","label","account","model","tools","behaviour","behaviourSamples","touch","touchSamples","code","codeFiles","codeDirty","aiKey","aiModel","ai","aiSamples","createdAt"]),ATTESTED_FIELDS=ATTESTED_FIELDS_V4,ATTESTED_FIELDS_BY_VERSION=Object.freeze({1:ATTESTED_FIELDS_V1,2:ATTESTED_FIELDS_V2,3:ATTESTED_FIELDS_V3,4:ATTESTED_FIELDS_V4});function attestedFieldsFor(e){return"number"==typeof e&&Number.isInteger(e)&&Object.prototype.hasOwnProperty.call(ATTESTED_FIELDS_BY_VERSION,e)?ATTESTED_FIELDS_BY_VERSION[e]:null}function normalise(e){return null==e?"":String(e).trim().replace(/\s+/g," ").toLowerCase()}function canonical(e,t=0){if(t>MAX_DEPTH)return'"[depth]"';if(null==e)return"null";const r=typeof e;return"number"===r?Number.isFinite(e)?String(e):"null":"boolean"===r?e?"true":"false":"string"===r?JSON.stringify(normalise(e)):"function"===r||"symbol"===r||"bigint"===r?"null":Array.isArray(e)?"["+e.map((e=>canonical(e,t+1))).join(",")+"]":"object"===r?"{"+Object.keys(e).filter((t=>void 0!==e[t]&&"function"!=typeof e[t])).sort().map((r=>JSON.stringify(r)+":"+canonical(e[r],t+1))).join(",")+"}":"null"}function digest(e,t){return crypto.createHash(FP_ALGO).update(e+"\n"+t,"utf8").digest("hex")}function safeLabel(e,t=MAX_LABEL){if(null==e)return"";const r=String(e).replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return r?r.length>t?r.slice(0,t):r:""}function longHexRun(e,t=LEAK_HEX_RUN){return new RegExp(`[0-9a-fA-F]{${t},}`).test(String(e))}const HEX_ATTESTATION=new RegExp(`^[0-9a-f]{${ATTEST_LENGTH}}$`);function isFingerprintShape(e){return new RegExp(`^[0-9a-f]{${KEY_FP_LENGTH}}$`).test(String(e||""))}function assertNoLeak(e,t,r){const n=[t,r].map((e=>null==e?"":String(e))).filter(Boolean);for(const[t,r]of Object.entries(e)){if(null==r)continue;const e=Array.isArray(r)?r.join("\0"):String(r);for(const r of n)if(e.includes(r))throw new Error(`fingerprint: field "${t}" would carry the secret verbatim`);if("attestation"!==t){if(longHexRun(e))throw new Error(`fingerprint: field "${t}" carries a long hex run (possible key leak)`)}else if(!HEX_ATTESTATION.test(e))throw new Error("fingerprint: attestation must be 32 lowercase hex characters")}return!0}function assertInputsClean(e,t,r){const n=[t,r].map((e=>null==e?"":String(e))).filter(Boolean);if(!n.length)return!0;for(const t of["label","account","model","tools","aiModel"]){const r=e[t];if(null==r)continue;const i=Array.isArray(r)?r.join("\0"):String(r);if(n.some((e=>i.includes(e))))throw new Error(`fingerprint: input "${t}" would carry the secret verbatim`);if(longHexRun(i))throw new Error(`fingerprint: input "${t}" carries a long hex run (possible key leak)`)}return!0}function keyFingerprint(e){if(null==e)return null;const t=String(e).trim();return t?digest("aegiscode-agent-v1",t).slice(0,KEY_FP_LENGTH):null}function observationKey(e){if("string"==typeof e||"number"==typeof e)return normalise(e);if(!e||"object"!=typeof e)return"";const t=[e.tool,e.target,e.outcome,e.model].map((e=>normalise(e))).join("|");return t.replace(/^\|+|\|+$/g,"")?t:""}function countObservations(e){return Array.isArray(e)?e.slice(0,MAX_OBSERVATIONS).filter((e=>""!==observationKey(e))).length:0}function signatureFromObservations(e,t){if(!Array.isArray(e))return null;const r=e.slice(0,MAX_OBSERVATIONS).map(observationKey).filter(Boolean);return r.length?digest(t,Array.from(new Set(r)).sort().join("\n")).slice(0,SIG_LENGTH):null}function behaviouralSignature(e){return signatureFromObservations(e,BEHAVIOUR_PURPOSE)}function aiSignature(e){return signatureFromObservations(e,AI_PURPOSE)}function normaliseTools(e){if(!Array.isArray(e))return Object.freeze([]);const t=new Set;for(const r of e.slice(0,MAX_TOOLS)){const e=normalise("string"==typeof r?r:r&&(r.name||r.id)||"");e&&t.add(e)}return Object.freeze(Array.from(t).sort())}function normaliseCodePath(e){if(null==e)return null;const t=String(e).replace(/\\/g,"/").trim();if(!t)return null;if(t.startsWith("/")||/^[a-zA-Z]:\//.test(t))return null;const r=[];for(const e of t.split("/"))if(""!==e&&"."!==e){if(".."===e)return null;r.push(e)}const n=r.join("/");return n?n.length>MAX_PATH?null:n:null}function codeFileDigest(e,t){const r=normaliseCodePath(e);if(!r)throw new Error(`fingerprint: unusable code path ${JSON.stringify(String(e))}`);const n=Buffer.isBuffer(t)?t:Buffer.from(null==t?"":String(t),"utf8");return crypto.createHash(FP_ALGO).update(`aegiscode-code-v3\0${r}\0`,"utf8").update(n).digest("hex")}function codeDigest(e){if(!Array.isArray(e))return{code:null,codeFiles:0};const t=new Map;for(const r of e){if(!r||"object"!=typeof r)continue;const e=normaliseCodePath(r.path);e&&t.set(e,{path:e,content:r.content})}const r=Array.from(t.keys()).sort();if(!r.length)return{code:null,codeFiles:0};if(r.length>MAX_CODE_FILES)throw new Error(`fingerprint: ${r.length} code files exceeds MAX_CODE_FILES (${MAX_CODE_FILES}); hash a subtree rather than silently attesting a prefix of one`);let n=digest("aegiscode-code-v3-root",String(r.length));for(const e of r)n=digest("aegiscode-code-v3-fold",`${n}\n${e}\n${codeFileDigest(e,t.get(e).content)}`);return{code:n.slice(0,CODE_LEN),codeFiles:r.length}}function codeAxisFrom(e,t){const{code:r,codeFiles:n}=codeDigest(e);return{code:r,codeFiles:n,codeDirty:r&&"boolean"==typeof t?t:null}}function aiAxisFrom(e={}){const{secret:t,model:r,observations:n}=e||{},i=keyFingerprint(t),o=aiSignature(n);return{aiKey:i,aiModel:safeLabel(r,MAX_FIELD)||null,ai:o,aiSamples:o?countObservations(n):0}}function attestationBody(e){const t=attestedFieldsFor(e&&e.v);if(!t)throw new Error(`fingerprint: cannot attest version ${e&&e.v}`);const r={};for(const n of t){const t=e[n];r[n]=void 0===t?null:t}return canonical(r)}function attest(e,t){if(!t)throw new Error("fingerprint: a secret is required to attest a record");return crypto.createHmac(FP_ALGO,String(t)).update(attestationBody(e),"utf8").digest("hex").slice(0,ATTEST_LENGTH)}function isoTs(e){if(null==e)return(new Date).toISOString();const t=e instanceof Date?e:new Date(e);if(Number.isNaN(t.getTime()))throw new Error("fingerprint: createdAt is not a valid date");return t.toISOString()}function touchSignatureFrom(e){if(!e||"object"!=typeof e)return{signature:null,samples:0};const t=Number(e.samples)||0,r=signatureFromMedians(e.medians,t);return{signature:r,samples:r?t:0}}function mint(e={}){const{secret:t,label:r,account:n,model:i,tools:o,observations:a,touch:s,code:l,codeDirty:u,aiSecret:c,aiModel:f,aiObservations:d,createdAt:E}=e,S=keyFingerprint(t);if(!S)throw new Error("fingerprint: a secret (API key or device seed) is required to mint φ(α)");assertInputsClean({label:r,account:n,model:i,tools:o,aiModel:f},t,c);const g=touchSignatureFrom(s),_=codeAxisFrom(l,u),p=aiAxisFrom({secret:c,model:f,observations:d}),F={v:FP_VERSION,algo:FP_ALGO,keyFingerprint:S,label:safeLabel(r,MAX_LABEL),account:safeLabel(n,MAX_FIELD)||null,model:safeLabel(i,MAX_FIELD)||null,tools:normaliseTools(o),behaviour:behaviouralSignature(a),behaviourSamples:countObservations(a),touch:g.signature,touchSamples:g.samples,code:_.code,codeFiles:_.codeFiles,codeDirty:_.codeDirty,aiKey:p.aiKey,aiModel:p.aiModel,ai:p.ai,aiSamples:p.aiSamples,createdAt:isoTs(E)},T={...F,attestation:attest(F,t)};return assertNoLeak(T,t,c),Object.freeze(T)}function id(e){if(!e||!isFingerprintShape(e.keyFingerprint))throw new Error("fingerprint: not a fingerprinted record");return`${FP_PREFIX}${e.keyFingerprint}-${e.behaviour||"unobserved"}`}function sameReason(e){return e&&"object"==typeof e?attestedFieldsFor(e.v)?e.algo!==FP_ALGO?`unsupported algo ${e.algo}`:isFingerprintShape(e.keyFingerprint)?null:"keyFingerprint is malformed":`unsupported version ${e.v}`:"not a record"}function verify(e,t){const r=sameReason(e);if(r)return{ok:!1,reason:r,id:null,credentialMatch:null};const n=t?keyFingerprint(t)===e.keyFingerprint:null;if(!t)return{ok:!1,reason:"no secret supplied — attestation cannot be recomputed",id:id(e),credentialMatch:null};const i=attest(e,t),o=String(e.attestation||""),a=Buffer.from(i,"utf8"),s=Buffer.from(o.padEnd(i.length," ").slice(0,i.length),"utf8");return a.length===s.length&&crypto.timingSafeEqual(a,s)?n?{ok:!0,reason:null,id:id(e),credentialMatch:!0}:{ok:!1,reason:"attestation valid but secret does not match keyFingerprint",id:id(e),credentialMatch:!1}:{ok:!1,reason:"attestation mismatch",id:id(e),credentialMatch:n}}function same(e,t,r="full"){if(!e||!t)return!1;if("credential"===r)return e.keyFingerprint===t.keyFingerprint;if("behaviour"===r)return Boolean(e.behaviour)&&e.behaviour===t.behaviour;if("full"===r)return e.keyFingerprint===t.keyFingerprint&&e.behaviour===t.behaviour;if("ai-credential"===r)return Boolean(e.aiKey)&&e.aiKey===t.aiKey;if("ai"===r)return Boolean(e.ai)&&e.ai===t.ai;if("mind"===r)return Boolean(e.aiKey)&&e.aiKey===t.aiKey&&Boolean(e.ai)&&e.ai===t.ai;throw new Error(`fingerprint: unknown comparison axis "${r}"`)}function describe(e){const t=sameReason(e);if(t)return`φ(?) ${t}`;const r=[`key ${e.keyFingerprint}`,e.behaviour?`behaviour ${e.behaviour}`:"behaviour unobserved",e.behaviourSamples?`${e.behaviourSamples} samples`:null,e.touch?`touch ${e.touch}`:"touch unobserved",e.touchSamples?`${e.touchSamples} strokes`:null,e.code?`code ${e.code}${null===e.codeDirty?"":e.codeDirty?" (dirty)":" (clean)"}`:"code unobserved",e.codeFiles?`${e.codeFiles} files`:null,e.ai&&e.aiKey?`ai ${e.ai} on ${e.aiKey}`:e.ai?`ai ${e.ai} (no key nominated)`:e.aiKey?`ai key ${e.aiKey}, behaviour unobserved`:"ai unobserved",e.aiSamples?`${e.aiSamples} ai turn(s)`:null,e.aiModel?`ran on ${e.aiModel}`:null,e.model?`model ${e.model}`:null,e.tools&&e.tools.length?`tools ${e.tools.length}`:null].filter(Boolean);return`${e.label||"agent"} · ${r.join(" · ")}`}function readAiSecret(e,t){if(t.AEGIS_AI_SECRET)return String(t.AEGIS_AI_SECRET).trim();const r=e.indexOf("--ai-secret-file");return-1!==r&&e[r+1]?fs.readFileSync(e[r+1],"utf8").trim():""}function readSecret(e,t){if(t.AEGIS_FINGERPRINT_SECRET)return String(t.AEGIS_FINGERPRINT_SECRET).trim();const r=e.indexOf("--secret-file");return-1!==r&&e[r+1]?fs.readFileSync(e[r+1],"utf8").trim():""}function flag(e,t,r=null){const n=e.indexOf(t);return-1!==n&&void 0!==e[n+1]?e[n+1]:r}function main(e,t=process.env){const r=readSecret(e,t);if(e.includes("--verify")){const t=flag(e,"--verify");if(!t)throw new Error("fingerprint: --verify needs a record file");const n=verify(JSON.parse(fs.readFileSync(t,"utf8")),r);return process.stdout.write(JSON.stringify(n,null,2)+"\n"),n.ok?0:1}const n=flag(e,"--observations"),i=n?JSON.parse(fs.readFileSync(n,"utf8")):[],o=flag(e,"--touch"),a=o?JSON.parse(fs.readFileSync(o,"utf8")):null,s=flag(e,"--ai-observations"),l=s?JSON.parse(fs.readFileSync(s,"utf8")):null,u=mint({secret:r,label:flag(e,"--label",""),account:flag(e,"--account",""),model:flag(e,"--model",""),tools:(flag(e,"--tools","")||"").split(",").filter(Boolean),observations:i,touch:a,aiSecret:readAiSecret(e,t),aiModel:flag(e,"--ai-model",""),aiObservations:l});return process.stdout.write(JSON.stringify(u,null,2)+"\n"),0}const API={mint:mint,verify:verify,attest:attest,attestationBody:attestationBody,id:id,same:same,describe:describe,keyFingerprint:keyFingerprint,behaviouralSignature:behaviouralSignature,aiSignature:aiSignature,aiAxisFrom:aiAxisFrom,observationKey:observationKey,countObservations:countObservations,normaliseTools:normaliseTools,safeLabel:safeLabel,touchSignatureFrom:touchSignatureFrom,normaliseCodePath:normaliseCodePath,codeFileDigest:codeFileDigest,codeDigest:codeDigest,codeAxisFrom:codeAxisFrom,canonical:canonical,assertNoLeak:assertNoLeak,assertInputsClean:assertInputsClean,longHexRun:longHexRun,isFingerprintShape:isFingerprintShape,attestedFieldsFor:attestedFieldsFor,FP_VERSION:FP_VERSION,FP_ALGO:FP_ALGO,FP_PREFIX:FP_PREFIX,KEY_FP_LENGTH:KEY_FP_LENGTH,SIG_LENGTH:SIG_LENGTH,ATTEST_LENGTH:ATTEST_LENGTH,LEAK_HEX_RUN:LEAK_HEX_RUN,CODE_LEN:CODE_LEN,MAX_CODE_FILES:MAX_CODE_FILES,MAX_PATH:MAX_PATH,BEHAVIOUR_PURPOSE:BEHAVIOUR_PURPOSE,AI_PURPOSE:AI_PURPOSE,ATTESTED_FIELDS:ATTESTED_FIELDS,ATTESTED_FIELDS_V1:ATTESTED_FIELDS_V1,ATTESTED_FIELDS_V2:ATTESTED_FIELDS_V2,ATTESTED_FIELDS_V3:ATTESTED_FIELDS_V3,ATTESTED_FIELDS_V4:ATTESTED_FIELDS_V4,ATTESTED_FIELDS_BY_VERSION:ATTESTED_FIELDS_BY_VERSION,main:main};module.exports=API;
|
|
3
|
+
"use strict";const crypto=require("node:crypto"),fs=require("node:fs"),{signatureFromMedians:signatureFromMedians,MIN_STROKES:TOUCH_MIN_STROKES}=require("./touch.js"),FP_VERSION=4,FP_ALGO="sha256",FP_PREFIX="φ_",KEY_FP_LENGTH=12,SIG_LENGTH=16,ATTEST_LENGTH=32,LEAK_HEX_RUN=24,MAX_LABEL=40,MAX_FIELD=64,MAX_TOOLS=64,MAX_OBSERVATIONS=4096,MAX_DEPTH=8,CODE_LEN=16,MAX_CODE_FILES=4096,MAX_PATH=200,ATTESTED_FIELDS_V1=Object.freeze(["v","algo","keyFingerprint","label","account","model","tools","behaviour","behaviourSamples","createdAt"]),BEHAVIOUR_PURPOSE="aegiscode-behaviour-v2",AI_PURPOSE="aegiscode-ai-v1",ATTESTED_FIELDS_V2=Object.freeze(["v","algo","keyFingerprint","label","account","model","tools","behaviour","behaviourSamples","touch","touchSamples","createdAt"]),ATTESTED_FIELDS_V3=Object.freeze(["v","algo","keyFingerprint","label","account","model","tools","behaviour","behaviourSamples","touch","touchSamples","code","codeFiles","codeDirty","createdAt"]),ATTESTED_FIELDS_V4=Object.freeze(["v","algo","keyFingerprint","label","account","model","tools","behaviour","behaviourSamples","touch","touchSamples","code","codeFiles","codeDirty","aiKey","aiModel","ai","aiSamples","createdAt"]),ATTESTED_FIELDS=ATTESTED_FIELDS_V4,ATTESTED_FIELDS_BY_VERSION=Object.freeze({1:ATTESTED_FIELDS_V1,2:ATTESTED_FIELDS_V2,3:ATTESTED_FIELDS_V3,4:ATTESTED_FIELDS_V4});function attestedFieldsFor(e){return"number"==typeof e&&Number.isInteger(e)&&Object.prototype.hasOwnProperty.call(ATTESTED_FIELDS_BY_VERSION,e)?ATTESTED_FIELDS_BY_VERSION[e]:null}function normalise(e){return null==e?"":String(e).trim().replace(/\s+/g," ").toLowerCase()}function canonical(e,t=0){if(t>8)return'"[depth]"';if(null==e)return"null";const r=typeof e;return"number"===r?Number.isFinite(e)?String(e):"null":"boolean"===r?e?"true":"false":"string"===r?JSON.stringify(normalise(e)):"function"===r||"symbol"===r||"bigint"===r?"null":Array.isArray(e)?"["+e.map(e=>canonical(e,t+1)).join(",")+"]":"object"===r?"{"+Object.keys(e).filter(t=>void 0!==e[t]&&"function"!=typeof e[t]).sort().map(r=>JSON.stringify(r)+":"+canonical(e[r],t+1)).join(",")+"}":"null"}function digest(e,t){return crypto.createHash(FP_ALGO).update(e+"\n"+t,"utf8").digest("hex")}function safeLabel(e,t=40){if(null==e)return"";const r=String(e).replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return r?r.length>t?r.slice(0,t):r:""}function longHexRun(e,t=24){return new RegExp(`[0-9a-fA-F]{${t},}`).test(String(e))}const HEX_ATTESTATION=new RegExp("^[0-9a-f]{32}$");function isFingerprintShape(e){return new RegExp("^[0-9a-f]{12}$").test(String(e||""))}function assertNoLeak(e,t,r){const n=[t,r].map(e=>null==e?"":String(e)).filter(Boolean);for(const[t,r]of Object.entries(e)){if(null==r)continue;const e=Array.isArray(r)?r.join("\0"):String(r);for(const r of n)if(e.includes(r))throw new Error(`fingerprint: field "${t}" would carry the secret verbatim`);if("attestation"!==t){if(longHexRun(e))throw new Error(`fingerprint: field "${t}" carries a long hex run (possible key leak)`)}else if(!HEX_ATTESTATION.test(e))throw new Error("fingerprint: attestation must be 32 lowercase hex characters")}return!0}function assertInputsClean(e,t,r){const n=[t,r].map(e=>null==e?"":String(e)).filter(Boolean);if(!n.length)return!0;for(const t of["label","account","model","tools","aiModel"]){const r=e[t];if(null==r)continue;const i=Array.isArray(r)?r.join("\0"):String(r);if(n.some(e=>i.includes(e)))throw new Error(`fingerprint: input "${t}" would carry the secret verbatim`);if(longHexRun(i))throw new Error(`fingerprint: input "${t}" carries a long hex run (possible key leak)`)}return!0}function keyFingerprint(e){if(null==e)return null;const t=String(e).trim();return t?digest("aegiscode-agent-v1",t).slice(0,12):null}function observationKey(e){if("string"==typeof e||"number"==typeof e)return normalise(e);if(!e||"object"!=typeof e)return"";const t=[e.tool,e.target,e.outcome,e.model].map(e=>normalise(e)).join("|");return t.replace(/^\|+|\|+$/g,"")?t:""}function countObservations(e){return Array.isArray(e)?e.slice(0,4096).filter(e=>""!==observationKey(e)).length:0}function signatureFromObservations(e,t){if(!Array.isArray(e))return null;const r=e.slice(0,4096).map(observationKey).filter(Boolean);return r.length?digest(t,Array.from(new Set(r)).sort().join("\n")).slice(0,16):null}function behaviouralSignature(e){return signatureFromObservations(e,BEHAVIOUR_PURPOSE)}function aiSignature(e){return signatureFromObservations(e,AI_PURPOSE)}function normaliseTools(e){if(!Array.isArray(e))return Object.freeze([]);const t=new Set;for(const r of e.slice(0,64)){const e=normalise("string"==typeof r?r:r&&(r.name||r.id)||"");e&&t.add(e)}return Object.freeze(Array.from(t).sort())}function normaliseCodePath(e){if(null==e)return null;const t=String(e).replace(/\\/g,"/").trim();if(!t)return null;if(t.startsWith("/")||/^[a-zA-Z]:\//.test(t))return null;const r=[];for(const e of t.split("/"))if(""!==e&&"."!==e){if(".."===e)return null;r.push(e)}const n=r.join("/");return n?n.length>200?null:n:null}function codeFileDigest(e,t){const r=normaliseCodePath(e);if(!r)throw new Error(`fingerprint: unusable code path ${JSON.stringify(String(e))}`);const n=Buffer.isBuffer(t)?t:Buffer.from(null==t?"":String(t),"utf8");return crypto.createHash(FP_ALGO).update(`aegiscode-code-v3\0${r}\0`,"utf8").update(n).digest("hex")}function codeDigest(e){if(!Array.isArray(e))return{code:null,codeFiles:0};const t=new Map;for(const r of e){if(!r||"object"!=typeof r)continue;const e=normaliseCodePath(r.path);e&&t.set(e,{path:e,content:r.content})}const r=Array.from(t.keys()).sort();if(!r.length)return{code:null,codeFiles:0};if(r.length>4096)throw new Error(`fingerprint: ${r.length} code files exceeds MAX_CODE_FILES (4096); hash a subtree rather than silently attesting a prefix of one`);let n=digest("aegiscode-code-v3-root",String(r.length));for(const e of r)n=digest("aegiscode-code-v3-fold",`${n}\n${e}\n${codeFileDigest(e,t.get(e).content)}`);return{code:n.slice(0,16),codeFiles:r.length}}function codeAxisFrom(e,t){const{code:r,codeFiles:n}=codeDigest(e);return{code:r,codeFiles:n,codeDirty:r&&"boolean"==typeof t?t:null}}function aiAxisFrom(e={}){const{secret:t,model:r,observations:n}=e||{},i=keyFingerprint(t),o=aiSignature(n);return{aiKey:i,aiModel:safeLabel(r,64)||null,ai:o,aiSamples:o?countObservations(n):0}}function attestationBody(e){const t=attestedFieldsFor(e&&e.v);if(!t)throw new Error(`fingerprint: cannot attest version ${e&&e.v}`);const r={};for(const n of t){const t=e[n];r[n]=void 0===t?null:t}return canonical(r)}function attest(e,t){if(!t)throw new Error("fingerprint: a secret is required to attest a record");return crypto.createHmac(FP_ALGO,String(t)).update(attestationBody(e),"utf8").digest("hex").slice(0,32)}function isoTs(e){if(null==e)return(new Date).toISOString();const t=e instanceof Date?e:new Date(e);if(Number.isNaN(t.getTime()))throw new Error("fingerprint: createdAt is not a valid date");return t.toISOString()}function touchSignatureFrom(e){if(!e||"object"!=typeof e)return{signature:null,samples:0};const t=Number(e.samples)||0,r=signatureFromMedians(e.medians,t);return{signature:r,samples:r?t:0}}function mint(e={}){const{secret:t,label:r,account:n,model:i,tools:o,observations:a,touch:s,code:l,codeDirty:u,aiSecret:c,aiModel:f,aiObservations:d,createdAt:g}=e,S=keyFingerprint(t);if(!S)throw new Error("fingerprint: a secret (API key or device seed) is required to mint φ(α)");assertInputsClean({label:r,account:n,model:i,tools:o,aiModel:f},t,c);const E=touchSignatureFrom(s),p=codeAxisFrom(l,u),m=aiAxisFrom({secret:c,model:f,observations:d}),F={v:4,algo:FP_ALGO,keyFingerprint:S,label:safeLabel(r,40),account:safeLabel(n,64)||null,model:safeLabel(i,64)||null,tools:normaliseTools(o),behaviour:behaviouralSignature(a),behaviourSamples:countObservations(a),touch:E.signature,touchSamples:E.samples,code:p.code,codeFiles:p.codeFiles,codeDirty:p.codeDirty,aiKey:m.aiKey,aiModel:m.aiModel,ai:m.ai,aiSamples:m.aiSamples,createdAt:isoTs(g)},h={...F,attestation:attest(F,t)};return assertNoLeak(h,t,c),Object.freeze(h)}function id(e){if(!e||!isFingerprintShape(e.keyFingerprint))throw new Error("fingerprint: not a fingerprinted record");return`φ_${e.keyFingerprint}-${e.behaviour||"unobserved"}`}function sameReason(e){return e&&"object"==typeof e?attestedFieldsFor(e.v)?e.algo!==FP_ALGO?`unsupported algo ${e.algo}`:isFingerprintShape(e.keyFingerprint)?null:"keyFingerprint is malformed":`unsupported version ${e.v}`:"not a record"}function verify(e,t){const r=sameReason(e);if(r)return{ok:!1,reason:r,id:null,credentialMatch:null};const n=t?keyFingerprint(t)===e.keyFingerprint:null;if(!t)return{ok:!1,reason:"no secret supplied — attestation cannot be recomputed",id:id(e),credentialMatch:null};const i=attest(e,t),o=String(e.attestation||""),a=Buffer.from(i,"utf8"),s=Buffer.from(o.padEnd(i.length," ").slice(0,i.length),"utf8");return a.length===s.length&&crypto.timingSafeEqual(a,s)?n?{ok:!0,reason:null,id:id(e),credentialMatch:!0}:{ok:!1,reason:"attestation valid but secret does not match keyFingerprint",id:id(e),credentialMatch:!1}:{ok:!1,reason:"attestation mismatch",id:id(e),credentialMatch:n}}function same(e,t,r="full"){if(!e||!t)return!1;if("credential"===r)return e.keyFingerprint===t.keyFingerprint;if("behaviour"===r)return Boolean(e.behaviour)&&e.behaviour===t.behaviour;if("full"===r)return e.keyFingerprint===t.keyFingerprint&&e.behaviour===t.behaviour;if("ai-credential"===r)return Boolean(e.aiKey)&&e.aiKey===t.aiKey;if("ai"===r)return Boolean(e.ai)&&e.ai===t.ai;if("mind"===r)return Boolean(e.aiKey)&&e.aiKey===t.aiKey&&Boolean(e.ai)&&e.ai===t.ai;throw new Error(`fingerprint: unknown comparison axis "${r}"`)}function describe(e){const t=sameReason(e);if(t)return`φ(?) ${t}`;const r=[`key ${e.keyFingerprint}`,e.behaviour?`behaviour ${e.behaviour}`:"behaviour unobserved",e.behaviourSamples?`${e.behaviourSamples} samples`:null,e.touch?`touch ${e.touch}`:"touch unobserved",e.touchSamples?`${e.touchSamples} strokes`:null,e.code?`code ${e.code}${null===e.codeDirty?"":e.codeDirty?" (dirty)":" (clean)"}`:"code unobserved",e.codeFiles?`${e.codeFiles} files`:null,e.ai&&e.aiKey?`ai ${e.ai} on ${e.aiKey}`:e.ai?`ai ${e.ai} (no key nominated)`:e.aiKey?`ai key ${e.aiKey}, behaviour unobserved`:"ai unobserved",e.aiSamples?`${e.aiSamples} ai turn(s)`:null,e.aiModel?`ran on ${e.aiModel}`:null,e.model?`model ${e.model}`:null,e.tools&&e.tools.length?`tools ${e.tools.length}`:null].filter(Boolean);return`${e.label||"agent"} · ${r.join(" · ")}`}function readAiSecret(e,t){if(t.AEGIS_AI_SECRET)return String(t.AEGIS_AI_SECRET).trim();const r=e.indexOf("--ai-secret-file");return-1!==r&&e[r+1]?fs.readFileSync(e[r+1],"utf8").trim():""}function readSecret(e,t){if(t.AEGIS_FINGERPRINT_SECRET)return String(t.AEGIS_FINGERPRINT_SECRET).trim();const r=e.indexOf("--secret-file");return-1!==r&&e[r+1]?fs.readFileSync(e[r+1],"utf8").trim():""}function flag(e,t,r=null){const n=e.indexOf(t);return-1!==n&&void 0!==e[n+1]?e[n+1]:r}function main(e,t=process.env){const r=readSecret(e,t);if(e.includes("--verify")){const t=flag(e,"--verify");if(!t)throw new Error("fingerprint: --verify needs a record file");const n=verify(JSON.parse(fs.readFileSync(t,"utf8")),r);return process.stdout.write(JSON.stringify(n,null,2)+"\n"),n.ok?0:1}const n=flag(e,"--observations"),i=n?JSON.parse(fs.readFileSync(n,"utf8")):[],o=flag(e,"--touch"),a=o?JSON.parse(fs.readFileSync(o,"utf8")):null,s=flag(e,"--ai-observations"),l=s?JSON.parse(fs.readFileSync(s,"utf8")):null,u=mint({secret:r,label:flag(e,"--label",""),account:flag(e,"--account",""),model:flag(e,"--model",""),tools:(flag(e,"--tools","")||"").split(",").filter(Boolean),observations:i,touch:a,aiSecret:readAiSecret(e,t),aiModel:flag(e,"--ai-model",""),aiObservations:l});return process.stdout.write(JSON.stringify(u,null,2)+"\n"),0}const API={mint:mint,verify:verify,attest:attest,attestationBody:attestationBody,id:id,same:same,describe:describe,keyFingerprint:keyFingerprint,behaviouralSignature:behaviouralSignature,aiSignature:aiSignature,aiAxisFrom:aiAxisFrom,observationKey:observationKey,countObservations:countObservations,normaliseTools:normaliseTools,safeLabel:safeLabel,touchSignatureFrom:touchSignatureFrom,normaliseCodePath:normaliseCodePath,codeFileDigest:codeFileDigest,codeDigest:codeDigest,codeAxisFrom:codeAxisFrom,canonical:canonical,assertNoLeak:assertNoLeak,assertInputsClean:assertInputsClean,longHexRun:longHexRun,isFingerprintShape:isFingerprintShape,attestedFieldsFor:attestedFieldsFor,FP_VERSION:4,FP_ALGO:FP_ALGO,FP_PREFIX:"φ_",KEY_FP_LENGTH:12,SIG_LENGTH:16,ATTEST_LENGTH:32,LEAK_HEX_RUN:24,CODE_LEN:16,MAX_CODE_FILES:4096,MAX_PATH:200,BEHAVIOUR_PURPOSE:BEHAVIOUR_PURPOSE,AI_PURPOSE:AI_PURPOSE,ATTESTED_FIELDS:ATTESTED_FIELDS,ATTESTED_FIELDS_V1:ATTESTED_FIELDS_V1,ATTESTED_FIELDS_V2:ATTESTED_FIELDS_V2,ATTESTED_FIELDS_V3:ATTESTED_FIELDS_V3,ATTESTED_FIELDS_V4:ATTESTED_FIELDS_V4,ATTESTED_FIELDS_BY_VERSION:ATTESTED_FIELDS_BY_VERSION,main:main};module.exports=API;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const fs=require("node:fs"),path=require("node:path"),os=require("node:os"),crypto=require("node:crypto"),DEFAULTS={minChars:24,maxChars:2e3,maxEntriesPerSource:500,maxFilesPerSource:400,maxFileBytes:8388608},NOISE=[/^<command-name>/i,/^<local-command-stdout>/i,/^\[Request interrupted by user/i,/^Caveat: The messages below were generated by the user while running local commands/i,/^(ok|okay|yes|no|yep|nope|sure|thanks|thank you|continue|proceed|go on|done)[.!]?$/i];function isNoise(e){return NOISE.some(
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),os=require("node:os"),crypto=require("node:crypto"),DEFAULTS={minChars:24,maxChars:2e3,maxEntriesPerSource:500,maxFilesPerSource:400,maxFileBytes:8388608},NOISE=[/^<command-name>/i,/^<local-command-stdout>/i,/^\[Request interrupted by user/i,/^Caveat: The messages below were generated by the user while running local commands/i,/^(ok|okay|yes|no|yep|nope|sure|thanks|thank you|continue|proceed|go on|done)[.!]?$/i];function isNoise(e){return NOISE.some(t=>t.test(e))}function homeDir(e){return e||os.homedir()}function platformOf(e){return e||process.platform}function roamingDir(e,t){return"win32"!==t?null:e===os.homedir()&&process.env.APPDATA?process.env.APPDATA:path.join(e,"AppData","Roaming")}function localDir(e,t){return"win32"!==t?null:e===os.homedir()&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:path.join(e,"AppData","Local")}function macSupportDir(e,t){return"darwin"===t?path.join(e,"Library","Application Support"):null}function appRoots(e,t,r,{config:o=!0,data:n=!1,macSupport:s=!1}={}){const i=[];o&&i.push(path.join(e,".config",r)),n&&i.push(path.join(e,".local","share",r));const a=roamingDir(e,t);a&&o&&i.push(path.join(a,r));const c=localDir(e,t);if(c&&i.push(path.join(c,r)),s){const o=macSupportDir(e,t);o&&i.push(path.join(o,r))}return i}function cleanText(e){return"string"!=typeof e?"":e.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g," ").replace(/\s+/g," ").trim()}function stableId(...e){return`import-${crypto.createHash("sha1").update(e.join("|")).digest("hex").slice(0,32)}`}function readJsonl(e){const t=[];let r;try{r=fs.readFileSync(e,"utf8")}catch{return t}for(const e of r.split("\n")){const r=e.trim();if(r)try{t.push(JSON.parse(r))}catch{}}return t}function walkFiles(e,{ext:t,limit:r}){const o=[],n=[e];for(;n.length&&o.length<r;){const e=n.pop();let s;try{s=fs.readdirSync(e,{withFileTypes:!0})}catch{continue}for(const i of s){if(o.length>=r)break;if(i.isSymbolicLink())continue;const s=path.join(e,i.name);if(i.isDirectory()){if("node_modules"===i.name||".git"===i.name)continue;n.push(s)}else if(i.isFile()){if(t&&!t.some(e=>i.name.endsWith(e)))continue;o.push(s)}}}return o}function fileSize(e){try{return fs.statSync(e).size}catch{return 0}}function isFile(e){try{return fs.statSync(e).isFile()}catch{return!1}}function isDir(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function textFromClaudeMessage(e){if(!e)return"";const t=e.content;return"string"==typeof t?cleanText(t):Array.isArray(t)?t.filter(e=>e&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n"):""}function extractClaudeJsonl(e,t){const r=[],o=t.rel(e);for(const[t,n]of readJsonl(e).entries()){const e=n&&n.type,s="user"===e?"user":"assistant"===e?"assistant":null;if(!s)continue;if(n.isSidechain)continue;const i=cleanText(textFromClaudeMessage(n.message));i&&r.push({role:s,text:i,timestamp:n.timestamp||"",where:`${o}#${t}`})}return r}function extractGenericJsonl(e,t){const r=[],o=t.rel(e);for(const[t,n]of readJsonl(e).entries()){if(!n||"object"!=typeof n)continue;const e=n.role||n.message&&n.message.role;if("user"!==e&&"assistant"!==e)continue;const s=null!=n.content?n.content:n.message&&n.message.content,i=cleanText("string"==typeof s?s:textFromClaudeMessage({content:s}));i&&r.push({role:e,text:i,timestamp:n.timestamp||n.created_at||"",where:`${o}#${t}`})}return r}function extractMarkdown(e,t){if(fileSize(e)>DEFAULTS.maxFileBytes)return[];let r;try{r=fs.readFileSync(e,"utf8")}catch{return[]}const o=cleanText(r);return o?[{role:"user",text:o,timestamp:"",where:t.rel(e)}]:[]}function extractJsonMemory(e,t){if(fileSize(e)>DEFAULTS.maxFileBytes)return[];let r;try{r=JSON.parse(fs.readFileSync(e,"utf8"))}catch{return[]}const o=Array.isArray(r)?r:r&&Array.isArray(r.entries)?r.entries:r&&Array.isArray(r.memories)?r.memories:r&&Array.isArray(r.memory)?r.memory:[],n=t.rel(e);return o.map((e,t)=>"string"==typeof e?{role:"user",text:cleanText(e),timestamp:"",where:`${n}#${t}`}:{role:"user",text:cleanText(e&&(e.content||e.text||e.value||e.fact)),timestamp:e&&(e.timestamp||e.createdAt)||"",where:`${n}#${t}`}).filter(e=>e.text)}const SOURCES=[{id:"claude-code",label:"Claude Code",verified:!0,roots:e=>[path.join(e,".claude","projects")],files:e=>[path.join(e,".claude","history.jsonl")],extract:{"**/*.jsonl":extractClaudeJsonl,"*.jsonl":extractClaudeJsonl}},{id:"claude-memory",label:"Claude memory files",verified:!0,roots:e=>[path.join(e,".claude","memory")],files:e=>[path.join(e,".claude","memory.json")],extract:{".json":extractJsonMemory,".md":extractMarkdown,".txt":extractMarkdown}},{id:"aegiscodex",label:"AEGIS Codex engine",verified:!0,roots:e=>[path.join(e,".aegiscodex","memory")],files:()=>[],extract:{".json":extractJsonMemory,".jsonl":extractGenericJsonl,".md":extractMarkdown}},{id:"codex",label:"OpenAI Codex CLI",verified:!1,roots:e=>[path.join(e,".codex")],files:()=>[],extract:{".jsonl":extractGenericJsonl,".json":extractJsonMemory,".md":extractMarkdown}},{id:"gemini-cli",label:"Gemini CLI",verified:!1,roots:e=>[path.join(e,".gemini")],files:()=>[],extract:{".json":extractJsonMemory,".jsonl":extractGenericJsonl,".md":extractMarkdown}},{id:"cursor",label:"Cursor",verified:!1,roots:e=>[path.join(e,".cursor")],files:()=>[],extract:{".json":extractJsonMemory,".jsonl":extractGenericJsonl,".md":extractMarkdown}},{id:"continue",label:"Continue",verified:!1,roots:e=>[path.join(e,".continue")],files:()=>[],extract:{".json":extractJsonMemory,".jsonl":extractGenericJsonl,".md":extractMarkdown}},{id:"goose",label:"Goose",verified:!1,roots:(e,t)=>appRoots(e,t,"goose",{data:!0}),files:()=>[],extract:{".jsonl":extractGenericJsonl,".json":extractJsonMemory,".md":extractMarkdown}},{id:"opencode",label:"opencode",verified:!1,roots:(e,t)=>appRoots(e,t,"opencode",{data:!0}),files:()=>[],extract:{".json":extractJsonMemory,".jsonl":extractGenericJsonl,".md":extractMarkdown}},{id:"windsurf",label:"Windsurf / Codeium",verified:!1,roots:(e,t)=>[path.join(e,".windsurf"),path.join(e,".codeium"),...appRoots(e,t,"Windsurf",{config:!1,macSupport:!0}),...appRoots(e,t,"Codeium",{config:!1,macSupport:!0})],files:()=>[],extract:{".json":extractJsonMemory,".jsonl":extractGenericJsonl,".md":extractMarkdown}},{id:"zed",label:"Zed",verified:!1,roots:(e,t)=>appRoots(e,t,"zed"),files:()=>[],extract:{".json":extractJsonMemory,".jsonl":extractGenericJsonl}},{id:"claude-desktop",label:"Claude Desktop app",verified:!1,roots:(e,t)=>appRoots(e,t,"Claude",{macSupport:!0}),files:()=>[],extract:{".json":extractJsonMemory,".jsonl":extractClaudeJsonl,".md":extractMarkdown}}];function suffixOf(e){const t=e.lastIndexOf("*");return-1===t?e:e.slice(t+1)}function extractorFor(e,t){for(const[r,o]of Object.entries(e))if(t.endsWith(suffixOf(r)))return o;return null}function sourceById(e){return SOURCES.find(t=>t.id===e)||null}function listSources(e,t){const r=homeDir(e),o=platformOf(t);return SOURCES.map(e=>{const t=e.roots(r,o).filter(isDir),n=(e.files?e.files(r):[]).filter(isFile);return{id:e.id,label:e.label,verified:e.verified,roots:t.concat(n),present:t.length>0||n.length>0}})}function scan(e={}){const t=homeDir(e.home),r=platformOf(e.platform),o=null!=e.minChars?e.minChars:DEFAULTS.minChars,n=null!=e.maxChars?e.maxChars:DEFAULTS.maxChars,s=null!=e.maxEntriesPerSource?e.maxEntriesPerSource:DEFAULTS.maxEntriesPerSource,i=null!=e.limit?e.limit:1/0,a=e.sources&&e.sources.length?new Set(e.sources):null,c=[],l=[],u=new Set;for(const e of SOURCES){if(a&&!a.has(e.id))continue;const f=e.roots(t,r).filter(isDir),d=(e.files?e.files(t):[]).filter(isFile),p=f.length>0||d.length>0,m={id:e.id,label:e.label,verified:e.verified,present:p,files:0,scanned:0,count:0,skipped:0,roots:f,session:`import:${e.id}`};if(!p){c.push(m);continue}const x=d.slice();for(const t of f){const r=Object.keys(e.extract).map(suffixOf);x.push(...walkFiles(t,{ext:r,limit:DEFAULTS.maxFilesPerSource}))}const h={rel:e=>path.relative(t,e)};for(const t of x){if(m.count>=s||l.length>=i)break;if(fileSize(t)>DEFAULTS.maxFileBytes){m.skipped+=1;continue}const r=extractorFor(e.extract,t);if(!r)continue;let a;m.files+=1;try{a=r(t,h)}catch{continue}for(const t of a){if(m.count>=s||l.length>=i)break;m.scanned+=1;let r=t.text;if(r.length>n&&(r=`${r.slice(0,n)}…`),r.length<o||isNoise(r)){m.skipped+=1;continue}const a=stableId(e.id,t.where,t.role,r);u.has(a)||(u.add(a),l.push({id:a,content:r,role:t.role,source:e.id,session:m.session,tags:["imported",e.id],importance:5,timestamp:t.timestamp||(new Date).toISOString()}),m.count+=1)}}c.push(m)}return{entries:l,sources:c,totals:{entries:l.length,sourcesPresent:c.filter(e=>e.present).length,sourcesWithEntries:c.filter(e=>e.count>0).length,scanned:c.reduce((e,t)=>e+t.scanned,0),skipped:c.reduce((e,t)=>e+t.skipped,0)},scannedAt:(new Date).toISOString()}}function chunk(e,t=200){const r=[];for(let o=0;o<e.length;o+=t)r.push(e.slice(o,o+t));return r}function describe(e){const t=e.sources.filter(e=>e.present);if(!t.length)return"No other AI tool memory found on this machine.";const r=t.map(e=>{const t=e.verified?"":" (best-effort layout)";return` ${e.label}${t}: ${e.count} entries from ${e.files} file(s), ${e.skipped} skipped`});return[`Found ${e.totals.entries} importable entries across ${e.totals.sourcesWithEntries} source(s):`,...r].join("\n")}module.exports={DEFAULTS:DEFAULTS,SOURCES:SOURCES,scan:scan,listSources:listSources,describe:describe,chunk:chunk,stableId:stableId,sourceById:sourceById,_internal:{walkFiles:walkFiles,extractClaudeJsonl:extractClaudeJsonl,extractGenericJsonl:extractGenericJsonl,extractJsonMemory:extractJsonMemory,extractMarkdown:extractMarkdown,cleanText:cleanText,isNoise:isNoise,suffixOf:suffixOf,platformOf:platformOf,roamingDir:roamingDir,localDir:localDir,macSupportDir:macSupportDir,appRoots:appRoots}};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const fs=require("node:fs"),path=require("node:path"),os=require("node:os"),crypto=require("node:crypto");let DatabaseSync=null;try{DatabaseSync=require("node:sqlite").DatabaseSync}catch{DatabaseSync=null}const DEFAULTS={minMessages:2,minChars:2,maxCharsPerMessage:8e3,maxMessagesPerSession:400,maxSessionsPerSource:200,maxFilesPerSource:600,maxFileBytes:33554432,maxTotalMessages:2e4},NOISE=[/^<command-name>/i,/^<local-command-stdout>/i,/^<local-command-caveat>/i,/^<environment_context>/i,/^<user_instructions>/i,/^\[Request interrupted by user/i,/^Caveat: The messages below were generated by the user while running local commands/i,/^(ok|okay|yes|no|yep|nope|sure|thanks|thank you|continue|proceed|go on|done)[.!]?$/i],layout=require("./foreign-memory.js")._internal,platformOf=layout.platformOf,appRoots=layout.appRoots;function homeDir(e){return e||os.homedir()}function isDir(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function isFile(e){try{return fs.statSync(e).isFile()}catch{return!1}}function fileSize(e){try{return fs.statSync(e).size}catch{return 0}}function fileMtime(e){try{return fs.statSync(e).mtimeMs}catch{return Date.now()}}function stableId(...e){return`imp-${crypto.createHash("sha1").update(e.join("|")).digest("hex").slice(0,16)}`}function cleanText(e){return"string"!=typeof e?"":e.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g," ").replace(/\s+/g," ").trim()}function isNoise(e){return!e||NOISE.some((t=>t.test(e)))}function readJsonl(e){const t=[];let s;try{s=fs.readFileSync(e,"utf8")}catch{return t}for(const e of s.split("\n")){const s=e.trim();if(s)try{t.push(JSON.parse(s))}catch{}}return t}function walkFiles(e,{ext:t,limit:s}){const n=[],o=[e];for(;o.length&&n.length<s;){const e=o.pop();let i;try{i=fs.readdirSync(e,{withFileTypes:!0})}catch{continue}for(const r of i){if(n.length>=s)break;if(r.isSymbolicLink())continue;const i=path.join(e,r.name);if(r.isDirectory()){if("node_modules"===r.name||".git"===r.name)continue;o.push(i)}else if(r.isFile()){if(t&&!t.some((e=>r.name.endsWith(e))))continue;n.push(i)}}}return n}function textFromClaudeMessage(e){if(!e)return"";const t=null!=e.content?e.content:e;return"string"==typeof t?cleanText(t):Array.isArray(t)?cleanText(t.filter((e=>e&&"text"===e.type&&"string"==typeof e.text)).map((e=>e.text)).join("\n")):""}function extractClaudeSession(e,t){const s=readJsonl(e),n=[];let o="",i="",r="",a="",c="";for(const e of s){if(!e||"object"!=typeof e)continue;if(e.sessionId&&!c&&(c=e.sessionId),e.cwd&&!i&&(i=e.cwd),"summary"===e.type&&"string"==typeof e.summary&&!o){o=cleanText(e.summary);continue}const s="user"===e.type?"user":"assistant"===e.type?"assistant":null;if(!s)continue;if(!0===e.isSidechain)continue;const l=textFromClaudeMessage(e.message);isNoise(l)||(n.push({role:s,content:l.slice(0,t.maxCharsPerMessage)}),!r&&e.timestamp&&(r=e.timestamp),e.timestamp&&(a=e.timestamp))}return finishSession({file:e,messages:n,title:o,cwd:i,foreignId:c,first:r,last:a,opts:t})}function extractCodexSession(e,t){const s=readJsonl(e),n=[];let o="",i="",r="",a="";const c=(e,s)=>{isNoise(s)||n.push({role:e,content:s.slice(0,t.maxCharsPerMessage)})};for(const e of s){if(!e||"object"!=typeof e)continue;const t=e.payload&&"object"==typeof e.payload?e.payload:null,s=e.timestamp||t&&t.timestamp||"";if("session_meta"===e.type&&t)t.id&&!a&&(a=String(t.id)),t.cwd&&!o&&(o=String(t.cwd)),s&&!i&&(i=s);else if("response_item"===e.type&&t&&"message"===t.type){const e=t.role;if("user"!==e&&"assistant"!==e)continue;c(e,cleanText((Array.isArray(t.content)?t.content:[]).filter((e=>e&&("input_text"===e.type||"output_text"===e.type||"text"===e.type))).map((e=>e.text)).filter((e=>"string"==typeof e)).join("\n"))),s&&(r=s)}else"event_msg"===e.type&&t&&("user_message"===t.type?c("user",cleanText(t.message)):"agent_message"===t.type&&c("assistant",cleanText(t.message)),s&&(r=s))}return finishSession({file:e,messages:n,title:"",cwd:o,foreignId:a,first:i,last:r,opts:t})}function extractGenericSession(e,t){const s=readJsonl(e),n=[];let o="",i="",r="",a="";for(const e of s){if(!e||"object"!=typeof e)continue;const s=e.role||e.message&&e.message.role;if("user"!==s&&"assistant"!==s)continue;const c=null!=e.content?e.content:e.message&&e.message.content,l=cleanText("string"==typeof c?c:textFromClaudeMessage({content:c}));if(isNoise(l))continue;n.push({role:s,content:l.slice(0,t.maxCharsPerMessage)});const u=e.timestamp||e.created_at||e.createdAt||"";u&&!o&&(o=u),u&&(i=u),a||"string"!=typeof e.cwd||(a=e.cwd),r||"string"!=typeof e.title||(r=cleanText(e.title))}return finishSession({file:e,messages:n,title:r,cwd:a,foreignId:"",first:o,last:i,opts:t})}function extractJsonSessions(e,t){if(fileSize(e)>t.maxFileBytes)return[];let s;try{s=JSON.parse(fs.readFileSync(e,"utf8"))}catch{return[]}if(!s||"object"!=typeof s)return[];const n=Array.isArray(s)?s:Array.isArray(s.sessions)?s.sessions:Array.isArray(s.conversations)?s.conversations:Array.isArray(s.chats)?s.chats:Array.isArray(s.threads)?s.threads:null;if(!n)return[];const o=[];for(const[s,i]of n.entries()){if(!i||"object"!=typeof i)continue;const n=Array.isArray(i.messages)?i.messages:Array.isArray(i.conversation)?i.conversation:Array.isArray(i.turns)?i.turns:[],r=[];for(const e of n){if(!e||"object"!=typeof e)continue;const s="assistant"===e.role?"assistant":"user"===e.role?"user":null;if(!s)continue;const n=null!=e.content?e.content:e.text,o=cleanText("string"==typeof n?n:textFromClaudeMessage({content:n}));isNoise(o)||r.push({role:s,content:o.slice(0,t.maxCharsPerMessage)})}const a=finishSession({file:`${e}#${s}`,messages:r,title:cleanText(i.title||i.name||""),cwd:"string"==typeof i.cwd?i.cwd:"",foreignId:i.id||i.sessionId||i.uuid||"",first:i.createdAt||i.created_at||"",last:i.updatedAt||i.updated_at||"",opts:t});a&&o.push(a)}return o}function finishSession({file:e,messages:t,title:s,cwd:n,foreignId:o,first:i,last:r,opts:a}){const c=t.slice(0,a.maxMessagesPerSession);if(c.length<a.minMessages)return null;const l=c.find((e=>"user"===e.role));if(!l)return null;const u=(e,t)=>{const s=Date.parse(e);return Number.isFinite(s)?s:t},d=fileMtime(e.split("#")[0]);return{file:e,foreignId:o?String(o):path.basename(e).replace(/\.(jsonl|json)$/i,""),title:s||cleanText(l.content).slice(0,60)||path.basename(path.dirname(e))||"imported session",cwd:n||"",messages:c,createdAt:u(i,d),updatedAt:u(r,d)}}function extractJsonSessionDoc(e,t){if(fileSize(e)>t.maxFileBytes)return[];let s;try{s=JSON.parse(fs.readFileSync(e,"utf8"))}catch{return[]}if(!s||"object"!=typeof s)return[];const n=Array.isArray(s.messages)?s.messages:Array.isArray(s.conversation)?s.conversation:Array.isArray(s.turns)?s.turns:null;if(!n)return[];const o=[];for(const e of n){if(!e||"object"!=typeof e)continue;const s=e.role||e.type||e.author,n="assistant"===s||"model"===s||"gemini"===s||"ai"===s?"assistant":"user"===s||"human"===s?"user":null;if(!n)continue;const i=null!=e.content?e.content:e.text,r=cleanText("string"==typeof i?i:textFromClaudeMessage({content:i}));isNoise(r)||o.push({role:n,content:r.slice(0,t.maxCharsPerMessage)})}const i=finishSession({file:e,messages:o,title:cleanText(s.title||s.name||""),cwd:"string"==typeof s.cwd?s.cwd:"",foreignId:s.id||s.sessionId||path.basename(e).replace(/\.json$/i,""),first:s.createdAt||s.created_at||s.startTime||"",last:s.updatedAt||s.updated_at||s.endTime||"",opts:t});return i?[i]:[]}function openReadOnlyDb(e){if(!DatabaseSync)return null;try{return new DatabaseSync(e,{readOnly:!0})}catch{return null}}function extractOpencodeDb(e,t){const s=openReadOnlyDb(e);if(!s)return[];try{const n=s.prepare("SELECT id, title, directory, time_created, time_updated FROM session").all(),o=[];for(const i of n){const n=s.prepare("SELECT id, data FROM message WHERE session_id = ? ORDER BY time_created, id").all(i.id),r=[];for(const e of n){let n;try{n=JSON.parse(e.data)}catch{continue}const o=n&&"assistant"===n.role?"assistant":n&&"user"===n.role?"user":null;if(!o)continue;const i=cleanText(s.prepare("SELECT data FROM part WHERE message_id = ? ORDER BY time_created, id").all(e.id).map((e=>{try{const t=JSON.parse(e.data);return t&&"text"===t.type&&"string"==typeof t.text?t.text:""}catch{return""}})).filter(Boolean).join("\n"));isNoise(i)||r.push({role:o,content:i.slice(0,t.maxCharsPerMessage)})}const a=finishSession({file:`${e}#${i.id}`,messages:r,title:cleanText(i.title||""),cwd:"string"==typeof i.directory?i.directory:"",foreignId:i.id,first:i.time_created?new Date(i.time_created).toISOString():"",last:i.time_updated?new Date(i.time_updated).toISOString():"",opts:t});a&&o.push(a)}return o}finally{s.close()}}function extractCodexThreadHistoryDb(e,t){const s=openReadOnlyDb(e);if(!s)return[];try{const n=s.prepare("SELECT thread_id, item_type, item_json, created_at_ms FROM thread_items WHERE item_type IN ('userMessage','agentMessage','assistantMessage') ORDER BY thread_id, rollout_ordinal").all(),o=new Map;for(const e of n)o.has(e.thread_id)||o.set(e.thread_id,[]),o.get(e.thread_id).push(e);const i=[];for(const[s,n]of o){const o=[];let r="",a="";for(const e of n){let s;try{s=JSON.parse(e.item_json)}catch{continue}const n="userMessage"===e.item_type?"user":"assistant",i=cleanText((Array.isArray(s&&s.content)?s.content:[]).filter((e=>e&&"text"===e.type&&"string"==typeof e.text)).map((e=>e.text)).join("\n"));if(isNoise(i))continue;o.push({role:n,content:i.slice(0,t.maxCharsPerMessage)});const c=e.created_at_ms?new Date(e.created_at_ms).toISOString():"";c&&!r&&(r=c),c&&(a=c)}const c=finishSession({file:`${e}#${s}`,messages:o,title:"",cwd:"",foreignId:s,first:r,last:a,opts:t});c&&i.push(c)}return i}finally{s.close()}}const SQLITE_EXTRACTORS={opencode:extractOpencodeDb,codex:extractCodexThreadHistoryDb},SOURCES=[{id:"claude-code",label:"Claude Code",verified:!0,roots:e=>[path.join(e,".claude","projects")],extract:{".jsonl":extractClaudeSession}},{id:"claude-desktop",label:"Claude Desktop",verified:!1,roots:(e,t)=>appRoots(e,t,"Claude",{macSupport:!0}),extract:{".jsonl":extractClaudeSession,".json":extractJsonSessions}},{id:"codex",label:"OpenAI Codex CLI",verified:!0,roots:e=>[path.join(e,".codex","sessions")],sqlite:e=>[path.join(e,".codex","thread_history_1.sqlite"),path.join(e,".codex","history_1.sqlite")],extract:{".jsonl":extractCodexSession}},{id:"gemini-cli",label:"Gemini CLI",verified:!1,roots:e=>[path.join(e,".gemini","tmp")],extract:{".json":extractJsonSessionDoc,".jsonl":extractGenericSession}},{id:"opencode",label:"opencode",verified:!1,roots:(e,t)=>[...appRoots(e,t,"opencode",{data:!0}),path.join(e,".local","share","opencode")],sqlite:e=>[path.join(e,".local","share","opencode","opencode.db")],extract:{".json":extractJsonSessions,".jsonl":extractGenericSession}},{id:"cursor",label:"Cursor",verified:!1,roots:(e,t)=>[path.join(e,".cursor"),...appRoots(e,t,"Cursor",{macSupport:!0})],sqlite:(e,t)=>{const s="darwin"===t?path.join(e,"Library","Application Support","Cursor"):null,n=appRoots(e,t,"Cursor",{macSupport:!0})[0]||path.join(e,".cursor");return[s?path.join(s,"User","globalStorage","state.vscdb"):path.join(n,"User","globalStorage","state.vscdb")]},extract:{}},{id:"windsurf",label:"Windsurf / Codeium",verified:!1,roots:(e,t)=>[path.join(e,".windsurf"),path.join(e,".codeium"),...appRoots(e,t,"Windsurf",{config:!1,macSupport:!0})],extract:{".json":extractJsonSessions,".jsonl":extractGenericSession}},{id:"continue",label:"Continue",verified:!1,roots:e=>[path.join(e,".continue")],extract:{".json":extractJsonSessions,".jsonl":extractGenericSession}},{id:"goose",label:"Goose",verified:!1,roots:(e,t)=>appRoots(e,t,"goose",{data:!0}),sqlite:(e,t)=>appRoots(e,t,"goose",{data:!0}).map((e=>path.join(e,"sessions.db"))),extract:{".json":extractJsonSessions,".jsonl":extractGenericSession}},{id:"zed",label:"Zed",verified:!1,roots:(e,t)=>appRoots(e,t,"zed"),sqlite:(e,t)=>appRoots(e,t,"zed").flatMap((e=>[path.join(e,"threads","threads.db"),path.join(e,"conversations","conversations.db")])),extract:{}},{id:"kimi-code",label:"Kimi Code",verified:!1,roots:e=>[path.join(e,".kimi-code","sessions"),path.join(e,".kimi-code","history")],extract:{".jsonl":extractGenericSession,".json":extractJsonSessionDoc}},{id:"aegiscodex",label:"AEGIS Codex engine",verified:!0,roots:e=>[path.join(e,".aegiscodex","sessions"),path.join(e,".aegiscodex","history")],extract:{".jsonl":extractGenericSession,".json":extractJsonSessionDoc}}];function sourceById(e){return SOURCES.find((t=>t.id===e))||null}function listSources(e,t){const s=homeDir(e),n=platformOf(t);return SOURCES.map((e=>{const t=e.roots(s,n).filter(isDir),o=(e.sqlite?e.sqlite(s,n):[]).filter(isFile),i=o.length>0&&"function"==typeof SQLITE_EXTRACTORS[e.id];return{id:e.id,label:e.label,verified:e.verified,roots:t,databases:o,present:t.length>0||o.length>0,readable:t.length>0||i}}))}function suffixOf(e){const t=e.lastIndexOf("*");return-1===t?e:e.slice(t+1)}function extractorFor(e,t){for(const[s,n]of Object.entries(e))if(t.endsWith(suffixOf(s)))return n;return null}function scan(e={}){const t=homeDir(e.home),s=platformOf(e.platform),n=null!=e.maxSessionsPerSource?e.maxSessionsPerSource:DEFAULTS.maxSessionsPerSource,o=null!=e.limit?e.limit:1/0,i=e.sources&&e.sources.length?new Set(e.sources):null,r={minMessages:null!=e.minMessages?e.minMessages:DEFAULTS.minMessages,minChars:null!=e.minChars?e.minChars:DEFAULTS.minChars,maxCharsPerMessage:null!=e.maxCharsPerMessage?e.maxCharsPerMessage:DEFAULTS.maxCharsPerMessage,maxMessagesPerSession:null!=e.maxMessagesPerSession?e.maxMessagesPerSession:DEFAULTS.maxMessagesPerSession,maxFileBytes:null!=e.maxFileBytes?e.maxFileBytes:DEFAULTS.maxFileBytes},a=[],c=[],l=new Set;let u=0;for(const e of SOURCES){if(i&&!i.has(e.id))continue;const d=e.roots(t,s).filter(isDir),f=(e.sqlite?e.sqlite(t,s):[]).filter(isFile),p=d.length>0||f.length>0,m=Object.keys(e.extract).map(suffixOf),h=SQLITE_EXTRACTORS[e.id],g={id:e.id,label:e.label,verified:e.verified,present:p,roots:d,databases:f,files:0,scanned:0,count:0,skipped:0,unreadable:p&&!m.length&&!(f.length&&h),messages:0};if(!p){a.push(g);continue}const y=t=>{if(t.messages.length<r.minMessages)return void(g.skipped+=1);if(u+t.messages.length>DEFAULTS.maxTotalMessages)return!1;const s=stableId(e.id,t.foreignId||t.file,t.title);if(!l.has(s))return l.add(s),u+=t.messages.length,g.scanned+=1,g.count+=1,g.messages+=t.messages.length,c.push({id:s,source:e.id,sourceLabel:e.label,title:t.title,cwd:t.cwd,createdAt:t.createdAt,updatedAt:t.updatedAt,messages:t.messages,file:t.file}),!0;g.skipped+=1};if(m.length){const t=[];for(const e of d)t.push(...walkFiles(e,{ext:m,limit:DEFAULTS.maxFilesPerSource}));for(const s of t){if(g.count>=n||c.length>=o)break;if(fileSize(s)>r.maxFileBytes){g.skipped+=1;continue}const t=extractorFor(e.extract,s);if(!t)continue;let i;g.files+=1;try{i=t(s,r)}catch{g.skipped+=1;continue}const a=Array.isArray(i)?i:i?[i]:[];if(a.length)for(const e of a){if(g.count>=n||c.length>=o)break;if(!1===y(e))break}else g.skipped+=1}}if(f.length&&h)for(const e of f){if(g.count>=n||c.length>=o)break;let t;try{t=h(e,r)}catch{g.skipped+=1;continue}const s=Array.isArray(t)?t:t?[t]:[];if(g.files+=1,s.length)for(const e of s){if(g.count>=n||c.length>=o)break;if(!1===y(e))break}else g.skipped+=1}a.push(g)}return{sessions:c,sources:a,totals:{sessions:c.length,sourcesPresent:a.filter((e=>e.present)).length,sourcesWithSessions:a.filter((e=>e.count>0)).length,sourcesUnreadable:a.filter((e=>e.unreadable)).length,files:a.reduce(((e,t)=>e+t.files),0),messages:u,skipped:a.reduce(((e,t)=>e+t.skipped),0)},scannedAt:(new Date).toISOString()}}function toRecord(e,{pending:t=!1}={}){const s=(Array.isArray(e.messages)?e.messages:[]).map(((t,s)=>({role:"assistant"===t.role?"assistant":"user",content:String(null==t.content?"":t.content),at:0===s?e.createdAt||e.updatedAt||Date.now():void 0})));for(const e of s)null==e.at&&delete e.at;return{id:e.id,title:e.title||"imported session",messages:s,createdAt:e.createdAt||e.updatedAt||Date.now(),updatedAt:e.updatedAt||e.createdAt||Date.now(),origin:`import:${e.source}`,importedFrom:{source:e.source,label:e.sourceLabel,file:e.file,at:(new Date).toISOString()},pending:!0===t}}function chunk(e,t=50){const s=[];for(let n=0;n<e.length;n+=t)s.push(e.slice(n,n+t));return s}function describe(e){const t=(e.sources||[]).filter((e=>e.present));if(!t.length)return"No other AI tool sessions found on this machine.";const s=t.map((e=>{if(e.unreadable)return` ${e.label}: found, but its store is a database this version cannot read`;const t=e.verified?"":" (best-effort layout)";return` ${e.label}${t}: ${e.count} session(s) from ${e.files} file(s), ${e.skipped} skipped`}));return[`Found ${e.totals.sessions} importable session(s) across ${e.totals.sourcesWithSessions} source(s):`,...s].join("\n")}module.exports={DEFAULTS:DEFAULTS,SOURCES:SOURCES,scan:scan,listSources:listSources,describe:describe,chunk:chunk,toRecord:toRecord,stableId:stableId,sourceById:sourceById,_internal:{walkFiles:walkFiles,readJsonl:readJsonl,cleanText:cleanText,isNoise:isNoise,finishSession:finishSession,extractClaudeSession:extractClaudeSession,extractCodexSession:extractCodexSession,extractGenericSession:extractGenericSession,extractJsonSessions:extractJsonSessions,extractJsonSessionDoc:extractJsonSessionDoc,extractorFor:extractorFor,suffixOf:suffixOf,platformOf:platformOf,appRoots:appRoots}};
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),os=require("node:os"),crypto=require("node:crypto");let DatabaseSync=null;try{DatabaseSync=require("node:sqlite").DatabaseSync}catch{DatabaseSync=null}const DEFAULTS={minMessages:2,minChars:2,maxCharsPerMessage:8e3,maxMessagesPerSession:400,maxSessionsPerSource:200,maxFilesPerSource:600,maxFileBytes:33554432,maxTotalMessages:2e4},NOISE=[/^<command-name>/i,/^<local-command-stdout>/i,/^<local-command-caveat>/i,/^<environment_context>/i,/^<user_instructions>/i,/^\[Request interrupted by user/i,/^Caveat: The messages below were generated by the user while running local commands/i,/^(ok|okay|yes|no|yep|nope|sure|thanks|thank you|continue|proceed|go on|done)[.!]?$/i],layout=require("./foreign-memory.js")._internal,platformOf=layout.platformOf,appRoots=layout.appRoots;function homeDir(e){return e||os.homedir()}function isDir(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function isFile(e){try{return fs.statSync(e).isFile()}catch{return!1}}function fileSize(e){try{return fs.statSync(e).size}catch{return 0}}function fileMtime(e){try{return fs.statSync(e).mtimeMs}catch{return Date.now()}}function stableId(...e){return`imp-${crypto.createHash("sha1").update(e.join("|")).digest("hex").slice(0,16)}`}function cleanText(e){return"string"!=typeof e?"":e.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g," ").replace(/\s+/g," ").trim()}function isNoise(e){return!e||NOISE.some(t=>t.test(e))}function readJsonl(e){const t=[];let s;try{s=fs.readFileSync(e,"utf8")}catch{return t}for(const e of s.split("\n")){const s=e.trim();if(s)try{t.push(JSON.parse(s))}catch{}}return t}function walkFiles(e,{ext:t,limit:s}){const n=[],o=[e];for(;o.length&&n.length<s;){const e=o.pop();let i;try{i=fs.readdirSync(e,{withFileTypes:!0})}catch{continue}for(const r of i){if(n.length>=s)break;if(r.isSymbolicLink())continue;const i=path.join(e,r.name);if(r.isDirectory()){if("node_modules"===r.name||".git"===r.name)continue;o.push(i)}else if(r.isFile()){if(t&&!t.some(e=>r.name.endsWith(e)))continue;n.push(i)}}}return n}function textFromClaudeMessage(e){if(!e)return"";const t=null!=e.content?e.content:e;return"string"==typeof t?cleanText(t):Array.isArray(t)?cleanText(t.filter(e=>e&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n")):""}function extractClaudeSession(e,t){const s=readJsonl(e),n=[];let o="",i="",r="",a="",c="";for(const e of s){if(!e||"object"!=typeof e)continue;if(e.sessionId&&!c&&(c=e.sessionId),e.cwd&&!i&&(i=e.cwd),"summary"===e.type&&"string"==typeof e.summary&&!o){o=cleanText(e.summary);continue}const s="user"===e.type?"user":"assistant"===e.type?"assistant":null;if(!s)continue;if(!0===e.isSidechain)continue;const l=textFromClaudeMessage(e.message);isNoise(l)||(n.push({role:s,content:l.slice(0,t.maxCharsPerMessage)}),!r&&e.timestamp&&(r=e.timestamp),e.timestamp&&(a=e.timestamp))}return finishSession({file:e,messages:n,title:o,cwd:i,foreignId:c,first:r,last:a,opts:t})}function extractCodexSession(e,t){const s=readJsonl(e),n=[];let o="",i="",r="",a="";const c=(e,s)=>{isNoise(s)||n.push({role:e,content:s.slice(0,t.maxCharsPerMessage)})};for(const e of s){if(!e||"object"!=typeof e)continue;const t=e.payload&&"object"==typeof e.payload?e.payload:null,s=e.timestamp||t&&t.timestamp||"";if("session_meta"===e.type&&t)t.id&&!a&&(a=String(t.id)),t.cwd&&!o&&(o=String(t.cwd)),s&&!i&&(i=s);else{if("response_item"===e.type&&t&&"message"===t.type){const e=t.role;if("user"!==e&&"assistant"!==e)continue;c(e,cleanText((Array.isArray(t.content)?t.content:[]).filter(e=>e&&("input_text"===e.type||"output_text"===e.type||"text"===e.type)).map(e=>e.text).filter(e=>"string"==typeof e).join("\n"))),s&&(r=s);continue}"event_msg"===e.type&&t&&("user_message"===t.type?c("user",cleanText(t.message)):"agent_message"===t.type&&c("assistant",cleanText(t.message)),s&&(r=s))}}return finishSession({file:e,messages:n,title:"",cwd:o,foreignId:a,first:i,last:r,opts:t})}function extractGenericSession(e,t){const s=readJsonl(e),n=[];let o="",i="",r="",a="";for(const e of s){if(!e||"object"!=typeof e)continue;const s=e.role||e.message&&e.message.role;if("user"!==s&&"assistant"!==s)continue;const c=null!=e.content?e.content:e.message&&e.message.content,l=cleanText("string"==typeof c?c:textFromClaudeMessage({content:c}));if(isNoise(l))continue;n.push({role:s,content:l.slice(0,t.maxCharsPerMessage)});const u=e.timestamp||e.created_at||e.createdAt||"";u&&!o&&(o=u),u&&(i=u),a||"string"!=typeof e.cwd||(a=e.cwd),r||"string"!=typeof e.title||(r=cleanText(e.title))}return finishSession({file:e,messages:n,title:r,cwd:a,foreignId:"",first:o,last:i,opts:t})}function extractJsonSessions(e,t){if(fileSize(e)>t.maxFileBytes)return[];let s;try{s=JSON.parse(fs.readFileSync(e,"utf8"))}catch{return[]}if(!s||"object"!=typeof s)return[];const n=Array.isArray(s)?s:Array.isArray(s.sessions)?s.sessions:Array.isArray(s.conversations)?s.conversations:Array.isArray(s.chats)?s.chats:Array.isArray(s.threads)?s.threads:null;if(!n)return[];const o=[];for(const[s,i]of n.entries()){if(!i||"object"!=typeof i)continue;const n=Array.isArray(i.messages)?i.messages:Array.isArray(i.conversation)?i.conversation:Array.isArray(i.turns)?i.turns:[],r=[];for(const e of n){if(!e||"object"!=typeof e)continue;const s="assistant"===e.role?"assistant":"user"===e.role?"user":null;if(!s)continue;const n=null!=e.content?e.content:e.text,o=cleanText("string"==typeof n?n:textFromClaudeMessage({content:n}));isNoise(o)||r.push({role:s,content:o.slice(0,t.maxCharsPerMessage)})}const a=finishSession({file:`${e}#${s}`,messages:r,title:cleanText(i.title||i.name||""),cwd:"string"==typeof i.cwd?i.cwd:"",foreignId:i.id||i.sessionId||i.uuid||"",first:i.createdAt||i.created_at||"",last:i.updatedAt||i.updated_at||"",opts:t});a&&o.push(a)}return o}function finishSession({file:e,messages:t,title:s,cwd:n,foreignId:o,first:i,last:r,opts:a}){const c=t.slice(0,a.maxMessagesPerSession);if(c.length<a.minMessages)return null;const l=c.find(e=>"user"===e.role);if(!l)return null;const u=(e,t)=>{const s=Date.parse(e);return Number.isFinite(s)?s:t},d=fileMtime(e.split("#")[0]);return{file:e,foreignId:o?String(o):path.basename(e).replace(/\.(jsonl|json)$/i,""),title:s||cleanText(l.content).slice(0,60)||path.basename(path.dirname(e))||"imported session",cwd:n||"",messages:c,createdAt:u(i,d),updatedAt:u(r,d)}}function extractJsonSessionDoc(e,t){if(fileSize(e)>t.maxFileBytes)return[];let s;try{s=JSON.parse(fs.readFileSync(e,"utf8"))}catch{return[]}if(!s||"object"!=typeof s)return[];const n=Array.isArray(s.messages)?s.messages:Array.isArray(s.conversation)?s.conversation:Array.isArray(s.turns)?s.turns:null;if(!n)return[];const o=[];for(const e of n){if(!e||"object"!=typeof e)continue;const s=e.role||e.type||e.author,n="assistant"===s||"model"===s||"gemini"===s||"ai"===s?"assistant":"user"===s||"human"===s?"user":null;if(!n)continue;const i=null!=e.content?e.content:e.text,r=cleanText("string"==typeof i?i:textFromClaudeMessage({content:i}));isNoise(r)||o.push({role:n,content:r.slice(0,t.maxCharsPerMessage)})}const i=finishSession({file:e,messages:o,title:cleanText(s.title||s.name||""),cwd:"string"==typeof s.cwd?s.cwd:"",foreignId:s.id||s.sessionId||path.basename(e).replace(/\.json$/i,""),first:s.createdAt||s.created_at||s.startTime||"",last:s.updatedAt||s.updated_at||s.endTime||"",opts:t});return i?[i]:[]}function openReadOnlyDb(e){if(!DatabaseSync)return null;try{return new DatabaseSync(e,{readOnly:!0})}catch{return null}}function extractOpencodeDb(e,t){const s=openReadOnlyDb(e);if(!s)return[];try{const n=s.prepare("SELECT id, title, directory, time_created, time_updated FROM session").all(),o=[];for(const i of n){const n=s.prepare("SELECT id, data FROM message WHERE session_id = ? ORDER BY time_created, id").all(i.id),r=[];for(const e of n){let n;try{n=JSON.parse(e.data)}catch{continue}const o=n&&"assistant"===n.role?"assistant":n&&"user"===n.role?"user":null;if(!o)continue;const i=cleanText(s.prepare("SELECT data FROM part WHERE message_id = ? ORDER BY time_created, id").all(e.id).map(e=>{try{const t=JSON.parse(e.data);return t&&"text"===t.type&&"string"==typeof t.text?t.text:""}catch{return""}}).filter(Boolean).join("\n"));isNoise(i)||r.push({role:o,content:i.slice(0,t.maxCharsPerMessage)})}const a=finishSession({file:`${e}#${i.id}`,messages:r,title:cleanText(i.title||""),cwd:"string"==typeof i.directory?i.directory:"",foreignId:i.id,first:i.time_created?new Date(i.time_created).toISOString():"",last:i.time_updated?new Date(i.time_updated).toISOString():"",opts:t});a&&o.push(a)}return o}finally{s.close()}}function extractCodexThreadHistoryDb(e,t){const s=openReadOnlyDb(e);if(!s)return[];try{const n=s.prepare("SELECT thread_id, item_type, item_json, created_at_ms FROM thread_items WHERE item_type IN ('userMessage','agentMessage','assistantMessage') ORDER BY thread_id, rollout_ordinal").all(),o=new Map;for(const e of n)o.has(e.thread_id)||o.set(e.thread_id,[]),o.get(e.thread_id).push(e);const i=[];for(const[s,n]of o){const o=[];let r="",a="";for(const e of n){let s;try{s=JSON.parse(e.item_json)}catch{continue}const n="userMessage"===e.item_type?"user":"assistant",i=cleanText((Array.isArray(s&&s.content)?s.content:[]).filter(e=>e&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n"));if(isNoise(i))continue;o.push({role:n,content:i.slice(0,t.maxCharsPerMessage)});const c=e.created_at_ms?new Date(e.created_at_ms).toISOString():"";c&&!r&&(r=c),c&&(a=c)}const c=finishSession({file:`${e}#${s}`,messages:o,title:"",cwd:"",foreignId:s,first:r,last:a,opts:t});c&&i.push(c)}return i}finally{s.close()}}const SQLITE_EXTRACTORS={opencode:extractOpencodeDb,codex:extractCodexThreadHistoryDb},SOURCES=[{id:"claude-code",label:"Claude Code",verified:!0,roots:e=>[path.join(e,".claude","projects")],extract:{".jsonl":extractClaudeSession}},{id:"claude-desktop",label:"Claude Desktop",verified:!1,roots:(e,t)=>appRoots(e,t,"Claude",{macSupport:!0}),extract:{".jsonl":extractClaudeSession,".json":extractJsonSessions}},{id:"codex",label:"OpenAI Codex CLI",verified:!0,roots:e=>[path.join(e,".codex","sessions")],sqlite:e=>[path.join(e,".codex","thread_history_1.sqlite"),path.join(e,".codex","history_1.sqlite")],extract:{".jsonl":extractCodexSession}},{id:"gemini-cli",label:"Gemini CLI",verified:!1,roots:e=>[path.join(e,".gemini","tmp")],extract:{".json":extractJsonSessionDoc,".jsonl":extractGenericSession}},{id:"opencode",label:"opencode",verified:!1,roots:(e,t)=>[...appRoots(e,t,"opencode",{data:!0}),path.join(e,".local","share","opencode")],sqlite:e=>[path.join(e,".local","share","opencode","opencode.db")],extract:{".json":extractJsonSessions,".jsonl":extractGenericSession}},{id:"cursor",label:"Cursor",verified:!1,roots:(e,t)=>[path.join(e,".cursor"),...appRoots(e,t,"Cursor",{macSupport:!0})],sqlite:(e,t)=>{const s="darwin"===t?path.join(e,"Library","Application Support","Cursor"):null,n=appRoots(e,t,"Cursor",{macSupport:!0})[0]||path.join(e,".cursor");return[s?path.join(s,"User","globalStorage","state.vscdb"):path.join(n,"User","globalStorage","state.vscdb")]},extract:{}},{id:"windsurf",label:"Windsurf / Codeium",verified:!1,roots:(e,t)=>[path.join(e,".windsurf"),path.join(e,".codeium"),...appRoots(e,t,"Windsurf",{config:!1,macSupport:!0})],extract:{".json":extractJsonSessions,".jsonl":extractGenericSession}},{id:"continue",label:"Continue",verified:!1,roots:e=>[path.join(e,".continue")],extract:{".json":extractJsonSessions,".jsonl":extractGenericSession}},{id:"goose",label:"Goose",verified:!1,roots:(e,t)=>appRoots(e,t,"goose",{data:!0}),sqlite:(e,t)=>appRoots(e,t,"goose",{data:!0}).map(e=>path.join(e,"sessions.db")),extract:{".json":extractJsonSessions,".jsonl":extractGenericSession}},{id:"zed",label:"Zed",verified:!1,roots:(e,t)=>appRoots(e,t,"zed"),sqlite:(e,t)=>appRoots(e,t,"zed").flatMap(e=>[path.join(e,"threads","threads.db"),path.join(e,"conversations","conversations.db")]),extract:{}},{id:"kimi-code",label:"Kimi Code",verified:!1,roots:e=>[path.join(e,".kimi-code","sessions"),path.join(e,".kimi-code","history")],extract:{".jsonl":extractGenericSession,".json":extractJsonSessionDoc}},{id:"aegiscodex",label:"AEGIS Codex engine",verified:!0,roots:e=>[path.join(e,".aegiscodex","sessions"),path.join(e,".aegiscodex","history")],extract:{".jsonl":extractGenericSession,".json":extractJsonSessionDoc}}];function sourceById(e){return SOURCES.find(t=>t.id===e)||null}function listSources(e,t){const s=homeDir(e),n=platformOf(t);return SOURCES.map(e=>{const t=e.roots(s,n).filter(isDir),o=(e.sqlite?e.sqlite(s,n):[]).filter(isFile),i=o.length>0&&"function"==typeof SQLITE_EXTRACTORS[e.id];return{id:e.id,label:e.label,verified:e.verified,roots:t,databases:o,present:t.length>0||o.length>0,readable:t.length>0||i}})}function suffixOf(e){const t=e.lastIndexOf("*");return-1===t?e:e.slice(t+1)}function extractorFor(e,t){for(const[s,n]of Object.entries(e))if(t.endsWith(suffixOf(s)))return n;return null}function scan(e={}){const t=homeDir(e.home),s=platformOf(e.platform),n=null!=e.maxSessionsPerSource?e.maxSessionsPerSource:DEFAULTS.maxSessionsPerSource,o=null!=e.limit?e.limit:1/0,i=e.sources&&e.sources.length?new Set(e.sources):null,r={minMessages:null!=e.minMessages?e.minMessages:DEFAULTS.minMessages,minChars:null!=e.minChars?e.minChars:DEFAULTS.minChars,maxCharsPerMessage:null!=e.maxCharsPerMessage?e.maxCharsPerMessage:DEFAULTS.maxCharsPerMessage,maxMessagesPerSession:null!=e.maxMessagesPerSession?e.maxMessagesPerSession:DEFAULTS.maxMessagesPerSession,maxFileBytes:null!=e.maxFileBytes?e.maxFileBytes:DEFAULTS.maxFileBytes},a=[],c=[],l=new Set;let u=0;for(const e of SOURCES){if(i&&!i.has(e.id))continue;const d=e.roots(t,s).filter(isDir),f=(e.sqlite?e.sqlite(t,s):[]).filter(isFile),p=d.length>0||f.length>0,m=Object.keys(e.extract).map(suffixOf),h=SQLITE_EXTRACTORS[e.id],g={id:e.id,label:e.label,verified:e.verified,present:p,roots:d,databases:f,files:0,scanned:0,count:0,skipped:0,unreadable:p&&!m.length&&!(f.length&&h),messages:0};if(!p){a.push(g);continue}const y=t=>{if(t.messages.length<r.minMessages)return void(g.skipped+=1);if(u+t.messages.length>DEFAULTS.maxTotalMessages)return!1;const s=stableId(e.id,t.foreignId||t.file,t.title);if(!l.has(s))return l.add(s),u+=t.messages.length,g.scanned+=1,g.count+=1,g.messages+=t.messages.length,c.push({id:s,source:e.id,sourceLabel:e.label,title:t.title,cwd:t.cwd,createdAt:t.createdAt,updatedAt:t.updatedAt,messages:t.messages,file:t.file}),!0;g.skipped+=1};if(m.length){const t=[];for(const e of d)t.push(...walkFiles(e,{ext:m,limit:DEFAULTS.maxFilesPerSource}));for(const s of t){if(g.count>=n||c.length>=o)break;if(fileSize(s)>r.maxFileBytes){g.skipped+=1;continue}const t=extractorFor(e.extract,s);if(!t)continue;let i;g.files+=1;try{i=t(s,r)}catch{g.skipped+=1;continue}const a=Array.isArray(i)?i:i?[i]:[];if(a.length)for(const e of a){if(g.count>=n||c.length>=o)break;if(!1===y(e))break}else g.skipped+=1}}if(f.length&&h)for(const e of f){if(g.count>=n||c.length>=o)break;let t;try{t=h(e,r)}catch{g.skipped+=1;continue}const s=Array.isArray(t)?t:t?[t]:[];if(g.files+=1,s.length)for(const e of s){if(g.count>=n||c.length>=o)break;if(!1===y(e))break}else g.skipped+=1}a.push(g)}return{sessions:c,sources:a,totals:{sessions:c.length,sourcesPresent:a.filter(e=>e.present).length,sourcesWithSessions:a.filter(e=>e.count>0).length,sourcesUnreadable:a.filter(e=>e.unreadable).length,files:a.reduce((e,t)=>e+t.files,0),messages:u,skipped:a.reduce((e,t)=>e+t.skipped,0)},scannedAt:(new Date).toISOString()}}function toRecord(e,{pending:t=!1}={}){const s=(Array.isArray(e.messages)?e.messages:[]).map((t,s)=>({role:"assistant"===t.role?"assistant":"user",content:String(null==t.content?"":t.content),at:0===s?e.createdAt||e.updatedAt||Date.now():void 0}));for(const e of s)null==e.at&&delete e.at;return{id:e.id,title:e.title||"imported session",messages:s,createdAt:e.createdAt||e.updatedAt||Date.now(),updatedAt:e.updatedAt||e.createdAt||Date.now(),origin:`import:${e.source}`,importedFrom:{source:e.source,label:e.sourceLabel,file:e.file,at:(new Date).toISOString()},pending:!0===t}}function chunk(e,t=50){const s=[];for(let n=0;n<e.length;n+=t)s.push(e.slice(n,n+t));return s}function describe(e){const t=(e.sources||[]).filter(e=>e.present);if(!t.length)return"No other AI tool sessions found on this machine.";const s=t.map(e=>{if(e.unreadable)return` ${e.label}: found, but its store is a database this version cannot read`;const t=e.verified?"":" (best-effort layout)";return` ${e.label}${t}: ${e.count} session(s) from ${e.files} file(s), ${e.skipped} skipped`});return[`Found ${e.totals.sessions} importable session(s) across ${e.totals.sourcesWithSessions} source(s):`,...s].join("\n")}module.exports={DEFAULTS:DEFAULTS,SOURCES:SOURCES,scan:scan,listSources:listSources,describe:describe,chunk:chunk,toRecord:toRecord,stableId:stableId,sourceById:sourceById,_internal:{walkFiles:walkFiles,readJsonl:readJsonl,cleanText:cleanText,isNoise:isNoise,finishSession:finishSession,extractClaudeSession:extractClaudeSession,extractCodexSession:extractCodexSession,extractGenericSession:extractGenericSession,extractJsonSessions:extractJsonSessions,extractJsonSessionDoc:extractJsonSessionDoc,extractorFor:extractorFor,suffixOf:suffixOf,platformOf:platformOf,appRoots:appRoots}};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const http=require("node:http"),{URL:URL}=require("node:url");function escapeHtml(e){return String(null==e?"":e).replace(/[&<>"']/g,
|
|
3
|
+
"use strict";const http=require("node:http"),{URL:URL}=require("node:url");function escapeHtml(e){return String(null==e?"":e).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"}[e]))}function page({ok:e,error:t,username:r,surface:n}){const a=e?"Signed in":"Sign-in failed",o="app"===n?"the app":"the terminal";return`<!doctype html><html><head><meta charset="utf-8"><title>${a} — AEGIS</title></head><body style="font:16px sans-serif;max-width:32rem;margin:4rem auto;text-align:center;"><h2>${a}</h2><p>${e?`Signed in${r?` as <b>${escapeHtml(r)}</b>`:""}. You can close this tab and return to ${o}.`:`Sign-in failed: ${escapeHtml(t||"no token was returned")}. You can close this tab and try again.`}</p></body></html>`}function buildAuthUrl(e,t,{fingerprint:r,app:n}={}){const a=new URL("/auth/google",e);return a.searchParams.set("callback",t),r&&a.searchParams.set("fingerprint",String(r)),n&&a.searchParams.set("app",String(n)),a.toString()}async function startGoogleSignIn({apiBase:e,host:t="127.0.0.1",timeoutMs:r=3e5,surface:n="terminal",fingerprint:a=null,app:o=null}={}){if(!e)throw new Error("startGoogleSignIn requires apiBase");let i,s,l=!1;const u=new Promise((e,t)=>{i=e,s=t}),c=http.createServer((e,r)=>{let a;try{a=new URL(e.url,`http://${t}`)}catch{return void r.writeHead(400).end()}const o=a.searchParams.get("token"),u=a.searchParams.get("username"),p=a.searchParams.get("memory_token"),h=a.searchParams.get("error");o||h?(r.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),r.end(page({ok:Boolean(o),error:h,username:u,surface:n})),l||(l=!0,clearTimeout(m),c.close(),o?i({apiKey:o,username:u||null,memoryToken:p||null}):s(new Error(h||"no token was returned")))):r.writeHead(404).end()});await new Promise((e,r)=>{c.once("error",r),c.listen(0,t,e)});const{port:p}=c.address(),h=buildAuthUrl(e,`http://${t}:${p}`,{fingerprint:a,app:o}),m=setTimeout(()=>{l||(l=!0,c.close(),s(new Error(`timed out after ${Math.round(r/1e3)}s waiting for the browser sign-in`)))},r);return"function"==typeof m.unref&&m.unref(),{url:h,wait:()=>u}}module.exports={startGoogleSignIn:startGoogleSignIn,buildAuthUrl:buildAuthUrl};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),SETTINGS_DIRS=[".aegis",".aegiscode"];function hookSettingPaths(o={}){const e=platformPath(o.platform),t=homeDir(o),n=o.cwd||process.cwd(),s=[];for(const o of SETTINGS_DIRS)s.push(e.join(t,o,"settings.json")),s.push(e.join(n,o,"settings.json"));return s.push(e.join(t,".claude","settings.json")),dedupe(s)}function platformPath(o){return"win32"===(o||process.platform)?path.win32:path.posix}function homeDir(o={}){if(o.home)return String(o.home);const e=o.env||process.env,t="win32"===(o.platform||process.platform)?["USERPROFILE","HOME"]:["HOME","USERPROFILE"];for(const o of t)if(e&&e[o])return String(e[o]);return os.homedir()}function hookSourceKind(o){const e=path.posix.basename(String(o).replace(/\\/g,"/")),t=path.posix.basename(path.posix.dirname(String(o).replace(/\\/g,"/")));return"settings.json"!==e?"other":".claude"===t?"foreign":SETTINGS_DIRS.includes(t)?"aegis":"other"}function dedupe(o){const e=new Set,t=[];for(const n of o){const o=String(n).replace(/\\/g,"/");e.has(o)||(e.add(o),t.push(n))}return t}function shorten(o,e={}){const t=homeDir(e),n=String(o);if(!t)return n;const s=n.replace(/\\/g,"/"),r=String(t).replace(/\\/g,"/").replace(/\/+$/,"");return s===r?"~":s.startsWith(`${r}/`)?`~${s.slice(r.length)}`:n}function readHookConfig(o={}){const e=o.readFile||defaultReadFile,t=o.paths||hookSettingPaths(o),n={},s=[],r=[],i=[];for(const a of t){let t,c=null;try{c=e(a)}catch{c=null}if(null==c){i.push({path:a,exists:!1,kind:hookSourceKind(a)});continue}try{t=JSON.parse(String(c))}catch{i.push({path:a,exists:!0,parsed:!1,kind:hookSourceKind(a)});continue}const h=hookSourceKind(a),u=eventsOf(t),d=Object.keys(u);if(i.push({path:a,exists:!0,parsed:!0,kind:h,events:d}),"foreign"!==h){if(d.length){s.push(shorten(a,o));for(const[o,e]of Object.entries(u))Array.isArray(e)&&e.length&&(n[o]=[...n[o]||[],...e])}}else r.push(shorten(a,o))}return{hooks:n,from:s,foreign:r,files:i}}function eventsOf(o){if(!o||"object"!=typeof o)return{};if(o.hooks&&"object"==typeof o.hooks&&!Array.isArray(o.hooks)){const e={};for(const[t,n]of Object.entries(o.hooks))Array.isArray(n)&&(e[t]=n);return e}const e={};for(const t of HOOK_EVENTS)Array.isArray(o[t])&&(e[t]=o[t]);return e}const HOOK_EVENTS=["PreToolUse","PostToolUse","PostToolUseFailure","PermissionRequest","UserPromptSubmit","SessionStart","SessionEnd","Stop","SubagentStop","Notification","Compaction"];function hookStats(o){const e=o&&"object"==typeof o?o:{},t=Object.keys(e);let n=0;const s={};for(const o of t){const t=Array.isArray(e[o])?e[o]:[];s[o]=t.length,n+=t.length}return{enabled:n>0,hooks:n,events:t,byEvent:s}}const REQUIRED_HOOKS=["pre-commit","pre-push"],OPTIONAL_HOOKS=["post-merge","lib-gate.sh","push-policy"];function defaultRunGit(o,{cwd:e,env:t}={}){try{const n=execFileSync("git",o,{cwd:e,env:t||process.env,encoding:"utf8",stdio:["ignore","pipe","pipe"],windowsHide:!0});return{ok:!0,out:String(n).trim(),err:""}}catch(o){return{ok:!1,out:String(o&&o.stdout?o.stdout:"").trim(),err:String(o&&o.stderr?o.stderr:o&&o.message||o).trim()}}}function defaultReadFile(o){return fs.readFileSync(o,"utf8")}function defaultExists(o){try{return fs.statSync(o).isFile()}catch{return!1}}function defaultChmod(o){fs.chmodSync(o,493)}function repoHookStatus(o={}){const e=o.platform||process.platform,t=platformPath(e),n=o.cwd||process.cwd(),s=o.exists||defaultExists,r=o.runGit||defaultRunGit,i=t.join(n,".githooks"),a=[],c=[];for(const o of[...REQUIRED_HOOKS,...OPTIONAL_HOOKS])s(t.join(i,o))?a.push(o):c.push(o);const h=r(["rev-parse","--is-inside-work-tree"],{cwd:n,env:o.env}),u=h.ok&&"true"===h.out;let d=null;if(u){const e=r(["config","--get","core.hooksPath"],{cwd:n,env:o.env});d=e.ok&&e.out?e.out:null}const f=".githooks";var l;return{repo:n,hooksDir:i,platform:e,inGitRepo:u,configured:d,wanted:f,installed:u&&(null==(l=d)?null:String(l).replace(/\\/g,"/").replace(/\/+$/,""))===f,present:a,missing:c,execBit:"win32"!==e,execNote:"win32"===e?"Windows: the exec bit is not enforced and not needed — git for Windows runs hooks with its bundled sh.":"POSIX: the hooks are chmod 0755 so git can execute them."}}function installRepoHooks(o={}){const e=o.platform||process.platform,t=platformPath(e),n=o.cwd||process.cwd(),s=o.runGit||defaultRunGit,r=o.exists||defaultExists,i=o.chmod||defaultChmod,a=Boolean(o.dryRun),c=repoHookStatus({...o,platform:e,cwd:n,runGit:s,exists:r}),h=[];if(!r(t.join(c.hooksDir,"pre-commit")))return{ok:!1,changed:!1,code:"no-hooks",actions:h,status:c,error:`no ${c.wanted}/pre-commit under ${n} — nothing to install. A tree that never had the hooks needs them restored (\`git checkout -- .githooks/\`) or created (\`agent-gate.mjs init --hooks\`).`};if(!c.inGitRepo)return{ok:!1,changed:!1,code:"no-git",actions:h,status:c,error:`${n} is not inside a git work tree (core.hooksPath is a per-repo setting), or git is not on PATH.`};if(!c.installed&&(h.push(`git -C ${n} config core.hooksPath ${c.wanted}`),!a)){const e=s(["config","core.hooksPath",c.wanted],{cwd:n,env:o.env});if(!e.ok)return{ok:!1,changed:!1,code:"git-failed",actions:h,status:c,error:`git config refused: ${e.err||"unknown error"}`};const t=s(["config","--get","core.hooksPath"],{cwd:n,env:o.env}),r=t.ok?String(t.out).replace(/\\/g,"/").replace(/\/+$/,""):null;if(r!==c.wanted)return{ok:!1,changed:!0,code:"verify-failed",actions:h,status:c,error:`core.hooksPath reads back as "${r||"(unset)"}", not "${c.wanted}"`}}const u=[];if("win32"!==e){const n=o.modeOf||(o=>{try{return 511&fs.statSync(o).mode}catch{return null}});for(const o of c.present.filter(
|
|
3
|
+
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),SETTINGS_DIRS=[".aegis",".aegiscode"];function hookSettingPaths(o={}){const e=platformPath(o.platform),t=homeDir(o),n=o.cwd||process.cwd(),s=[];for(const o of SETTINGS_DIRS)s.push(e.join(t,o,"settings.json")),s.push(e.join(n,o,"settings.json"));return s.push(e.join(t,".claude","settings.json")),dedupe(s)}function platformPath(o){return"win32"===(o||process.platform)?path.win32:path.posix}function homeDir(o={}){if(o.home)return String(o.home);const e=o.env||process.env,t="win32"===(o.platform||process.platform)?["USERPROFILE","HOME"]:["HOME","USERPROFILE"];for(const o of t)if(e&&e[o])return String(e[o]);return os.homedir()}function hookSourceKind(o){const e=path.posix.basename(String(o).replace(/\\/g,"/")),t=path.posix.basename(path.posix.dirname(String(o).replace(/\\/g,"/")));return"settings.json"!==e?"other":".claude"===t?"foreign":SETTINGS_DIRS.includes(t)?"aegis":"other"}function dedupe(o){const e=new Set,t=[];for(const n of o){const o=String(n).replace(/\\/g,"/");e.has(o)||(e.add(o),t.push(n))}return t}function shorten(o,e={}){const t=homeDir(e),n=String(o);if(!t)return n;const s=n.replace(/\\/g,"/"),r=String(t).replace(/\\/g,"/").replace(/\/+$/,"");return s===r?"~":s.startsWith(`${r}/`)?`~${s.slice(r.length)}`:n}function readHookConfig(o={}){const e=o.readFile||defaultReadFile,t=o.paths||hookSettingPaths(o),n={},s=[],r=[],i=[];for(const a of t){let t,c=null;try{c=e(a)}catch{c=null}if(null==c){i.push({path:a,exists:!1,kind:hookSourceKind(a)});continue}try{t=JSON.parse(String(c))}catch{i.push({path:a,exists:!0,parsed:!1,kind:hookSourceKind(a)});continue}const h=hookSourceKind(a),u=eventsOf(t),d=Object.keys(u);if(i.push({path:a,exists:!0,parsed:!0,kind:h,events:d}),"foreign"!==h){if(d.length){s.push(shorten(a,o));for(const[o,e]of Object.entries(u))Array.isArray(e)&&e.length&&(n[o]=[...n[o]||[],...e])}}else r.push(shorten(a,o))}return{hooks:n,from:s,foreign:r,files:i}}function eventsOf(o){if(!o||"object"!=typeof o)return{};if(o.hooks&&"object"==typeof o.hooks&&!Array.isArray(o.hooks)){const e={};for(const[t,n]of Object.entries(o.hooks))Array.isArray(n)&&(e[t]=n);return e}const e={};for(const t of HOOK_EVENTS)Array.isArray(o[t])&&(e[t]=o[t]);return e}const HOOK_EVENTS=["PreToolUse","PostToolUse","PostToolUseFailure","PermissionRequest","UserPromptSubmit","SessionStart","SessionEnd","Stop","SubagentStop","Notification","Compaction"];function hookStats(o){const e=o&&"object"==typeof o?o:{},t=Object.keys(e);let n=0;const s={};for(const o of t){const t=Array.isArray(e[o])?e[o]:[];s[o]=t.length,n+=t.length}return{enabled:n>0,hooks:n,events:t,byEvent:s}}const REQUIRED_HOOKS=["pre-commit","pre-push"],OPTIONAL_HOOKS=["post-merge","lib-gate.sh","push-policy"];function defaultRunGit(o,{cwd:e,env:t}={}){try{const n=execFileSync("git",o,{cwd:e,env:t||process.env,encoding:"utf8",stdio:["ignore","pipe","pipe"],windowsHide:!0});return{ok:!0,out:String(n).trim(),err:""}}catch(o){return{ok:!1,out:String(o&&o.stdout?o.stdout:"").trim(),err:String(o&&o.stderr?o.stderr:o&&o.message||o).trim()}}}function defaultReadFile(o){return fs.readFileSync(o,"utf8")}function defaultExists(o){try{return fs.statSync(o).isFile()}catch{return!1}}function defaultChmod(o){fs.chmodSync(o,493)}function repoHookStatus(o={}){const e=o.platform||process.platform,t=platformPath(e),n=o.cwd||process.cwd(),s=o.exists||defaultExists,r=o.runGit||defaultRunGit,i=t.join(n,".githooks"),a=[],c=[];for(const o of[...REQUIRED_HOOKS,...OPTIONAL_HOOKS])s(t.join(i,o))?a.push(o):c.push(o);const h=r(["rev-parse","--is-inside-work-tree"],{cwd:n,env:o.env}),u=h.ok&&"true"===h.out;let d=null;if(u){const e=r(["config","--get","core.hooksPath"],{cwd:n,env:o.env});d=e.ok&&e.out?e.out:null}const f=".githooks";var l;return{repo:n,hooksDir:i,platform:e,inGitRepo:u,configured:d,wanted:f,installed:u&&(null==(l=d)?null:String(l).replace(/\\/g,"/").replace(/\/+$/,""))===f,present:a,missing:c,execBit:"win32"!==e,execNote:"win32"===e?"Windows: the exec bit is not enforced and not needed — git for Windows runs hooks with its bundled sh.":"POSIX: the hooks are chmod 0755 so git can execute them."}}function installRepoHooks(o={}){const e=o.platform||process.platform,t=platformPath(e),n=o.cwd||process.cwd(),s=o.runGit||defaultRunGit,r=o.exists||defaultExists,i=o.chmod||defaultChmod,a=Boolean(o.dryRun),c=repoHookStatus({...o,platform:e,cwd:n,runGit:s,exists:r}),h=[];if(!r(t.join(c.hooksDir,"pre-commit")))return{ok:!1,changed:!1,code:"no-hooks",actions:h,status:c,error:`no ${c.wanted}/pre-commit under ${n} — nothing to install. A tree that never had the hooks needs them restored (\`git checkout -- .githooks/\`) or created (\`agent-gate.mjs init --hooks\`).`};if(!c.inGitRepo)return{ok:!1,changed:!1,code:"no-git",actions:h,status:c,error:`${n} is not inside a git work tree (core.hooksPath is a per-repo setting), or git is not on PATH.`};if(!c.installed&&(h.push(`git -C ${n} config core.hooksPath ${c.wanted}`),!a)){const e=s(["config","core.hooksPath",c.wanted],{cwd:n,env:o.env});if(!e.ok)return{ok:!1,changed:!1,code:"git-failed",actions:h,status:c,error:`git config refused: ${e.err||"unknown error"}`};const t=s(["config","--get","core.hooksPath"],{cwd:n,env:o.env}),r=t.ok?String(t.out).replace(/\\/g,"/").replace(/\/+$/,""):null;if(r!==c.wanted)return{ok:!1,changed:!0,code:"verify-failed",actions:h,status:c,error:`core.hooksPath reads back as "${r||"(unset)"}", not "${c.wanted}"`}}const u=[];if("win32"!==e){const n=o.modeOf||(o=>{try{return 511&fs.statSync(o).mode}catch{return null}});for(const o of c.present.filter(o=>"push-policy"!==o)){const s=t.join(c.hooksDir,o);if(493!==n(s))if(a)u.push(`chmod 0755 ${s}`);else try{i(s,493),u.push(`chmod 0755 ${o}`)}catch(e){u.push(`chmod 0755 ${o} FAILED: ${e&&e.message||e}`)}}h.push(...u)}return d={modes:u,note:c.execNote},{ok:!0,changed:h.length>0,code:"installed",actions:h,status:c,...d};var d}function hooksSummary(o={}){const e=o.platform||process.platform,t=o.config||readHookConfig({...o,platform:e}),n=o.stats||hookStats(t.hooks),s=o.repo||repoHookStatus({...o,platform:e}),r=[];if(r.push(`hooks: ${n.enabled?"enabled":"disabled"} · ${n.hooks} matcher(s) in ${n.events.length} event(s)`),n.events.length)for(const o of n.events)r.push(` ${o}: ${n.byEvent[o]}`);else r.push(" (no settings.json declares hooks — checked "+hookSettingPaths({...o,platform:e}).map(e=>shorten(e,o)).join(", ")+")");return t.from.length&&r.push(` from: ${t.from.join(", ")}`),t.foreign&&t.foreign.length&&r.push(` foreign host files (read, listed—${n.hooks&&t.foreign.length?"may outrank ours":"no hooks"}): ${t.foreign.join(", ")}`),r.push(""),r.push(`repo guard hooks (${s.wanted}/): ${s.present.length?s.present.join(", "):"none found"}`),s.missing.length&&r.push(` missing: ${s.missing.join(", ")}`),r.push(" core.hooksPath: "+(s.installed?`${s.wanted} (installed)`:`${s.configured||"(unset)"} — NOT installed, so a commit runs NO guard hooks`)),r.push(` ${s.execNote}`),r.join("\n")}module.exports={HOOK_EVENTS:HOOK_EVENTS,SETTINGS_DIRS:SETTINGS_DIRS,hooksSummary:hooksSummary,REQUIRED_HOOKS:REQUIRED_HOOKS,OPTIONAL_HOOKS:OPTIONAL_HOOKS,hookSettingPaths:hookSettingPaths,hookSourceKind:hookSourceKind,homeDir:homeDir,platformPath:platformPath,shorten:shorten,readHookConfig:readHookConfig,hookStats:hookStats,repoHookStatus:repoHookStatus,installRepoHooks:installRepoHooks};
|