aegisone 1.0.64 → 1.0.65
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/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/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.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/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/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/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/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/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 +22 -0
- 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.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/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 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};
|
|
@@ -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{sanitizeModel:sanitizeModel}=require("./user-models.js"),DISCOVERY_TIMEOUT_MS=8e3;function bearer(e){return{authorization:`Bearer ${e}`}}const ENDPOINTS=Object.freeze({anthropic:Object.freeze({url:"https://api.anthropic.com/v1/models",headers:e=>({"x-api-key":e,"anthropic-version":"2023-06-01"}),note:"the vendor requires anthropic-version; the console key is sent as x-api-key"}),openai:Object.freeze({url:"https://api.openai.com/v1/models",headers:bearer,note:"OpenAI-compatible: { data: [ { id } ] }"}),deepseek:Object.freeze({url:"https://api.deepseek.com/models",headers:bearer,note:"OpenAI-compatible; /v1/models answers the same list"}),grok:Object.freeze({url:"https://api.x.ai/v1/models",headers:bearer,note:"xAI answers on /v1/models under the vendor id grok"}),gemini:Object.freeze({url:"https://generativelanguage.googleapis.com/v1beta/models",headers:()=>({}),query:e=>({key:e}),note:'the key travels in the query string; ids come back as "models/<id>"'}),groq:Object.freeze({url:"https://api.groq.com/openai/v1/models",headers:bearer,note:"OpenAI-compatible under /openai/v1"}),mistral:Object.freeze({url:"https://api.mistral.ai/v1/models",headers:bearer,note:"OpenAI-compatible"}),openrouter:Object.freeze({url:"https://openrouter.ai/api/v1/models",headers:bearer,note:'OpenAI-compatible; ids are prefixed "vendor/model"'}),together:Object.freeze({url:"https://api.together.xyz/v1/models",headers:bearer,note:"OpenAI-compatible"}),cerebras:Object.freeze({url:"https://api.cerebras.ai/v1/models",headers:bearer,note:"OpenAI-compatible under /v1"}),fireworks:Object.freeze({url:"https://api.fireworks.ai/inference/v1/models",headers:bearer,note:'OpenAI-compatible under /inference/v1; ids are "accounts/fireworks/models/<id>"'}),nvidia_nim:Object.freeze({url:"https://integrate.api.nvidia.com/v1/models",headers:bearer,note:'OpenAI-compatible; ids are "<vendor>/<model>"'}),sakana:Object.freeze({url:"https://api.sakana.ai/v1/models",headers:bearer,note:"OpenAI-compatible under /v1"})}),ALIASES=Object.freeze({"x.ai":"grok",xai:"grok",google:"gemini","google-ai":"gemini",googleai:"gemini","open-ai":"openai","deep-seek":"deepseek","openai-gpt4o-mini":"openai","anthropic-haiku":"anthropic"}),NON_CHAT_RE=/embed|whisper|\btts\b|dall-e|moderation|rerank|imagen|\bveo\b|\baqa\b|transcribe|audio|speech|synthia|guard-content/i;function endpointFor(e){const r=String(null==e?"":e).trim().toLowerCase();if(!r)return null;const o=ALIASES[r]||r,t=ENDPOINTS[o];return t?Object.freeze({id:o,...t}):null}function canDiscover(e){return Boolean(endpointFor(e))}function discoverableProviders(){return Object.keys(ENDPOINTS).sort()}function looksNonChat(e){return NON_CHAT_RE.test(String(e))}function idsFromPayload(e){const r=Array.isArray(e)?e:Array.isArray(e&&e.data)?e.data:Array.isArray(e&&e.models)?e.models:null;if(!r)return null;const o=[],t=[];for(const e of r){if(null==e)continue;const r="string"==typeof e?e:e.id||e.name||e.model;if("string"!=typeof r||!r.trim())continue;const n=r.trim().replace(/^models\//,""),i=e&&Array.isArray(e.supportedGenerationMethods)?e.supportedGenerationMethods:e&&Array.isArray(e.supported_actions)?e.supported_actions:null,s=i?i.includes("generateContent")||i.includes("generate"):null;let a;try{a=sanitizeModel(n)}catch{continue}!1===s||null===s&&looksNonChat(a)?t.push(a):o.push(a)}const n=e=>[...new Set(e)];return{ids:n(o),others:n(t).filter(
|
|
3
|
+
"use strict";const{sanitizeModel:sanitizeModel}=require("./user-models.js"),DISCOVERY_TIMEOUT_MS=8e3;function bearer(e){return{authorization:`Bearer ${e}`}}const ENDPOINTS=Object.freeze({anthropic:Object.freeze({url:"https://api.anthropic.com/v1/models",headers:e=>({"x-api-key":e,"anthropic-version":"2023-06-01"}),note:"the vendor requires anthropic-version; the console key is sent as x-api-key"}),openai:Object.freeze({url:"https://api.openai.com/v1/models",headers:bearer,note:"OpenAI-compatible: { data: [ { id } ] }"}),deepseek:Object.freeze({url:"https://api.deepseek.com/models",headers:bearer,note:"OpenAI-compatible; /v1/models answers the same list"}),grok:Object.freeze({url:"https://api.x.ai/v1/models",headers:bearer,note:"xAI answers on /v1/models under the vendor id grok"}),gemini:Object.freeze({url:"https://generativelanguage.googleapis.com/v1beta/models",headers:()=>({}),query:e=>({key:e}),note:'the key travels in the query string; ids come back as "models/<id>"'}),groq:Object.freeze({url:"https://api.groq.com/openai/v1/models",headers:bearer,note:"OpenAI-compatible under /openai/v1"}),mistral:Object.freeze({url:"https://api.mistral.ai/v1/models",headers:bearer,note:"OpenAI-compatible"}),openrouter:Object.freeze({url:"https://openrouter.ai/api/v1/models",headers:bearer,note:'OpenAI-compatible; ids are prefixed "vendor/model"'}),together:Object.freeze({url:"https://api.together.xyz/v1/models",headers:bearer,note:"OpenAI-compatible"}),cerebras:Object.freeze({url:"https://api.cerebras.ai/v1/models",headers:bearer,note:"OpenAI-compatible under /v1"}),fireworks:Object.freeze({url:"https://api.fireworks.ai/inference/v1/models",headers:bearer,note:'OpenAI-compatible under /inference/v1; ids are "accounts/fireworks/models/<id>"'}),nvidia_nim:Object.freeze({url:"https://integrate.api.nvidia.com/v1/models",headers:bearer,note:'OpenAI-compatible; ids are "<vendor>/<model>"'}),sakana:Object.freeze({url:"https://api.sakana.ai/v1/models",headers:bearer,note:"OpenAI-compatible under /v1"})}),ALIASES=Object.freeze({"x.ai":"grok",xai:"grok",google:"gemini","google-ai":"gemini",googleai:"gemini","open-ai":"openai","deep-seek":"deepseek","openai-gpt4o-mini":"openai","anthropic-haiku":"anthropic"}),NON_CHAT_RE=/embed|whisper|\btts\b|dall-e|moderation|rerank|imagen|\bveo\b|\baqa\b|transcribe|audio|speech|synthia|guard-content/i;function endpointFor(e){const r=String(null==e?"":e).trim().toLowerCase();if(!r)return null;const o=ALIASES[r]||r,t=ENDPOINTS[o];return t?Object.freeze({id:o,...t}):null}function canDiscover(e){return Boolean(endpointFor(e))}function discoverableProviders(){return Object.keys(ENDPOINTS).sort()}function looksNonChat(e){return NON_CHAT_RE.test(String(e))}function idsFromPayload(e){const r=Array.isArray(e)?e:Array.isArray(e&&e.data)?e.data:Array.isArray(e&&e.models)?e.models:null;if(!r)return null;const o=[],t=[];for(const e of r){if(null==e)continue;const r="string"==typeof e?e:e.id||e.name||e.model;if("string"!=typeof r||!r.trim())continue;const n=r.trim().replace(/^models\//,""),i=e&&Array.isArray(e.supportedGenerationMethods)?e.supportedGenerationMethods:e&&Array.isArray(e.supported_actions)?e.supported_actions:null,s=i?i.includes("generateContent")||i.includes("generate"):null;let a;try{a=sanitizeModel(n)}catch{continue}!1===s||null===s&&looksNonChat(a)?t.push(a):o.push(a)}const n=e=>[...new Set(e)];return{ids:n(o),others:n(t).filter(e=>!o.includes(e))}}async function discoverModels(e,r={}){const o=endpointFor(e),t=String(null==e?"":e).trim().toLowerCase(),n=String(null==r.key?"":r.key).trim();if(!o)return{ok:!1,provider:t,supported:!1,error:`${t||"that provider"} has no model-list endpoint this client knows`};if(!n)return{ok:!1,provider:o.id,supported:!0,error:`no ${o.id} key on this machine`};const i=r.fetchImpl||("function"==typeof fetch?fetch:null);if(!i)return{ok:!1,provider:o.id,supported:!0,error:"no fetch implementation available"};const s=Number.isFinite(r.timeoutMs)?r.timeoutMs:8e3,a="function"==typeof AbortController?new AbortController:null,d=a?setTimeout(()=>a.abort(),s):null,l=()=>a&&a.abort();a&&r.signal&&(r.signal.aborted?l():"function"==typeof r.signal.addEventListener&&r.signal.addEventListener("abort",l,{once:!0}));try{const r=new URL(o.url);if("function"==typeof o.query)for(const[e,t]of Object.entries(o.query(n)||{}))r.searchParams.set(e,t);const t={accept:"application/json"};for(const[e,r]of Object.entries(o.headers(n)||{}))t["authorization"===e?"Authorization":e]=r;const s=await i(r.toString(),{method:"GET",headers:t,signal:a?a.signal:void 0}),d=s&&"number"==typeof s.status?s.status:0;if(!s||"boolean"==typeof s.ok&&!s.ok){const e=401===d||403===d?`the vendor refused the key (HTTP ${d})`:404===d?`the vendor has no model list at ${r.pathname} (HTTP 404)`:`the vendor answered HTTP ${d||"nothing"}`;return{ok:!1,provider:o.id,supported:!0,status:d,error:e}}let l;try{l=await s.json()}catch(e){return{ok:!1,provider:o.id,supported:!0,status:d,error:`the vendor's reply was not JSON (${e&&e.message||e})`}}const c=idsFromPayload(l);return c?{ok:!0,provider:o.id,endpoint:o.url,ids:c.ids,others:c.others,count:c.ids.length}:{ok:!1,provider:o.id,supported:!0,status:d,error:'the vendor answered in a shape this client does not know (no "data" or "models" list)'}}catch(e){const r=e&&("AbortError"===e.name||"ABORT_ERR"===e.code)||a&&a.signal.aborted;return{ok:!1,provider:o.id,supported:!0,error:r?`the vendor did not answer within ${s} ms`:`could not reach the vendor (${e&&e.message||e})`}}finally{d&&clearTimeout(d),a&&r.signal&&"function"==typeof r.signal.removeEventListener&&r.signal.removeEventListener("abort",l)}}module.exports={DISCOVERY_TIMEOUT_MS:8e3,ENDPOINTS:ENDPOINTS,ALIASES:ALIASES,NON_CHAT_RE:NON_CHAT_RE,endpointFor:endpointFor,canDiscover:canDiscover,discoverableProviders:discoverableProviders,looksNonChat:looksNonChat,idsFromPayload:idsFromPayload,discoverModels:discoverModels};
|
|
@@ -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{canDiscover:canDiscover,discoverableProviders:discoverableProviders,discoverModels:discoverModels}=require("./model-discovery.js"),{addUserModel:addUserModel,MAX_MODELS_PER_PROVIDER:MAX_MODELS_PER_PROVIDER}=require("./user-models.js");function modelIdsOf(r){return(Array.isArray(r&&r.models)?r.models:[]).map(
|
|
3
|
+
"use strict";const{canDiscover:canDiscover,discoverableProviders:discoverableProviders,discoverModels:discoverModels}=require("./model-discovery.js"),{addUserModel:addUserModel,MAX_MODELS_PER_PROVIDER:MAX_MODELS_PER_PROVIDER}=require("./user-models.js");function modelIdsOf(r){return(Array.isArray(r&&r.models)?r.models:[]).map(r=>"string"==typeof r?r:r&&r.id).map(r=>"string"==typeof r?r.trim():"").filter(Boolean)}function providerArray(r){return Array.isArray(r)?r:Array.isArray(r&&r.providers)?r.providers:[]}function askableProviders(r,e){const o=String(null==e?"":e).trim().toLowerCase(),i=[],s=new Set;for(const e of providerArray(r)){const r="string"==typeof e.id?e.id.trim().toLowerCase():"";r&&!s.has(r)&&(o&&r!==o||canDiscover(r)&&(s.add(r),i.push(r)))}return i}function diffProvider(r,e,o){const i=Array.isArray(e)?e:[],s=Array.isArray(o)?o:[],d=new Set(i.map(r=>String(r).trim()).filter(Boolean)),n=new Set(s.map(r=>String(r).trim()).filter(Boolean)),t=[];for(const r of n)d.has(r)||t.push(r);const a=[];for(const r of d)n.has(r)||a.push(r);return{provider:r,missing:t,stale:a,offered:d.size,issued:n.size}}async function plan(r,e={}){const o=providerArray(r),i=askableProviders(o,e.only),s={ok:!1,providers:[],skipped:[],failed:[],missing:0,stale:0,askable:i,known:discoverableProviders()};if(!i.length)return s.skipped=[{provider:String(e.only||"").trim()||"(any)",reason:"nothing to ask — this client has no list endpoint for the provider(s) listed"}],s;const d=e.keys&&"object"==typeof e.keys?e.keys:{};for(const r of i){const i="string"==typeof d[r]?d[r].trim():"";if(!i){s.skipped.push({provider:r,reason:"no key on this machine"});continue}let n;try{n=await discoverModels(r,{key:i,fetchImpl:e.fetchImpl,signal:e.signal,timeoutMs:e.timeoutMs})}catch(e){n={ok:!1,provider:r,error:e&&e.message||String(e)}}if(!n||!n.ok){s.failed.push({provider:r,error:n&&n.error||"no answer"});continue}const t=o.find(e=>e&&"string"==typeof e.id&&e.id.trim().toLowerCase()===r)||{},a=diffProvider(r,modelIdsOf(t),n.ids);a.endpoint=n.endpoint||"",a.notChat=Array.isArray(n.others)?n.others.length:0,s.providers.push(a),s.missing+=a.missing.length,s.stale+=a.stale.length}return s.ok=s.providers.length>0,s.ok||s.failed.length||!s.skipped.length||(s.error=s.skipped.map(r=>`${r.provider}: ${r.reason}`).join("; ")),s}function apply(r,e={}){const o={added:0,already:0,capped:0,failed:[],providers:[]},i=r&&Array.isArray(r.providers)?r.providers:[],s=String(null==e.only?"":e.only).trim().toLowerCase();for(const d of i){if(!d||!d.provider)continue;if(s&&d.provider.toLowerCase()!==s)continue;const i=Array.isArray(d.missing)?d.missing:[];if(!i.length)continue;const n={provider:d.provider,added:0,already:0,capped:0,failed:[]};for(const o of i)try{addUserModel(d.provider,o,e).added?n.added+=1:n.already+=1}catch(r){const e=r&&r.message||String(r);if(/the cap/.test(e)){n.capped=i.length-n.added-n.already-n.failed.length;break}n.failed.push({id:o,reason:e})}o.added+=n.added,o.already+=n.already,o.capped+=n.capped,o.failed.push(...n.failed.map(r=>({provider:d.provider,...r}))),o.providers.push(n)}return o}function summary(r){const e=r||{},o=Number(e.missing)||0,i=Number(e.stale)||0,s=Array.isArray(e.providers)?e.providers.length:0;return s?o?`checked ${s} provider(s): ${o} model id(s) the vendor issues and this machine does not offer${i?`, ${i} listed here the vendor no longer issues`:""}.`:`checked ${s} provider(s): nothing new${i?`, ${i} listed here that the vendor no longer issues`:""}.`:`could not check any provider — ${Array.isArray(e.failed)&&e.failed.length?e.failed.map(r=>`${r.provider}: ${r.error}`).join("; "):e.error||"no provider answered"}`}module.exports={MAX_MODELS_PER_PROVIDER:MAX_MODELS_PER_PROVIDER,modelIdsOf:modelIdsOf,askableProviders:askableProviders,diffProvider:diffProvider,plan:plan,apply:apply,summary:summary};
|
|
@@ -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 GENERIC_TITLE="New conversation",TITLE_SYSTEM='You name conversations. Write a short descriptive title (2 to 6 words) that captures the topic of the conversation. Never repeat the user\'s words verbatim — if the message is just a greeting or has no clear topic, name it something like "New conversation". Sentence case, no quotes, no markdown, no trailing punctuation, no explanation.',isGenericTitle=e=>!e||String(e).trim().toLowerCase()===GENERIC_TITLE.toLowerCase(),GREETINGS=new Set(["hey","heey","heyy","heyyy","hi","hii","hello","hej","hejj","yo","sup","hola","howdy","hai","heyo","hiya","wassup","greetings","namaste","ahoy","hallo"]);function isTopicless(e){const t=String(e).trim().toLowerCase().replace(/[^a-z0-9\s]/g," ").replace(/\s+/g," ").trim();if(!t)return!0;const i=t.split(" ");return!!/^(good (morning|afternoon|evening)|whats up|wassup|hey there|hello there|hi there|how are you)\b/.test(t)||i.length<=2&&t.length<=12&&GREETINGS.has(i[0])}function looksLikeEcho(e,t){const i=e=>String(e).toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim(),n=i(e),r=i(t);if(!n||!r)return!1;if(n===r)return!0;if(r.length<=14&&(n.startsWith(r)||r.startsWith(n)))return!0;if(r.length<=24){const i=e=>new Set((String(e).toLowerCase().match(/[a-z0-9]+/g)||[]).filter(
|
|
3
|
+
"use strict";const GENERIC_TITLE="New conversation",TITLE_SYSTEM='You name conversations. Write a short descriptive title (2 to 6 words) that captures the topic of the conversation. Never repeat the user\'s words verbatim — if the message is just a greeting or has no clear topic, name it something like "New conversation". Sentence case, no quotes, no markdown, no trailing punctuation, no explanation.',isGenericTitle=e=>!e||String(e).trim().toLowerCase()===GENERIC_TITLE.toLowerCase(),GREETINGS=new Set(["hey","heey","heyy","heyyy","hi","hii","hello","hej","hejj","yo","sup","hola","howdy","hai","heyo","hiya","wassup","greetings","namaste","ahoy","hallo"]);function isTopicless(e){const t=String(e).trim().toLowerCase().replace(/[^a-z0-9\s]/g," ").replace(/\s+/g," ").trim();if(!t)return!0;const i=t.split(" ");return!!/^(good (morning|afternoon|evening)|whats up|wassup|hey there|hello there|hi there|how are you)\b/.test(t)||i.length<=2&&t.length<=12&&GREETINGS.has(i[0])}function looksLikeEcho(e,t){const i=e=>String(e).toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim(),n=i(e),r=i(t);if(!n||!r)return!1;if(n===r)return!0;if(r.length<=14&&(n.startsWith(r)||r.startsWith(n)))return!0;if(r.length<=24){const i=e=>new Set((String(e).toLowerCase().match(/[a-z0-9]+/g)||[]).filter(e=>!ECHO_STOP.has(e))),n=i(e),r=i(t);if(n.size&&n.size===r.size&&[...n].every(e=>r.has(e)))return!0}return!1}const SEED_MAX=60;function isSeedTitle(e,t){const i=String(null==e?"":e).replace(/\s+/g," ").trim(),n=String(null==t?"":t).replace(/\s+/g," ").trim();if(!i||!n)return!1;const r=n.slice(0,60);return i===r||!!(60===r.length&&i.length>=52&&r.startsWith(i))}const ECHO_STOP=new Set(["the","a","an","to","of","in","on","at","for","and","or","is","are","be","it","its","my","our","please","can","you","just","do","that","this"]);function cleanTitle(e){return String(null==e?"":e).replace(/\s+/g," ").trim().replace(/["'`“”‘’]/g,"").replace(/[*_#]/g,"").replace(/^\s*(?:title|name)\s*[:\-–]\s*/i,"").replace(/[.\s]+$/g,"").slice(0,60).trim()}const titlePromptOf=e=>`Write a short title for a conversation that begins with: "${String(e).slice(0,500)}"`,FILLER=/^(?:please|pls|plz|hey|hi|hello|ok(?:ay)?|so|now|just|also|and|then|maybe|well|um|uh|can you|could you|would you|will you|i want you to|i want to|i need you to|i need to|i'?d like you to|i would like you to|i'?d like to|help me|help|let'?s|lets|go ahead and)\b[\s,:;-]*/i,TRAILING_STOP=new Set(["the","a","an","in","on","at","to","for","of","and","or","with","is","are","my","our","this","that","please","can","you","could","would","i","we","just","do","it"]);function deriveTitle(e){let t=String(null==e?"":e).trim().replace(/\s+/g," ");if(!t)return GENERIC_TITLE;for(let e=0;e<6;e++){const e=t.replace(FILLER,"").trim();if(e===t)break;t=e}const i=t.split(" ").filter(Boolean);if(!i.length)return GENERIC_TITLE;const n=i.slice(0,6);for(;n.length>2&&TRAILING_STOP.has(n[n.length-1].toLowerCase().replace(/[^a-z0-9]/g,""));)n.pop();let r=n.join(" ").replace(/[.,!?;:]+$/,"").trim();return r?(r=r[0].toUpperCase()+r.slice(1),r.slice(0,60).trim()||GENERIC_TITLE):GENERIC_TITLE}async function nameConversation(e,{callModel:t,signal:i}={}){const n=null==e?"":String(e);if(!n.trim())return"";if(isTopicless(n))return GENERIC_TITLE;if(!("function"!=typeof t||i&&i.aborted)){let e=null;try{e=await t(titlePromptOf(n),{system:TITLE_SYSTEM,signal:i,naming:!0})}catch{e=null}const r=cleanTitle(e);if(r)return looksLikeEcho(r,n)?GENERIC_TITLE:r}return deriveTitle(n)}async function refineTitle(e,t,i={}){const n=i&&!0===i.named,r=i&&!0===i.seeded,o=isSeedTitle(e,t);if(n&&!o)return null;if(!r&&!isGenericTitle(e)&&!o)return null;if(!String(t||"").trim()||isTopicless(t))return null;const s=cleanTitle(await nameConversation(t,i));return!s||isGenericTitle(s)?null:s}async function nameSession(e,t,i,n,r={}){if(!e||"function"!=typeof e.setTitle)return null;if(!i)return null;const o="function"==typeof e.getSession?e.getSession(t,i):null,s=o&&o.title,l=!(!o||o.named);if(l&&s&&!isGenericTitle(s)&&!isSeedTitle(s,n)&&!looksLikeEcho(s,n)){try{e.setTitle(t,i,s,{named:!0})}catch{return null}return null}const a={...r,seeded:l},c=await refineTitle(s,n,a);if(c){try{e.setTitle(t,i,c,{named:!0})}catch{return null}return c}if(isTopicless(n)&&o&&!o.named&&!isGenericTitle(s)){try{e.setTitle(t,i,GENERIC_TITLE)}catch{return null}return GENERIC_TITLE}return null}module.exports={GENERIC_TITLE:GENERIC_TITLE,TITLE_SYSTEM:TITLE_SYSTEM,isGenericTitle:isGenericTitle,isTopicless:isTopicless,isSeedTitle:isSeedTitle,looksLikeEcho:looksLikeEcho,cleanTitle:cleanTitle,titlePromptOf:titlePromptOf,deriveTitle:deriveTitle,nameConversation:nameConversation,refineTitle:refineTitle,nameSession:nameSession};
|
|
@@ -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"),{spawnSync:spawnSync}=require("node:child_process"),IS_WIN32="win32"===process.platform,DEFAULT_PATHEXT=".COM;.EXE;.BAT;.CMD";function defaultExists(e){try{return fs.statSync(e).isFile()}catch{return!1}}function defaultProbe(e,t=[],r={}){try{const n=spawnSync(e,t,{encoding:"utf8",timeout:r.timeout||5e3,windowsHide:!0,env:r.env});return n.error||0!==n.status?null:"string"==typeof n.stdout?n.stdout:""}catch{return null}}function defaultDirExists(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function defaultDirNonEmpty(e){try{return fs.readdirSync(e).length>0}catch{return!1}}function defaultReadText(e){try{return fs.readFileSync(e,"utf8")}catch{return null}}function defaultRun(e,t=[],r={}){try{const n=spawnSync(e,t,{encoding:"utf8",windowsHide:!0,timeout:r.timeout||1e4,env:r.env});if(n.error)return{ok:!1,error:n.error,output:""};if(0!==n.status){const t=String(n.stderr||"").trim();return{ok:!1,error:new Error(`${e} exited ${n.status}${t?`: ${t}`:""}`),status:n.status,output:String(n.stdout||"")}}return{ok:!0,error:null,output:String(n.stdout||"")}}catch(e){return{ok:!1,error:e,output:""}}}function seams(e){const t=e&&"object"==typeof e?e:{},r="string"==typeof t.platform&&t.platform?t.platform:process.platform;return{o:t,platform:r,env:t.env&&"object"==typeof t.env?t.env:process.env,win32:"win32"===r,exists:"function"==typeof t.exists?t.exists:defaultExists,probe:"function"==typeof t.probe?t.probe:defaultProbe,injectedProbe:"function"==typeof t.probe,kill:"function"==typeof t.kill?t.kill:(...e)=>process.kill(...e),run:"function"==typeof t.run?t.run:defaultRun}}function envValue(e,t,r){if(!e||"object"!=typeof e)return;const n=void 0!==e[t]?e[t]:e[t.toUpperCase()];if(void 0!==n)return n;if("win32"!==r)return;const o=t.toLowerCase();for(const t of Object.keys(e))if(t.toLowerCase()===o)return e[t]}function pathEntries(e,t,r,n){const o=String(envValue(e,"PATH",t)||"").split("win32"===t?";":":"),s=[];for(const e of o){const t=e.trim().replace(/^"|"$/g,"");t&&s.push(n.isAbsolute(t)?t:n.join(r,t))}return s}function extList(e,t){const r=String(envValue(e,"PATHEXT",t)||DEFAULT_PATHEXT).split(";").map((e=>e.trim())).filter(Boolean).map((e=>e.startsWith(".")?e:`.${e}`));return r.length?r:DEFAULT_PATHEXT.split(";")}function resolveExecutable(e,t={}){const{platform:r,env:n,exists:o,win32:s,o:i}=seams(t);if("string"!=typeof e||!e.trim())return null;const a=e.trim(),l="string"==typeof i.cwd&&i.cwd?i.cwd:process.cwd(),u=s?path.win32:path;if(s?a.includes("/")||a.includes("\\")||/^[a-zA-Z]:/.test(a):a.includes("/")){const e=u.isAbsolute(a)?a:u.join(l,a);return o(e)?e:null}const c=s?["",...extList(n,r)]:[""];for(const e of pathEntries(n,r,l,u))for(const t of c){const r=u.join(e,a+t);if(o(r))return r}return null}function shellSpec(e={}){const{platform:t,env:r,win32:n}=seams(e);return n?{cmd:envValue(r,"ComSpec",t)||envValue(r,"COMSPEC",t)||"cmd.exe",arg:"/d /s /c",kind:"cmd"}:{cmd:envValue(r,"SHELL",t)||"/bin/sh",arg:"-c",kind:"posix"}}function killTree(e,t={}){const{platform:r,env:n,win32:o,kill:s,run:i,o:a}=seams(t),l="number"==typeof e?e:e&&e.pid,u=a.signal||"SIGTERM",c=!1!==a.detached,f=a.timeout||1e4;if(!Number.isInteger(l)||l<=0)return{ok:!1,method:"none",pid:Number.isInteger(l)?l:null,error:new Error(`killTree: no usable pid (got ${JSON.stringify(e&&e.pid)})`),gone:!1};if(o){const e=i("taskkill",["/PID",String(l),"/T","/F"],{env:n,platform:r,timeout:f})||{};return!1===e.ok?{ok:!1,method:"taskkill",pid:l,error:e.error||new Error("taskkill failed"),gone:!1}:{ok:!0,method:"taskkill",pid:l,error:null,gone:!1}}let p=null;if(c)try{return s(-l,u),{ok:!0,method:"group",pid:l,error:null,gone:!1}}catch(e){p=e;const t=e&&e.code;if("ESRCH"!==t&&"EPERM"!==t)return{ok:!1,method:"group",pid:l,error:e,gone:!1}}try{return s(l,u),{ok:!0,method:"signal",pid:l,error:null,groupError:p,gone:!1}}catch(e){return{ok:!1,method:"signal",pid:l,error:e,groupError:p,gone:"ESRCH"===(e&&e.code)}}}function isAlive(e,t={}){const{platform:r,env:n,win32:o,probe:s,kill:i}=seams(t),a="number"==typeof e?e:Number(e);if(!Number.isInteger(a)||a<=0)return!1;if(o){const e=s("tasklist",["/FI",`PID eq ${a}`,"/NH","/FO","CSV"],{env:n,platform:r});if(null==e)return!1;const t=String(e).trim();return!!t&&new RegExp(`(^|[^0-9])${a}([^0-9]|$)`).test(t)}try{return i(a,0),!0}catch(e){return Boolean(e&&"EPERM"===e.code)}}function hasDisplay(e={}){const{platform:t,env:r,win32:n,probe:o,injectedProbe:s}=seams(e);return!!(n||"darwin"===t||envValue(r,"DISPLAY",t)||envValue(r,"WAYLAND_DISPLAY",t)||s&&null!==o("xdpyinfo",[],{env:r,platform:t}))}function normalizeLocale(e){if(null==e)return"";const t=String(e).trim();if(!t)return"";const r=t.split("@")[0].split(".")[0];if(/^(c|posix)$/i.test(r))return"";const n=/^([A-Za-z]{2,3})(?:[_-]([A-Za-z0-9]{2,8}))?$/.exec(r);if(!n)return"";const o=n[1].toLowerCase();return"c"===o||"posix"===o?"":n[2]?`${o}-${n[2].toUpperCase()}`:o}function appLocale(e={}){const{platform:t,env:r,o:n}=seams(e);if("string"==typeof n.locale)return normalizeLocale(n.locale);const o=n.env&&"object"==typeof n.env;for(const e of["LC_ALL","LC_CTYPE","LC_MESSAGES","LANG"]){const n=normalizeLocale(envValue(r,e,t));if(n)return n}const s=String(envValue(r,"LANGUAGE",t)||"");if(s)for(const e of s.split(":")){const t=normalizeLocale(e);if(t)return t}if(o)return"";try{return normalizeLocale((new Intl.DateTimeFormat).resolvedOptions().locale)}catch{return""}}function languageName(e,t={}){const{o:r}=seams(t);if("string"==typeof r.languageName)return r.languageName;const n=normalizeLocale(e);if(!n)return"";const o=n.split("-")[0];try{return new Intl.DisplayNames(["en"],{type:"language"}).of(o)||""}catch{return""}}function homeDir(e={}){const{platform:t,env:r,o:n}=seams(e);if("string"==typeof n.home)return n.home.trim();const o="win32"===t?["USERPROFILE","HOME"]:["HOME","USERPROFILE"];for(const e of o){const n=envValue(r,e,t);if(n&&String(n).trim())return String(n).trim()}try{return os.homedir()||""}catch{return""}}function hasPosixModes(e={}){const{win32:t}=seams(e);return!t}function winShellFolderDesktop(e,t){const r=e("reg",["query","HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders","/v","Desktop"]);if(!r)return"";const n=/^\s*Desktop\s+REG_(?:EXPAND_)?SZ\s+(.+)$/im.exec(r),o=n&&n[1].trim();return o&&t(o)?o:""}function desktopDir(e={}){const{platform:t,env:r,win32:n,probe:o,o:s}=seams(e),i=n?path.win32:path.posix,a=homeDir(e),l="function"==typeof s.dirExists?s.dirExists:defaultDirExists,u="function"==typeof s.dirNonEmpty?s.dirNonEmpty:defaultDirNonEmpty;if(n){const e=winShellFolderDesktop(o,l);if(e)return e}const c="function"==typeof s.readText?s.readText:defaultReadText,f=[],p=e=>{e&&String(e).trim()&&f.push(String(e).trim())};if(n){const e=envValue(r,"OneDrive",t)||envValue(r,"OneDriveConsumer",t);e&&p(i.join(e,"Desktop")),a&&p(i.join(a,"OneDrive","Desktop")),a&&p(i.join(a,"Desktop"));const n=a?i.join(a,"Desktop"):"",o=f.indexOf(n);o>0&&l(n)&&u(n)&&f.slice(0,o).every((e=>!l(e)||!u(e)))&&(f.splice(o,1),f.unshift(n))}else if("darwin"===t)a&&p(i.join(a,"Desktop"));else{if(p(envValue(r,"XDG_DESKTOP_DIR",t)),a){const e=c(i.join(a,".config","user-dirs.dirs")),t=e&&/^\s*XDG_DESKTOP_DIR\s*=\s*"?([^"\n]+)"?\s*$/m.exec(e);t&&p(t[1].replace(/\$HOME\b|\${HOME}/g,a))}a&&p(i.join(a,"Desktop"))}for(const e of f)if(l(e))return e;return a&&(n||"darwin"===t)?i.join(a,"Desktop"):""}function applyDesktopAlias(e,{home:t,desktopdir:r,win32:n,P:o}){if(!t||!r)return e;const s=o.join(t,"Desktop"),i=e=>n?e.toLowerCase():e;if(i(s)===i(r))return e;if(i(e)===i(s))return r;const a=s+o.sep;return i(e).startsWith(i(a))?r+o.sep+e.slice(a.length):e}const WIN_DRIVE_RE=/^[A-Za-z]:[\\/]/,WIN_BARE_DRIVE_RE=/^[A-Za-z]:$/,WIN_UNC_RE=/^\\\\[^\\?.]/;function resolvePath(e,t={}){const{platform:r,win32:n,o:o}=seams(t),s=n?path.win32:path.posix,i=e=>({ok:!1,path:null,error:e,expandedHome:!1});if("string"!=typeof e||!e.trim())return i(`a path is required (got ${JSON.stringify(e)})`);const a=e.trim();let l=a,u=!1;if("~"===a||a.startsWith("~/")||n&&a.startsWith("~\\")){const e=homeDir(t);if(!e)return i(`cannot expand "~" in ${JSON.stringify(a)}: this machine reports no home directory. Pass a full absolute path instead.`);l="~"===a?e:s.join(e,a.slice(2)),u=!0}else if(a.startsWith("~"))return i(`${JSON.stringify(a)} names another user's home directory, which cannot be resolved from here. Use "~" for this user, or pass a full absolute path.`);if(l=applyDesktopAlias(l,{home:homeDir(t),desktopdir:o.desktopdir,win32:n,P:s}),!u){const e=homeDir(t),o=e?` This machine's home directory is ${e}.`:"";if(n){if((l.startsWith("/")||l.startsWith("\\"))&&!WIN_UNC_RE.test(l))return i(`${JSON.stringify(a)} is not an absolute path on this machine, which runs ${r}. A leading slash here means "the root of the current drive", so writing to it would silently land somewhere other than where you meant. Use a drive-qualified path (C:\\Users\\you\\Desktop\\file.txt) or "~/…".${o}`)}else if(WIN_DRIVE_RE.test(l)||WIN_BARE_DRIVE_RE.test(l)||WIN_UNC_RE.test(l))return i(`${JSON.stringify(a)} is a Windows path, but this machine runs ${r}. Use a posix path (/home/you/file.txt) or "~/…".${o}`)}const c="string"==typeof o.cwd&&o.cwd.trim()?o.cwd.trim():process.cwd(),f=s.isAbsolute(l)?s.resolve(l):s.resolve(c,l);return s.isAbsolute(f)?{ok:!0,path:f,error:null,expandedHome:u}:i(`${JSON.stringify(a)} is relative and the working directory (${JSON.stringify(c)}) is not absolute, so it cannot be resolved. Pass an absolute path.`)}function baseName(e){if("string"!=typeof e)return"";const t=e.trim().replace(/[/\\]+$/,"");if(!t)return"";if(/^[A-Za-z]:$/.test(t))return"";const r=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return-1===r?t:t.slice(r+1)}const api={IS_WIN32:IS_WIN32,seams:seams,resolveExecutable:resolveExecutable,shellSpec:shellSpec,killTree:killTree,isAlive:isAlive,hasDisplay:hasDisplay,homeDir:homeDir,desktopDir:desktopDir,resolvePath:resolvePath,baseName:baseName,hasPosixModes:hasPosixModes,appLocale:appLocale,languageName:languageName,normalizeLocale:normalizeLocale};module.exports=api;
|
|
3
|
+
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{spawnSync:spawnSync}=require("node:child_process"),IS_WIN32="win32"===process.platform,DEFAULT_PATHEXT=".COM;.EXE;.BAT;.CMD";function defaultExists(e){try{return fs.statSync(e).isFile()}catch{return!1}}function defaultProbe(e,t=[],r={}){try{const n=spawnSync(e,t,{encoding:"utf8",timeout:r.timeout||5e3,windowsHide:!0,env:r.env});return n.error||0!==n.status?null:"string"==typeof n.stdout?n.stdout:""}catch{return null}}function defaultDirExists(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function defaultDirNonEmpty(e){try{return fs.readdirSync(e).length>0}catch{return!1}}function defaultReadText(e){try{return fs.readFileSync(e,"utf8")}catch{return null}}function defaultRun(e,t=[],r={}){try{const n=spawnSync(e,t,{encoding:"utf8",windowsHide:!0,timeout:r.timeout||1e4,env:r.env});if(n.error)return{ok:!1,error:n.error,output:""};if(0!==n.status){const t=String(n.stderr||"").trim();return{ok:!1,error:new Error(`${e} exited ${n.status}${t?`: ${t}`:""}`),status:n.status,output:String(n.stdout||"")}}return{ok:!0,error:null,output:String(n.stdout||"")}}catch(e){return{ok:!1,error:e,output:""}}}function seams(e){const t=e&&"object"==typeof e?e:{},r="string"==typeof t.platform&&t.platform?t.platform:process.platform;return{o:t,platform:r,env:t.env&&"object"==typeof t.env?t.env:process.env,win32:"win32"===r,exists:"function"==typeof t.exists?t.exists:defaultExists,probe:"function"==typeof t.probe?t.probe:defaultProbe,injectedProbe:"function"==typeof t.probe,kill:"function"==typeof t.kill?t.kill:(...e)=>process.kill(...e),run:"function"==typeof t.run?t.run:defaultRun}}function envValue(e,t,r){if(!e||"object"!=typeof e)return;const n=void 0!==e[t]?e[t]:e[t.toUpperCase()];if(void 0!==n)return n;if("win32"!==r)return;const o=t.toLowerCase();for(const t of Object.keys(e))if(t.toLowerCase()===o)return e[t]}function pathEntries(e,t,r,n){const o=String(envValue(e,"PATH",t)||"").split("win32"===t?";":":"),s=[];for(const e of o){const t=e.trim().replace(/^"|"$/g,"");t&&s.push(n.isAbsolute(t)?t:n.join(r,t))}return s}function extList(e,t){const r=String(envValue(e,"PATHEXT",t)||DEFAULT_PATHEXT).split(";").map(e=>e.trim()).filter(Boolean).map(e=>e.startsWith(".")?e:`.${e}`);return r.length?r:DEFAULT_PATHEXT.split(";")}function resolveExecutable(e,t={}){const{platform:r,env:n,exists:o,win32:s,o:i}=seams(t);if("string"!=typeof e||!e.trim())return null;const a=e.trim(),l="string"==typeof i.cwd&&i.cwd?i.cwd:process.cwd(),u=s?path.win32:path;if(s?a.includes("/")||a.includes("\\")||/^[a-zA-Z]:/.test(a):a.includes("/")){const e=u.isAbsolute(a)?a:u.join(l,a);return o(e)?e:null}const c=s?["",...extList(n,r)]:[""];for(const e of pathEntries(n,r,l,u))for(const t of c){const r=u.join(e,a+t);if(o(r))return r}return null}function shellSpec(e={}){const{platform:t,env:r,win32:n}=seams(e);return n?{cmd:envValue(r,"ComSpec",t)||envValue(r,"COMSPEC",t)||"cmd.exe",arg:"/d /s /c",kind:"cmd"}:{cmd:envValue(r,"SHELL",t)||"/bin/sh",arg:"-c",kind:"posix"}}function killTree(e,t={}){const{platform:r,env:n,win32:o,kill:s,run:i,o:a}=seams(t),l="number"==typeof e?e:e&&e.pid,u=a.signal||"SIGTERM",c=!1!==a.detached,f=a.timeout||1e4;if(!Number.isInteger(l)||l<=0)return{ok:!1,method:"none",pid:Number.isInteger(l)?l:null,error:new Error(`killTree: no usable pid (got ${JSON.stringify(e&&e.pid)})`),gone:!1};if(o){const e=i("taskkill",["/PID",String(l),"/T","/F"],{env:n,platform:r,timeout:f})||{};return!1===e.ok?{ok:!1,method:"taskkill",pid:l,error:e.error||new Error("taskkill failed"),gone:!1}:{ok:!0,method:"taskkill",pid:l,error:null,gone:!1}}let p=null;if(c)try{return s(-l,u),{ok:!0,method:"group",pid:l,error:null,gone:!1}}catch(e){p=e;const t=e&&e.code;if("ESRCH"!==t&&"EPERM"!==t)return{ok:!1,method:"group",pid:l,error:e,gone:!1}}try{return s(l,u),{ok:!0,method:"signal",pid:l,error:null,groupError:p,gone:!1}}catch(e){return{ok:!1,method:"signal",pid:l,error:e,groupError:p,gone:"ESRCH"===(e&&e.code)}}}function isAlive(e,t={}){const{platform:r,env:n,win32:o,probe:s,kill:i}=seams(t),a="number"==typeof e?e:Number(e);if(!Number.isInteger(a)||a<=0)return!1;if(o){const e=s("tasklist",["/FI",`PID eq ${a}`,"/NH","/FO","CSV"],{env:n,platform:r});if(null==e)return!1;const t=String(e).trim();return!!t&&new RegExp(`(^|[^0-9])${a}([^0-9]|$)`).test(t)}try{return i(a,0),!0}catch(e){return Boolean(e&&"EPERM"===e.code)}}function hasDisplay(e={}){const{platform:t,env:r,win32:n,probe:o,injectedProbe:s}=seams(e);return!!(n||"darwin"===t||envValue(r,"DISPLAY",t)||envValue(r,"WAYLAND_DISPLAY",t)||s&&null!==o("xdpyinfo",[],{env:r,platform:t}))}function normalizeLocale(e){if(null==e)return"";const t=String(e).trim();if(!t)return"";const r=t.split("@")[0].split(".")[0];if(/^(c|posix)$/i.test(r))return"";const n=/^([A-Za-z]{2,3})(?:[_-]([A-Za-z0-9]{2,8}))?$/.exec(r);if(!n)return"";const o=n[1].toLowerCase();return"c"===o||"posix"===o?"":n[2]?`${o}-${n[2].toUpperCase()}`:o}function appLocale(e={}){const{platform:t,env:r,o:n}=seams(e);if("string"==typeof n.locale)return normalizeLocale(n.locale);const o=n.env&&"object"==typeof n.env;for(const e of["LC_ALL","LC_CTYPE","LC_MESSAGES","LANG"]){const n=normalizeLocale(envValue(r,e,t));if(n)return n}const s=String(envValue(r,"LANGUAGE",t)||"");if(s)for(const e of s.split(":")){const t=normalizeLocale(e);if(t)return t}if(o)return"";try{return normalizeLocale((new Intl.DateTimeFormat).resolvedOptions().locale)}catch{return""}}function languageName(e,t={}){const{o:r}=seams(t);if("string"==typeof r.languageName)return r.languageName;const n=normalizeLocale(e);if(!n)return"";const o=n.split("-")[0];try{return new Intl.DisplayNames(["en"],{type:"language"}).of(o)||""}catch{return""}}function homeDir(e={}){const{platform:t,env:r,o:n}=seams(e);if("string"==typeof n.home)return n.home.trim();const o="win32"===t?["USERPROFILE","HOME"]:["HOME","USERPROFILE"];for(const e of o){const n=envValue(r,e,t);if(n&&String(n).trim())return String(n).trim()}try{return os.homedir()||""}catch{return""}}function hasPosixModes(e={}){const{win32:t}=seams(e);return!t}function winShellFolderDesktop(e,t){const r=e("reg",["query","HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders","/v","Desktop"]);if(!r)return"";const n=/^\s*Desktop\s+REG_(?:EXPAND_)?SZ\s+(.+)$/im.exec(r),o=n&&n[1].trim();return o&&t(o)?o:""}function desktopDir(e={}){const{platform:t,env:r,win32:n,probe:o,o:s}=seams(e),i=n?path.win32:path.posix,a=homeDir(e),l="function"==typeof s.dirExists?s.dirExists:defaultDirExists,u="function"==typeof s.dirNonEmpty?s.dirNonEmpty:defaultDirNonEmpty;if(n){const e=winShellFolderDesktop(o,l);if(e)return e}const c="function"==typeof s.readText?s.readText:defaultReadText,f=[],p=e=>{e&&String(e).trim()&&f.push(String(e).trim())};if(n){const e=envValue(r,"OneDrive",t)||envValue(r,"OneDriveConsumer",t);e&&p(i.join(e,"Desktop")),a&&p(i.join(a,"OneDrive","Desktop")),a&&p(i.join(a,"Desktop"));const n=a?i.join(a,"Desktop"):"",o=f.indexOf(n);o>0&&l(n)&&u(n)&&f.slice(0,o).every(e=>!l(e)||!u(e))&&(f.splice(o,1),f.unshift(n))}else if("darwin"===t)a&&p(i.join(a,"Desktop"));else{if(p(envValue(r,"XDG_DESKTOP_DIR",t)),a){const e=c(i.join(a,".config","user-dirs.dirs")),t=e&&/^\s*XDG_DESKTOP_DIR\s*=\s*"?([^"\n]+)"?\s*$/m.exec(e);t&&p(t[1].replace(/\$HOME\b|\${HOME}/g,a))}a&&p(i.join(a,"Desktop"))}for(const e of f)if(l(e))return e;return a&&(n||"darwin"===t)?i.join(a,"Desktop"):""}function applyDesktopAlias(e,{home:t,desktopdir:r,win32:n,P:o}){if(!t||!r)return e;const s=o.join(t,"Desktop"),i=e=>n?e.toLowerCase():e;if(i(s)===i(r))return e;if(i(e)===i(s))return r;const a=s+o.sep;return i(e).startsWith(i(a))?r+o.sep+e.slice(a.length):e}const WIN_DRIVE_RE=/^[A-Za-z]:[\\/]/,WIN_BARE_DRIVE_RE=/^[A-Za-z]:$/,WIN_UNC_RE=/^\\\\[^\\?.]/;function resolvePath(e,t={}){const{platform:r,win32:n,o:o}=seams(t),s=n?path.win32:path.posix,i=e=>({ok:!1,path:null,error:e,expandedHome:!1});if("string"!=typeof e||!e.trim())return i(`a path is required (got ${JSON.stringify(e)})`);const a=e.trim();let l=a,u=!1;if("~"===a||a.startsWith("~/")||n&&a.startsWith("~\\")){const e=homeDir(t);if(!e)return i(`cannot expand "~" in ${JSON.stringify(a)}: this machine reports no home directory. Pass a full absolute path instead.`);l="~"===a?e:s.join(e,a.slice(2)),u=!0}else if(a.startsWith("~"))return i(`${JSON.stringify(a)} names another user's home directory, which cannot be resolved from here. Use "~" for this user, or pass a full absolute path.`);if(l=applyDesktopAlias(l,{home:homeDir(t),desktopdir:o.desktopdir,win32:n,P:s}),!u){const e=homeDir(t),o=e?` This machine's home directory is ${e}.`:"";if(n){if((l.startsWith("/")||l.startsWith("\\"))&&!WIN_UNC_RE.test(l))return i(`${JSON.stringify(a)} is not an absolute path on this machine, which runs ${r}. A leading slash here means "the root of the current drive", so writing to it would silently land somewhere other than where you meant. Use a drive-qualified path (C:\\Users\\you\\Desktop\\file.txt) or "~/…".${o}`)}else if(WIN_DRIVE_RE.test(l)||WIN_BARE_DRIVE_RE.test(l)||WIN_UNC_RE.test(l))return i(`${JSON.stringify(a)} is a Windows path, but this machine runs ${r}. Use a posix path (/home/you/file.txt) or "~/…".${o}`)}const c="string"==typeof o.cwd&&o.cwd.trim()?o.cwd.trim():process.cwd(),f=s.isAbsolute(l)?s.resolve(l):s.resolve(c,l);return s.isAbsolute(f)?{ok:!0,path:f,error:null,expandedHome:u}:i(`${JSON.stringify(a)} is relative and the working directory (${JSON.stringify(c)}) is not absolute, so it cannot be resolved. Pass an absolute path.`)}function baseName(e){if("string"!=typeof e)return"";const t=e.trim().replace(/[/\\]+$/,"");if(!t)return"";if(/^[A-Za-z]:$/.test(t))return"";const r=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return-1===r?t:t.slice(r+1)}const api={IS_WIN32:IS_WIN32,seams:seams,resolveExecutable:resolveExecutable,shellSpec:shellSpec,killTree:killTree,isAlive:isAlive,hasDisplay:hasDisplay,homeDir:homeDir,desktopDir:desktopDir,resolvePath:resolvePath,baseName:baseName,hasPosixModes:hasPosixModes,appLocale:appLocale,languageName:languageName,normalizeLocale:normalizeLocale};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"),{aegisHome:aegisHome}=require("./credentials.js"),PREFS_FILE="preferences.json",PREFS_VERSION=1,SHARED_PREF_KEYS=Object.freeze(["themeIndex","model","modelClass","currentModelId","models","modelAutoSync","effort","vim","memoryPersist","confirmMode","permissionMode","sandboxPolicy","devMode","speech","accountUsername"]),LEGACY_MEMORY_PERSIST_NAMESPACE="__memoryPersist",LEGACY_CONFIRM_MODE_NAMESPACE="__confirmMode",SECRET_KEY_RE=/(^|[^a-z0-9])(api[_-]?key|apikey|key|keys|token|secret|password|passwd|credential|credentials|authorization|bearer|private[_-]?key|access[_-]?key|session[_-]?key)([^a-z0-9]|$)/i,SECRET_VALUE_RES=[/\baegis_[A-Za-z0-9_\-]{12,}/,/\bsk-[A-Za-z0-9_\-]{12,}/,/\bghp_[A-Za-z0-9_\-]{20,}/,/\bxox[baprs]-[A-Za-z0-9\-]{10,}/,/\beyJ[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{8,}/,/^[A-Za-z0-9+/]{48,}={0,2}$/];function prefsDir(e){const r=e||{};return r.dir&&String(r.dir).trim()?path.resolve(String(r.dir).trim()):aegisHome(r.env)}function prefsFile(e){const r=e||{};return r.file&&String(r.file).trim()?path.resolve(String(r.file).trim()):path.join(prefsDir(r),PREFS_FILE)}function scanForSecrets(e,r="",t=[]){if(null==e)return t;if("string"==typeof e)return SECRET_VALUE_RES.some(
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),PREFS_FILE="preferences.json",PREFS_VERSION=1,SHARED_PREF_KEYS=Object.freeze(["themeIndex","model","modelClass","currentModelId","models","modelAutoSync","effort","vim","memoryPersist","confirmMode","permissionMode","sandboxPolicy","devMode","speech","accountUsername"]),LEGACY_MEMORY_PERSIST_NAMESPACE="__memoryPersist",LEGACY_CONFIRM_MODE_NAMESPACE="__confirmMode",SECRET_KEY_RE=/(^|[^a-z0-9])(api[_-]?key|apikey|key|keys|token|secret|password|passwd|credential|credentials|authorization|bearer|private[_-]?key|access[_-]?key|session[_-]?key)([^a-z0-9]|$)/i,SECRET_VALUE_RES=[/\baegis_[A-Za-z0-9_\-]{12,}/,/\bsk-[A-Za-z0-9_\-]{12,}/,/\bghp_[A-Za-z0-9_\-]{20,}/,/\bxox[baprs]-[A-Za-z0-9\-]{10,}/,/\beyJ[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{8,}/,/^[A-Za-z0-9+/]{48,}={0,2}$/];function prefsDir(e){const r=e||{};return r.dir&&String(r.dir).trim()?path.resolve(String(r.dir).trim()):aegisHome(r.env)}function prefsFile(e){const r=e||{};return r.file&&String(r.file).trim()?path.resolve(String(r.file).trim()):path.join(prefsDir(r),PREFS_FILE)}function scanForSecrets(e,r="",t=[]){if(null==e)return t;if("string"==typeof e)return SECRET_VALUE_RES.some(r=>r.test(e))&&t.push(r||"(root)"),t;if("object"!=typeof e)return t;if(Array.isArray(e))return e.forEach((e,o)=>scanForSecrets(e,`${r}[${o}]`,t)),t;for(const[o,s]of Object.entries(e)){const e=r?`${r}.${o}`:o;SECRET_KEY_RE.test(o)&&null!=s&&""!==s&&!1!==s?t.push(e):scanForSecrets(s,e,t)}return t}function assertNoSecrets(e,r="shared preference store"){const t=scanForSecrets(e);if(t.length)throw new Error(`${r} must not carry key material — refusing to write (found: ${t.join(", ")}). Secrets belong in the host-local credential store, where the OS can protect them.`);return e}function readJson(e,r){try{const t=JSON.parse(fs.readFileSync(e,"utf8"));return t&&"object"==typeof t&&!Array.isArray(t)?t:r}catch{return r}}function load(e){return readJson(prefsFile(e),{})}function write(e,r){assertNoSecrets(e);const t=prefsFile(r);fs.mkdirSync(path.dirname(t),{recursive:!0});const o=`${t}.tmp-${process.pid}`;fs.writeFileSync(o,JSON.stringify(e,null,2)+"\n",{mode:384}),fs.renameSync(o,t);try{fs.chmodSync(t,384)}catch{}return e}function set(e,r){const t={...load(r),...e||{}};for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return void 0===t.version&&(t.version=1),write(t,r)}function get(e,r,t){const o=load(r)[e];return void 0===o?t:o}function has(e,r){return void 0!==load(r)[e]}function remove(e,r){const t=load(r);return delete t[e],write(t,r)}function extractNonSecretHalf(e){const r={},t=(e||{}).__memoryPersist;t&&"object"==typeof t&&"boolean"==typeof t.enabled&&(r.memoryPersist=t.enabled);const o=(e||{}).__confirmMode;return o&&"object"==typeof o&&"boolean"==typeof o.enabled&&(r.confirmMode=o.enabled),r}function adopt(e){const r=e||{},t=prefsFile(r),o=r.legacyDir,s=o?path.join(String(o),"settings.json"):null;if(s&&path.resolve(s)===t)return{adopted:!1,keys:[],from:s,reason:"shared store is the legacy file"};if(!s||!fs.existsSync(s))return{adopted:!1,keys:[],from:s,reason:"no legacy settings file"};const n=load(r),i=extractNonSecretHalf(readJson(s,{})),a=Object.keys(i).filter(e=>void 0===n[e]);if(!a.length)return{adopted:!1,keys:[],from:s,reason:Object.keys(i).length?"shared store already carries these preferences":"legacy store has no shared preferences"};const c={};for(const e of a)c[e]=i[e];return c.adopted={from:s,at:(new Date).toISOString(),names:a.slice().sort()},write({...n,...c},r),{adopted:!0,keys:a.slice().sort(),from:s}}module.exports={PREFS_FILE:PREFS_FILE,PREFS_VERSION:1,SHARED_PREF_KEYS:SHARED_PREF_KEYS,LEGACY_MEMORY_PERSIST_NAMESPACE:"__memoryPersist",prefsDir:prefsDir,prefsFile:prefsFile,load:load,set:set,get:get,has:has,remove:remove,scanForSecrets:scanForSecrets,assertNoSecrets:assertNoSecrets,extractNonSecretHalf:extractNonSecretHalf,adopt:adopt};
|
|
@@ -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{PRESENCE_PATH:PRESENCE_PATH,DEFAULT_INTERVAL_MS:DEFAULT_INTERVAL_MS,MIN_INTERVAL_MS:MIN_INTERVAL_MS,MAX_INTERVAL_MS:MAX_INTERVAL_MS,BACKOFF_FACTOR:BACKOFF_FACTOR,MAX_BACKOFF_MS:MAX_BACKOFF_MS,REQUEST_TIMEOUT_MS:REQUEST_TIMEOUT_MS,APP_NAMES:APP_NAMES,saneToken:saneToken,saneCount:saneCount}=require("./presence-constants.js"),DEFAULT_API_BASE="https://aegiscloud.org";function disabledPresence(e){const n={enabled:!1,reason:String(e||"disabled"),beats:0,failures:0,lastError:null,lastSeenAt:null,intervalMs:null,install:null,app:null,running:!1};return{enabled:!1,reason:n.reason,install:null,beat:()=>Promise.resolve(!1),start:()=>!1,stop:()=>!1,state:()=>({...n})}}function isoOf(e){try{const n=Number(e);return Number.isFinite(n)?new Date(n).toISOString():null}catch{return null}}function createPresence(e={}){const n="string"==typeof e.apiKey?e.apiKey.trim():"";if(!n)return disabledPresence("no-api-key");if(!1===e.enabled)return disabledPresence("disabled");const t="function"==typeof e.log?e.log:()=>{};function r(e){if(!o.has(e)){o.add(e);try{t("debug",`presence: ${e}`)}catch{}}}const o=new Set,s="function"==typeof e.now?e.now:()=>Date.now(),i="function"==typeof e.setTimer?e.setTimer:setTimeout,a="function"==typeof e.clearTimer?e.clearTimer:clearTimeout;let l=saneToken(e.install,64);if(l||"function"!=typeof e.fingerprint){if(!l)try{l=saneToken(require("./device-fingerprint.js").machineFingerprint(),64)}catch{r("fingerprint")}}else try{l=saneToken(e.fingerprint(),64)}catch{r("fingerprint")}if(!l)return disabledPresence("no-install-identity");const u=saneToken(e.app,24).toLowerCase()||"other",c=saneToken(e.version,32),f=saneToken(e.platform,16).toLowerCase()||("undefined"!=typeof process&&process.platform?process.platform:""),_=String(e.baseUrl||"undefined"!=typeof process&&process.env&&process.env.AEGIS_API_BASE||DEFAULT_API_BASE).replace(/\/+$/,""),A=PRESENCE_PATH,E="function"==typeof e.fetchImpl?e.fetchImpl:"function"==typeof fetch?fetch:null;function M(e,n){try{return"function"==typeof e?e():e}catch{return n}}let p=b(e.intervalMs);const T={enabled:!0,reason:null,beats:0,failures:0,lastError:null,lastSeenAt:null,intervalMs:p,install:l,app:u,version:c||null,platform:f||null,running:!1};let S=null,m=null,d=0,N=!1;function b(e){const n=Number(e);return!Number.isFinite(n)||n<=0?DEFAULT_INTERVAL_MS:Math.min(MAX_INTERVAL_MS,Math.max(MIN_INTERVAL_MS,Math.floor(n)))}function y(){if(N)return Promise.resolve(!1);if(m)return m;if(!E)return r("no-fetch"),T.lastError="no fetch implementation",T.failures+=1,Promise.resolve(!1);const t=s();return m=(async()=>{let o=!1,P=null;try{const t="function"==typeof AbortController?new AbortController:null;if(t){const e=i((
|
|
3
|
+
"use strict";const{PRESENCE_PATH:PRESENCE_PATH,DEFAULT_INTERVAL_MS:DEFAULT_INTERVAL_MS,MIN_INTERVAL_MS:MIN_INTERVAL_MS,MAX_INTERVAL_MS:MAX_INTERVAL_MS,BACKOFF_FACTOR:BACKOFF_FACTOR,MAX_BACKOFF_MS:MAX_BACKOFF_MS,REQUEST_TIMEOUT_MS:REQUEST_TIMEOUT_MS,APP_NAMES:APP_NAMES,saneToken:saneToken,saneCount:saneCount}=require("./presence-constants.js"),DEFAULT_API_BASE="https://aegiscloud.org";function disabledPresence(e){const n={enabled:!1,reason:String(e||"disabled"),beats:0,failures:0,lastError:null,lastSeenAt:null,intervalMs:null,install:null,app:null,running:!1};return{enabled:!1,reason:n.reason,install:null,beat:()=>Promise.resolve(!1),start:()=>!1,stop:()=>!1,state:()=>({...n})}}function isoOf(e){try{const n=Number(e);return Number.isFinite(n)?new Date(n).toISOString():null}catch{return null}}function createPresence(e={}){const n="string"==typeof e.apiKey?e.apiKey.trim():"";if(!n)return disabledPresence("no-api-key");if(!1===e.enabled)return disabledPresence("disabled");const t="function"==typeof e.log?e.log:()=>{};function r(e){if(!o.has(e)){o.add(e);try{t("debug",`presence: ${e}`)}catch{}}}const o=new Set,s="function"==typeof e.now?e.now:()=>Date.now(),i="function"==typeof e.setTimer?e.setTimer:setTimeout,a="function"==typeof e.clearTimer?e.clearTimer:clearTimeout;let l=saneToken(e.install,64);if(l||"function"!=typeof e.fingerprint){if(!l)try{l=saneToken(require("./device-fingerprint.js").machineFingerprint(),64)}catch{r("fingerprint")}}else try{l=saneToken(e.fingerprint(),64)}catch{r("fingerprint")}if(!l)return disabledPresence("no-install-identity");const u=saneToken(e.app,24).toLowerCase()||"other",c=saneToken(e.version,32),f=saneToken(e.platform,16).toLowerCase()||("undefined"!=typeof process&&process.platform?process.platform:""),_=String(e.baseUrl||"undefined"!=typeof process&&process.env&&process.env.AEGIS_API_BASE||DEFAULT_API_BASE).replace(/\/+$/,""),A=PRESENCE_PATH,E="function"==typeof e.fetchImpl?e.fetchImpl:"function"==typeof fetch?fetch:null;function M(e,n){try{return"function"==typeof e?e():e}catch{return n}}let p=b(e.intervalMs);const T={enabled:!0,reason:null,beats:0,failures:0,lastError:null,lastSeenAt:null,intervalMs:p,install:l,app:u,version:c||null,platform:f||null,running:!1};let S=null,m=null,d=0,N=!1;function b(e){const n=Number(e);return!Number.isFinite(n)||n<=0?DEFAULT_INTERVAL_MS:Math.min(MAX_INTERVAL_MS,Math.max(MIN_INTERVAL_MS,Math.floor(n)))}function y(){if(N)return Promise.resolve(!1);if(m)return m;if(!E)return r("no-fetch"),T.lastError="no fetch implementation",T.failures+=1,Promise.resolve(!1);const t=s();return m=(async()=>{let o=!1,P=null;try{const t="function"==typeof AbortController?new AbortController:null;if(t){const e=i(()=>{o=!0;try{t.abort()}catch{}},REQUEST_TIMEOUT_MS);e&&"function"==typeof e.unref&&e.unref(),P=()=>a(e)}const r=await E(`${_}${A}`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":n,"X-AEGIS-Version":saneToken(e.clientVersion,32)||c||""},body:JSON.stringify({app:u,version:c||void 0,platform:f||void 0,install:l,queue:saneCount(M(e.queueDepth,0)),autonomous:Boolean(M(e.autonomous,!1))}),...t?{signal:t.signal}:{}});if(P&&P(),!r||"number"!=typeof r.status||r.status<200||r.status>=300)return T.failures+=1,T.lastError=`http ${r&&r.status?r.status:"error"}`,d=I(d),!1;let S=null;try{S=await r.json()}catch{S=null}if(T.beats+=1,T.failures=0,T.lastError=null,T.lastSeenAt=isoOf(s()),d=0,S&&"object"==typeof S&&null!=S.beat_interval_s){const e=Number(S.beat_interval_s);Number.isFinite(e)&&e>0&&(p=b(1e3*e))}return T.intervalMs=p,!0}catch(e){return P&&P(),T.failures+=1,T.lastError=o?"timeout":String(e&&e.message||e||"error").slice(0,200),d=I(d),1===T.failures&&r("beat-failed"),!1}finally{m=null,T.running&&function(e){if(N||"function"!=typeof i)return;S&&a(S);const n=Math.max(1e3,Math.floor(Number(e)||p));S=i(()=>{S=null,y()},n),S&&"function"==typeof S.unref&&S.unref()}(Math.max(0,p+d-(s()-t)))}})(),m}function I(e){const n=e>0?e*BACKOFF_FACTOR:Math.max(MIN_INTERVAL_MS,p);return Math.min(MAX_BACKOFF_MS,Math.floor(n))}return{enabled:!0,app:u,install:l,beat:y,start:function(){return!N&&(T.running=!0,y(),!0)},stop:function(){if(N=!0,T.running=!1,S){try{a(S)}catch{}S=null}return!0},pending:()=>m,state:()=>({...T,intervalMs:p})}}module.exports={createPresence:createPresence,disabledPresence:disabledPresence,PRESENCE_PATH:PRESENCE_PATH,DEFAULT_INTERVAL_MS:DEFAULT_INTERVAL_MS,MIN_INTERVAL_MS:MIN_INTERVAL_MS,MAX_INTERVAL_MS:MAX_INTERVAL_MS,MAX_BACKOFF_MS:MAX_BACKOFF_MS,REQUEST_TIMEOUT_MS:REQUEST_TIMEOUT_MS,APP_NAMES:APP_NAMES};
|
|
@@ -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 PROTO=1,METHODS=Object.freeze(["hello","exec","event","cancel"]),CAPS=Object.freeze({EXEC:"exec",EVENT:"event",CANCEL:"cancel",PTY:"pty"}),CODE=Object.freeze({BAD_JSON:"bad_json",BAD_FRAME:"bad_frame",UNKNOWN_METHOD:"unknown_method",PROTO_MISMATCH:"proto_mismatch",HELLO_REQUIRED:"hello_required",CAPABILITY_MISSING:"capability_missing",UNSUPPORTED:"unsupported"});function request(e,o,t){return{id:e,m:String(o),p:t&&"object"==typeof t?t:{}}}function ok(e,o){return{id:e,ok:!0,r:o&&"object"==typeof o?o:{}}}function err(e,o,t){return{id:e,ok:!1,e:{code:String(o||CODE.UNSUPPORTED),msg:String(t||"")}}}function isObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function validate(e){return isObject(e)?void 0===e.id||null===e.id?{ok:!1,code:CODE.BAD_FRAME,msg:"frame has no id"}:void 0!==e.ok?!0===e.ok?void 0!==e.e?{ok:!1,code:CODE.BAD_FRAME,msg:"reply carries both r and e"}:{ok:!0}:!1===e.ok?isObject(e.e)&&e.e.code?{ok:!0}:{ok:!1,code:CODE.BAD_FRAME,msg:"a failed reply must name a code"}:{ok:!1,code:CODE.BAD_FRAME,msg:"ok must be true or false"}:"string"==typeof e.m&&METHODS.includes(e.m)?void 0===e.p||isObject(e.p)?{ok:!0}:{ok:!1,code:CODE.BAD_FRAME,msg:"params must be an object"}:{ok:!1,code:CODE.UNKNOWN_METHOD,msg:`unknown method: ${String(e.m)}`}:{ok:!1,code:CODE.BAD_FRAME,msg:"frame must be an object"}}function negotiate(e,o){const t=o||{},r=validate(e);if(!r.ok)return{ok:!1,code:r.code,msg:r.msg};if("hello"!==e.m)return{ok:!1,code:CODE.HELLO_REQUIRED,msg:`the first frame must be hello, got ${String(e.m)}`};const n=e.p||{};if(1!==n.proto)return{ok:!1,code:CODE.PROTO_MISMATCH,msg:`peer speaks protocol ${String(n.proto)}, this build speaks 1`};const i=Array.isArray(n.caps)?n.caps.map(String):[],s=(Array.isArray(t.requireCaps)?t.requireCaps.map(String):[]).filter(
|
|
3
|
+
"use strict";const PROTO=1,METHODS=Object.freeze(["hello","exec","event","cancel"]),CAPS=Object.freeze({EXEC:"exec",EVENT:"event",CANCEL:"cancel",PTY:"pty"}),CODE=Object.freeze({BAD_JSON:"bad_json",BAD_FRAME:"bad_frame",UNKNOWN_METHOD:"unknown_method",PROTO_MISMATCH:"proto_mismatch",HELLO_REQUIRED:"hello_required",CAPABILITY_MISSING:"capability_missing",UNSUPPORTED:"unsupported"});function request(e,o,t){return{id:e,m:String(o),p:t&&"object"==typeof t?t:{}}}function ok(e,o){return{id:e,ok:!0,r:o&&"object"==typeof o?o:{}}}function err(e,o,t){return{id:e,ok:!1,e:{code:String(o||CODE.UNSUPPORTED),msg:String(t||"")}}}function isObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function validate(e){return isObject(e)?void 0===e.id||null===e.id?{ok:!1,code:CODE.BAD_FRAME,msg:"frame has no id"}:void 0!==e.ok?!0===e.ok?void 0!==e.e?{ok:!1,code:CODE.BAD_FRAME,msg:"reply carries both r and e"}:{ok:!0}:!1===e.ok?isObject(e.e)&&e.e.code?{ok:!0}:{ok:!1,code:CODE.BAD_FRAME,msg:"a failed reply must name a code"}:{ok:!1,code:CODE.BAD_FRAME,msg:"ok must be true or false"}:"string"==typeof e.m&&METHODS.includes(e.m)?void 0===e.p||isObject(e.p)?{ok:!0}:{ok:!1,code:CODE.BAD_FRAME,msg:"params must be an object"}:{ok:!1,code:CODE.UNKNOWN_METHOD,msg:`unknown method: ${String(e.m)}`}:{ok:!1,code:CODE.BAD_FRAME,msg:"frame must be an object"}}function negotiate(e,o){const t=o||{},r=validate(e);if(!r.ok)return{ok:!1,code:r.code,msg:r.msg};if("hello"!==e.m)return{ok:!1,code:CODE.HELLO_REQUIRED,msg:`the first frame must be hello, got ${String(e.m)}`};const n=e.p||{};if(1!==n.proto)return{ok:!1,code:CODE.PROTO_MISMATCH,msg:`peer speaks protocol ${String(n.proto)}, this build speaks 1`};const i=Array.isArray(n.caps)?n.caps.map(String):[],s=(Array.isArray(t.requireCaps)?t.requireCaps.map(String):[]).filter(e=>!i.includes(e));return s.length?{ok:!1,code:CODE.CAPABILITY_MISSING,msg:`peer does not offer: ${s.join(", ")}`}:{ok:!0,proto:1,caps:i}}function hello(e){return request(void 0===e?0:e,"hello",{proto:1,caps:[CAPS.EXEC,CAPS.EVENT,CAPS.CANCEL]})}function encode(e){return`${JSON.stringify(e)}\n`}function decodeLine(e){const o=String(null==e?"":e).trim();if(!o)return{ok:!1,id:null,code:CODE.BAD_JSON,msg:"empty line"};let t;try{t=JSON.parse(o)}catch(e){return{ok:!1,id:null,code:CODE.BAD_JSON,msg:`not JSON: ${e.message}`}}const r=validate(t);return r.ok?{ok:!0,frame:t}:{ok:!1,id:isObject(t)&&void 0!==t.id?t.id:null,code:r.code,msg:r.msg}}function splitLines(e){const o=String(null==e?"":e).split("\n"),t=o.pop();return{lines:o.filter(e=>""!==e.trim()),rest:void 0===t?"":t}}module.exports={PROTO:1,METHODS:METHODS,CAPS:CAPS,CODE:CODE,request:request,ok:ok,err:err,hello:hello,validate:validate,negotiate:negotiate,encode:encode,decodeLine:decodeLine,splitLines:splitLines};
|
|
@@ -95,11 +95,11 @@
|
|
|
95
95
|
* user's Drive or their account. The remote/root are overridable the same way
|
|
96
96
|
* (`AEGIS_VAULT_REMOTE`/`AEGIS_VAULT_ROOT`, `AEGIS_VAULT_BACKEND`), which is
|
|
97
97
|
* also what keeps a misconfigured vault from writing into an unrelated folder.
|
|
98
|
-
*/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"),authorship=require("./authorship-key.js"),BACKEND_CLOUD="aegiscloud",BACKEND_RCLONE="rclone",DEFAULT_BACKEND=
|
|
98
|
+
*/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"),authorship=require("./authorship-key.js"),BACKEND_CLOUD="aegiscloud",BACKEND_RCLONE="rclone",DEFAULT_BACKEND="aegiscloud",DEFAULT_REMOTE="gdrive",DEFAULT_ROOT="AEGIS-AGPL",RECORDS_DIR="records",INDEX_NAME="index.jsonl",ANCHOR_SUFFIX=".anchor.json",ANCHOR_VERSION=1,ANCHOR_KIND="aegiscode.record.anchor",INDEX_KIND="aegiscode.record.index",RCLONE_ENV="AEGIS_VAULT_RCLONE",REMOTE_ENV="AEGIS_VAULT_REMOTE",ROOT_ENV="AEGIS_VAULT_ROOT",BACKEND_ENV="AEGIS_VAULT_BACKEND",API_BASE_ENV="AEGIS_API_BASE",CLOUD_PREFIX="/api/v1/vault",RCLONE_TIMEOUT_MS=6e4,MAX_INSPECT_BYTES=2097152,MAX_AUDIT_FILES=500,KEY_PATH_PATTERNS=[/(^|\/)keys?\//i,/\.key$/i,/\.pem$/i,/(^|\/)id_(rsa|dsa|ecdsa|ed25519)(\.|$)/i,/(^|\/)agent\.key(\.|$)/i],BARE_TOKEN=/^[A-Za-z0-9_\-+/=]{40,}$/,BARE_HEX=/^[0-9a-fA-F]{32,}$/,PEM_PRIVATE=/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/;function flag(e,t,r=null){const n=Array.isArray(e)?e:[],o=n.indexOf(t);return-1===o||void 0===n[o+1]||String(n[o+1]).startsWith("--")?r:n[o+1]}function has(e,t){return(Array.isArray(e)?e:[]).includes(t)}function rcloneBinary(e=process.env,t=[]){return flag(t,"--rclone")||e[RCLONE_ENV]||"rclone"}function vaultTarget(e=process.env,t=[],r=null){const n=flag(t,"--remote")||e[REMOTE_ENV]||r&&r.remote||"gdrive";return{backend:backendFor(e,t,n,r),remote:n,root:flag(t,"--root")||e[ROOT_ENV]||r&&r.root||"AEGIS-AGPL",apiBase:String(flag(t,"--base")||e[API_BASE_ENV]||"https://aegiscloud.org").replace(/\/+$/,""),rclone:rcloneBinary(e,t),env:e}}function backendFor(e,t,r,n=null){const o=String(flag(t,"--backend")||e[BACKEND_ENV]||"").trim().toLowerCase();if(o){if("aegiscloud"!==o&&"rclone"!==o)throw new Error(`vault: unknown backend "${o}" — expected aegiscloud or rclone`);return o}return flag(t,"--remote")||e[REMOTE_ENV]?"rclone":!n||"aegiscloud"!==n.backend&&"rclone"!==n.backend?n&&void 0===n.backend&&n.remote&&"gdrive"!==n.remote?"rclone":"aegiscloud":n.backend}function remoteSpec(e,...t){return`${e.remote}:${[e.root,...t].filter(Boolean).join("/")}`
|
|
99
99
|
/**
|
|
100
100
|
* A path *below* the root, however it was written: `records/x.json`,
|
|
101
101
|
* `<root>/records/x.json`, or an absolute `remote:…` spec. Everything that
|
|
102
102
|
* reads tolerates all three, because the anchor stores the browsable
|
|
103
103
|
* root-prefixed form (a human reads `AEGIS-AGPL/records/x.json`) while rclone
|
|
104
104
|
* wants it relative.
|
|
105
|
-
*/}function relativeToRoot(e,t){let r=String(t||"").replace(/^\/+/,"");const n=`${e.remote}:`;return r.startsWith(n)&&(r=r.slice(n.length)),r===e.root?"":(r.startsWith(`${e.root}/`)&&(r=r.slice(e.root.length+1)),r)}function remoteSpecOf(e,t){const r=relativeToRoot(e,t);return r?remoteSpec(e,r):remoteSpec(e)}function rcloneRun(e,t,{timeout:r=RCLONE_TIMEOUT_MS}={}){try{return execFileSync(e.rclone,t,{encoding:"utf8",timeout:r,stdio:["ignore","pipe","pipe"],maxBuffer:33554432,env:e.env?{...process.env,...e.env}:process.env})}catch(e){const r=String(e&&e.stderr||"").trim().split("\n").filter((e=>!/NOTICE:/.test(e))).pop()||e&&e.message||String(e),n=new Error(`vault: rclone ${t[0]} failed — ${r}`);throw n.code="ERCLONE",n.stderr=String(e&&e.stderr||""),n}}function tempDir(){return fs.mkdtempSync(path.join(os.tmpdir(),"aegis-vault-"))}function cloudApiKey(e={}){if(e.apiKey)return String(e.apiKey).trim();const t=e.env||process.env;try{const e=require("./credentials.js");return String(e.resolveApiKey({env:t,dir:e.aegisHome(t)}).key||"").trim()}catch{return""}}async function cloudRun(e,t,r,{body:n=null,raw:o=!1,timeout:a=RCLONE_TIMEOUT_MS,fetchImpl:s=null,apiKey:i=null}={}){const c=i||"";if(!c){const e=new Error("vault: no AEGIS account key on this machine — the aegiscloud vault is the account you already have. Run `aegiscode login`, or publish to a folder you own with `--backend rclone --remote <name>`.");throw e.code="ENOKEY",e}const l=s||("function"==typeof fetch?fetch:null);if(!l){const e=new Error("vault: this Node has no global fetch — upgrade to Node 22+ to use the aegiscloud vault");throw e.code="ENOFETCH",e}const u=new AbortController,d=setTimeout((()=>u.abort()),a);let h;try{h=await l(`${e.apiBase}${CLOUD_PREFIX}${r}`,{method:t,headers:{"Content-Type":"application/json","X-API-Key":c,Authorization:`Bearer ${c}`},body:null===n?void 0:JSON.stringify(n),signal:u.signal})}catch(t){const r=new Error(`vault: could not reach ${e.apiBase} — ${t&&t.message||t}`);throw r.code="ENETWORK",r}finally{clearTimeout(d)}const E=await h.text();let p=null;try{p=E?JSON.parse(E):null}catch{p=null}if(!h.ok){if(404===h.status&&(""===r||r.startsWith("?"))){const t=new Error(`vault: ${e.apiBase} does not serve the account vault yet (${CLOUD_PREFIX} is missing on this server). Publish to a folder you own instead: \`--backend rclone --remote <name> --root <folder>\`.`);throw t.code="ENOVAULT",t.status=404,t}const n=p&&(p.error||p.message)||E.slice(0,200)||`HTTP ${h.status}`,o=new Error(`vault: ${t} ${CLOUD_PREFIX}${r} failed — ${n}`);throw o.code="ECLOUD",o.status=h.status,o}return o?E:null===p?{}:p}function cloudObject(e,t){return`/${String(t||"").split("/").filter(Boolean).map((e=>encodeURIComponent(e))).join("/")}`}function transportFor(e,t={}){if(e.backend===BACKEND_CLOUD){const r=cloudApiKey(t),n=(n,o,a)=>cloudRun(e,n,o,{...a,fetchImpl:t.fetch,apiKey:r});return{backend:BACKEND_CLOUD,async put(t,r){await n("PUT",cloudObject(e,remoteObjectName(t)),{body:{content:r}})},async putFile(e,t){await this.put(e,fs.readFileSync(t,"utf8"))},async cat(t){try{const r=await n("GET",cloudObject(e,remoteObjectName(t)));return r&&"string"==typeof r.content?r.content:null}catch(e){if(404===e.status)return null;throw e}},async list(t){const r=await n("GET",`?dir=${encodeURIComponent(relativeToRoot(e,t))}`);return Array.isArray(r&&r.files)?r.files:[]},async listRecursive(t){const r=await n("GET",`?dir=${encodeURIComponent(relativeToRoot(e,t))}&recursive=1`);return Array.isArray(r&&r.files)?r.files:[]},describe:`${e.apiBase} (account vault)`}}return{backend:BACKEND_RCLONE,async put(t,r,{name:n="object"}={}){const o=tempDir();try{const a=path.join(o,n);fs.writeFileSync(a,r),rcloneRun(e,["copyto",a,remoteSpecOf(e,t)])}finally{fs.rmSync(o,{recursive:!0,force:!0})}},async putFile(t,r){rcloneRun(e,["copyto",r,remoteSpecOf(e,t)])},async cat(t){try{return rcloneRun(e,["cat",remoteSpecOf(e,t)])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404/i.test(e.stderr||e.message))return null;throw e}},list:async t=>listRaw(e,t),listRecursive:async t=>rcloneLsjsonRecursive(e,t),describe:`${e.remote}:${e.root}`}}function remoteObjectName(e){return relativeToRoot({remote:"",root:""},e).replace(/^\/+/,"")}function inspect(e,t,{secret:r=null,keyPath:n=null}={}){const o=String(e||"");for(const e of KEY_PATH_PATTERNS)if(e.test(o))return{dangerous:!0,reason:`the path looks like key material (${e})`};if(n&&path.resolve(o)===path.resolve(n))return{dangerous:!0,reason:"this path IS the authorship key"};const a=String(null==t?"":t),s=a.trim();if(r&&s.includes(String(r)))return{dangerous:!0,reason:"the content carries the authorship key verbatim"};if(PEM_PRIVATE.test(a))return{dangerous:!0,reason:"the content is a PEM private key"};const i=1===s.split("\n").length;if(i&&BARE_TOKEN.test(s)&&!BARE_HEX.test(s))return{dangerous:!0,reason:"the content is a bare high-entropy token (a raw secret)"};if(i&&BARE_HEX.test(s))return{dangerous:!0,reason:"the content is an unlabelled hex blob (a raw digest or key)"};let c=null;try{c=JSON.parse(a)}catch{c=null}if(c&&"object"==typeof c&&!Array.isArray(c)){if("string"==typeof c.kind&&c.kind.startsWith("aegiscode."))return inspectArtifact(c,r);try{fp.assertNoLeak(c,r||"")}catch(e){return{dangerous:!0,reason:e&&e.message||"failed the leak check"}}}return{dangerous:!1,reason:null}}function inspectArtifact(e,t){const r=new Set(["sha256","attestation","code"]);for(const[n,o]of Object.entries(e)){if(null==o)continue;const e=Array.isArray(o)?o.join("\0"):String(o);if(t&&e.includes(String(t)))return{dangerous:!0,reason:`the link carries the authorship key verbatim in "${n}"`};if(!r.has(n)&&fp.longHexRun(e))return{dangerous:!0,reason:`the link carries a long hex run in "${n}"`}}return void 0===e.sha256||/^[0-9a-f]{64}$/.test(String(e.sha256))?void 0===e.attestation||/^[0-9a-f]{32}$/.test(String(e.attestation))?{dangerous:!1,reason:null}:{dangerous:!0,reason:"the link's attestation is not a 32-hex tag"}:{dangerous:!0,reason:"the link's sha256 is not a 64-hex digest"}}function assertPublishable(e,t,r={}){const n=inspect(e,t,r);if(n.dangerous)throw new Error(`vault: refusing to publish ${e} — ${n.reason}. The vault carries sealed records only: a key that reaches cloud storage can mint records indistinguishable from yours, so it is never a backup. Keep it in ${authorship.defaultKeyPath(r.env||process.env)} (0600) and back it up to a local disk or a password manager.`);return!0}function baseName(e,t=null){const r=e&&e.behaviour?String(e.behaviour):"unobserved",n=String(t||e&&e.createdAt||(new Date).toISOString()).replace(/[:.]/g,"-");return`${e.keyFingerprint}-${r}.${n}`}function driveUrl(e){return e?`https://drive.google.com/open?id=${encodeURIComponent(e)}`:null}function sha256(e){return crypto.createHash("sha256").update(e,"utf8").digest("hex")}function readRecord({file:e=null,record:t=null,secret:r=null,env:n=process.env}){if(e){const t=path.resolve(e);if(!fs.existsSync(t))throw new Error(`vault: no record at ${t}`);const o=fs.readFileSync(t,"utf8");let a;assertPublishable(t,o,{secret:r,keyPath:authorship.defaultKeyPath(n),env:n});try{a=JSON.parse(o)}catch(e){throw new Error(`vault: ${t} is not JSON — ${e.message}`)}return{text:o,record:a,file:t,serialised:o}}if(t){const e=JSON.stringify(t,null,2)+"\n";return{text:e,record:t,file:null,serialised:e}}throw new Error("vault: publish needs a record file or a record")}async function publish(e={}){const t=e.env||process.env,r=e.argv||[],n=vaultTarget(t,r),o=Boolean(e.dryRun)||has(r,"--dry-run"),a=void 0===e.index?!has(r,"--no-index"):Boolean(e.index),s=e.secret||null,{text:i,record:c,file:l}=readRecord({...e,secret:s,env:t});let u;try{u=fp.id(c)}catch(e){throw new Error(`vault: not a sealed φ(α) record — ${e&&e.message||e}`)}const d=authorship.defaultKeyPath(t);assertPublishable(path.basename(l||"record.json"),i,{secret:s,keyPath:d,env:t});const h=`${baseName(c)}.json`,E=`${h}${ANCHOR_SUFFIX}`,p=`${RECORDS_DIR}/${h}`,f=`${RECORDS_DIR}/${E}`,N=sha256(i),y={v:1,kind:ANCHOR_KIND,id:u,keyFingerprint:c.keyFingerprint,behaviour:c.behaviour||null,code:c.code||null,createdAt:c.createdAt,attestation:c.attestation,sha256:N,bytes:Buffer.byteLength(i,"utf8"),backend:n.backend,remote:n.remote,root:n.root,path:n.backend===BACKEND_CLOUD?`${CLOUD_PREFIX}/${p}`:`${n.root}/${p}`,key:p,emittedAt:new Date(e.now||Date.now()).toISOString(),driveId:null,url:null,index:a?`${n.root}/${RECORDS_DIR}/${INDEX_NAME}`:null},A=transportFor(n,e);if(o)return{ok:!0,dryRun:!0,backend:n.backend,anchor:y,url:null,remotePath:y.path,commands:n.backend===BACKEND_CLOUD?[`PUT ${n.apiBase}${CLOUD_PREFIX}/${p}`,`PUT ${n.apiBase}${CLOUD_PREFIX}/${f}`]:[`rclone copyto ${l||"<record>"} ${remoteSpec(n,p)}`,`rclone copyto <anchor> ${remoteSpec(n,f)}`]};l?await A.putFile(p,l):await A.put(p,i,{name:h});const g=(await A.list(RECORDS_DIR)).find((e=>String(e.Name)===h))||null;g&&(y.driveId=g.ID||null,y.url=g.url||(n.backend===BACKEND_CLOUD?null:driveUrl(g.ID)));const O=l?`${l}${ANCHOR_SUFFIX}`:null,R=JSON.stringify(y,null,2)+"\n";await A.put(f,R,{name:E}),O&&fs.writeFileSync(O,R);let _=null;return a&&(_=await appendIndex(n,y,A)),{ok:!0,dryRun:!1,backend:n.backend,anchor:y,url:y.url,localAnchor:O,remotePath:y.path,bytes:y.bytes,sha256:N,indexLines:_}}function rcloneCat(e,t){try{return rcloneRun(e,["cat",remoteSpecOf(e,t)])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404/i.test(e.stderr||e.message))return null;throw e}}function listRaw(e,t){let r;try{r=rcloneRun(e,["lsjson",remoteSpecOf(e,t),"--files-only"])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404|directory not found/i.test(e.stderr||e.message))return[];throw e}const n=String(r).trim();if(!n)return[];const o=JSON.parse(n);return Array.isArray(o)?o:[]}async function appendIndex(e,t,r=transportFor(e)){const n=`${RECORDS_DIR}/${INDEX_NAME}`,o=await r.cat(n)||"",a=JSON.stringify({kind:INDEX_KIND,id:t.id,keyFingerprint:t.keyFingerprint,sha256:t.sha256,path:t.path,url:t.url,driveId:t.driveId,emittedAt:t.emittedAt});return await r.put(n,o+a+"\n",{name:INDEX_NAME}),(o.trim()?o.trim().split("\n").length:0)+1}function localAnchor(e){const t=`${path.resolve(e)}${ANCHOR_SUFFIX}`;if(!fs.existsSync(t))return null;try{return JSON.parse(fs.readFileSync(t,"utf8"))}catch{return null}}async function checkAnchor(e={}){const t=e.env||process.env,r=e.argv||[],n=e.anchor||(e.file?localAnchor(e.file):null);if(!n)return{ok:!1,reason:"not linked — no anchor beside this record (publish it first)",present:!1,unchanged:null,attested:null};const o=transportFor(vaultTarget(t,r,n),e),a=await o.cat(n.key||n.path);if(null===a)return{ok:!1,reason:`no copy at ${n.path}`,present:!1,unchanged:!1,attested:null,anchor:n};const s=sha256(a)===n.sha256;let i=null,c=null;try{const n=e.key||authorship.resolveKey({argv:r,env:t});if(n.secret){const e=fp.verify(JSON.parse(a),n.secret);i=e.ok,c=e.reason}else c="no authorship key on this machine to recompute with"}catch(e){c=e&&e.message||String(e)}return{ok:s&&!1!==i,anchor:n,present:!0,unchanged:s,attested:i,attestationReason:c,remotePath:n.path,url:n.url,reason:s?!1===i?`the published copy does not verify: ${c}`:null:"the published copy is not the bytes that were sealed (sha256 differs)"}}async function list(e={}){const t=vaultTarget(e.env||process.env,e.argv||[]),r=transportFor(t,e),n=RECORDS_DIR,o=await r.list(n),a=o.filter((e=>String(e.Name).endsWith(ANCHOR_SUFFIX))),s=o.filter((e=>!String(e.Name).endsWith(ANCHOR_SUFFIX)&&String(e.Name).endsWith(".json")&&e.Name!==INDEX_NAME)),i=[];for(const e of s){const t=a.find((t=>String(t.Name)===`${e.Name}${ANCHOR_SUFFIX}`));let o=null;if(t){const e=await r.cat(`${n}/${t.Name}`);try{o=JSON.parse(e)}catch{o={unreadable:!0}}}i.push({name:e.Name,bytes:e.Size,emittedAt:e.ModTime,id:o?o.id:null,keyFingerprint:o?o.keyFingerprint:null,sha256:o?o.sha256:null,driveId:o&&o.driveId||e.ID||null,url:o&&o.url||e.url||driveUrl(e.ID),linked:Boolean(o)})}return{ok:!0,backend:t.backend,remote:t.remote,root:t.root,where:r.describe,records:i}}async function audit(e={}){const t=e.env||process.env,r=e.argv||[],n=vaultTarget(t,r),o=transportFor(n,e),a=Number(flag(r,"--max"))||500;let s;try{s=await o.listRecursive("")}catch(e){return{ok:!1,backend:n.backend,where:o.describe,error:e&&e.message||String(e),findings:[],checked:0}}const i=e.secret||null,c=[],l=[];let u=0;for(const t of s){const r=String(t.Path||t.Name);if(u>=a){l.push({path:r,reason:`stopped after ${a} files`});continue}if(Number(t.Size)>2097152){l.push({path:r,reason:"larger than 2097152 bytes"});continue}let n;u+=1;try{n=await o.cat(r)}catch(e){l.push({path:r,reason:e&&e.message||String(e)});continue}const s=inspect(r,n,{secret:i});s.dangerous&&c.push({path:r,reason:s.reason})}return{ok:0===c.length,backend:n.backend,remote:n.remote,root:n.root,where:o.describe,checked:u,files:s.length,uninspected:l,findings:c}}function rcloneLsjsonRecursive(e,t){const r=rcloneRun(e,["lsjson",remoteSpecOf(e,t),"--files-only","--recursive"]),n=String(r).trim();if(!n)return[];const o=JSON.parse(n);return Array.isArray(o)?o:[]}module.exports={DEFAULT_REMOTE:DEFAULT_REMOTE,DEFAULT_ROOT:DEFAULT_ROOT,DEFAULT_BACKEND:DEFAULT_BACKEND,BACKEND_CLOUD:BACKEND_CLOUD,BACKEND_RCLONE:BACKEND_RCLONE,CLOUD_PREFIX:CLOUD_PREFIX,BACKEND_ENV:BACKEND_ENV,API_BASE_ENV:API_BASE_ENV,RECORDS_DIR:RECORDS_DIR,INDEX_NAME:INDEX_NAME,ANCHOR_SUFFIX:ANCHOR_SUFFIX,ANCHOR_KIND:ANCHOR_KIND,INDEX_KIND:INDEX_KIND,RCLONE_ENV:RCLONE_ENV,REMOTE_ENV:REMOTE_ENV,ROOT_ENV:ROOT_ENV,inspect:inspect,assertPublishable:assertPublishable,publish:publish,checkAnchor:checkAnchor,list:list,audit:audit,localAnchor:localAnchor,relativeToRoot:relativeToRoot,remoteSpecOf:remoteSpecOf,baseName:baseName,driveUrl:driveUrl,vaultTarget:vaultTarget,rcloneBinary:rcloneBinary,rcloneCat:rcloneCat,transportFor:transportFor,cloudApiKey:cloudApiKey,backendFor:backendFor,sha256:sha256,flag:flag,has:has};
|
|
105
|
+
*/}function relativeToRoot(e,t){let r=String(t||"").replace(/^\/+/,"");const n=`${e.remote}:`;return r.startsWith(n)&&(r=r.slice(n.length)),r===e.root?"":(r.startsWith(`${e.root}/`)&&(r=r.slice(e.root.length+1)),r)}function remoteSpecOf(e,t){const r=relativeToRoot(e,t);return r?remoteSpec(e,r):remoteSpec(e)}function rcloneRun(e,t,{timeout:r=6e4}={}){try{return execFileSync(e.rclone,t,{encoding:"utf8",timeout:r,stdio:["ignore","pipe","pipe"],maxBuffer:33554432,env:e.env?{...process.env,...e.env}:process.env})}catch(e){const r=String(e&&e.stderr||"").trim().split("\n").filter(e=>!/NOTICE:/.test(e)).pop()||e&&e.message||String(e),n=new Error(`vault: rclone ${t[0]} failed — ${r}`);throw n.code="ERCLONE",n.stderr=String(e&&e.stderr||""),n}}function tempDir(){return fs.mkdtempSync(path.join(os.tmpdir(),"aegis-vault-"))}function cloudApiKey(e={}){if(e.apiKey)return String(e.apiKey).trim();const t=e.env||process.env;try{const e=require("./credentials.js");return String(e.resolveApiKey({env:t,dir:e.aegisHome(t)}).key||"").trim()}catch{return""}}async function cloudRun(e,t,r,{body:n=null,raw:o=!1,timeout:a=6e4,fetchImpl:s=null,apiKey:i=null}={}){const c=i||"";if(!c){const e=new Error("vault: no AEGIS account key on this machine — the aegiscloud vault is the account you already have. Run `aegiscode login`, or publish to a folder you own with `--backend rclone --remote <name>`.");throw e.code="ENOKEY",e}const l=s||("function"==typeof fetch?fetch:null);if(!l){const e=new Error("vault: this Node has no global fetch — upgrade to Node 22+ to use the aegiscloud vault");throw e.code="ENOFETCH",e}const u=new AbortController,d=setTimeout(()=>u.abort(),a);let h;try{h=await l(`${e.apiBase}${CLOUD_PREFIX}${r}`,{method:t,headers:{"Content-Type":"application/json","X-API-Key":c,Authorization:`Bearer ${c}`},body:null===n?void 0:JSON.stringify(n),signal:u.signal})}catch(t){const r=new Error(`vault: could not reach ${e.apiBase} — ${t&&t.message||t}`);throw r.code="ENETWORK",r}finally{clearTimeout(d)}const p=await h.text();let f=null;try{f=p?JSON.parse(p):null}catch{f=null}if(!h.ok){if(404===h.status&&(""===r||r.startsWith("?"))){const t=new Error(`vault: ${e.apiBase} does not serve the account vault yet (${CLOUD_PREFIX} is missing on this server). Publish to a folder you own instead: \`--backend rclone --remote <name> --root <folder>\`.`);throw t.code="ENOVAULT",t.status=404,t}const n=f&&(f.error||f.message)||p.slice(0,200)||`HTTP ${h.status}`,o=new Error(`vault: ${t} ${CLOUD_PREFIX}${r} failed — ${n}`);throw o.code="ECLOUD",o.status=h.status,o}return o?p:null===f?{}:f}function cloudObject(e,t){return`/${String(t||"").split("/").filter(Boolean).map(e=>encodeURIComponent(e)).join("/")}`}function transportFor(e,t={}){if("aegiscloud"===e.backend){const r=cloudApiKey(t),n=(n,o,a)=>cloudRun(e,n,o,{...a,fetchImpl:t.fetch,apiKey:r});return{backend:"aegiscloud",async put(t,r){await n("PUT",cloudObject(e,remoteObjectName(t)),{body:{content:r}})},async putFile(e,t){await this.put(e,fs.readFileSync(t,"utf8"))},async cat(t){try{const r=await n("GET",cloudObject(e,remoteObjectName(t)));return r&&"string"==typeof r.content?r.content:null}catch(e){if(404===e.status)return null;throw e}},async list(t){const r=await n("GET",`?dir=${encodeURIComponent(relativeToRoot(e,t))}`);return Array.isArray(r&&r.files)?r.files:[]},async listRecursive(t){const r=await n("GET",`?dir=${encodeURIComponent(relativeToRoot(e,t))}&recursive=1`);return Array.isArray(r&&r.files)?r.files:[]},describe:`${e.apiBase} (account vault)`}}return{backend:"rclone",async put(t,r,{name:n="object"}={}){const o=tempDir();try{const a=path.join(o,n);fs.writeFileSync(a,r),rcloneRun(e,["copyto",a,remoteSpecOf(e,t)])}finally{fs.rmSync(o,{recursive:!0,force:!0})}},async putFile(t,r){rcloneRun(e,["copyto",r,remoteSpecOf(e,t)])},async cat(t){try{return rcloneRun(e,["cat",remoteSpecOf(e,t)])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404/i.test(e.stderr||e.message))return null;throw e}},list:async t=>listRaw(e,t),listRecursive:async t=>rcloneLsjsonRecursive(e,t),describe:`${e.remote}:${e.root}`}}function remoteObjectName(e){return relativeToRoot({remote:"",root:""},e).replace(/^\/+/,"")}function inspect(e,t,{secret:r=null,keyPath:n=null}={}){const o=String(e||"");for(const e of KEY_PATH_PATTERNS)if(e.test(o))return{dangerous:!0,reason:`the path looks like key material (${e})`};if(n&&path.resolve(o)===path.resolve(n))return{dangerous:!0,reason:"this path IS the authorship key"};const a=String(null==t?"":t),s=a.trim();if(r&&s.includes(String(r)))return{dangerous:!0,reason:"the content carries the authorship key verbatim"};if(PEM_PRIVATE.test(a))return{dangerous:!0,reason:"the content is a PEM private key"};const i=1===s.split("\n").length;if(i&&BARE_TOKEN.test(s)&&!BARE_HEX.test(s))return{dangerous:!0,reason:"the content is a bare high-entropy token (a raw secret)"};if(i&&BARE_HEX.test(s))return{dangerous:!0,reason:"the content is an unlabelled hex blob (a raw digest or key)"};let c=null;try{c=JSON.parse(a)}catch{c=null}if(c&&"object"==typeof c&&!Array.isArray(c)){if("string"==typeof c.kind&&c.kind.startsWith("aegiscode."))return inspectArtifact(c,r);try{fp.assertNoLeak(c,r||"")}catch(e){return{dangerous:!0,reason:e&&e.message||"failed the leak check"}}}return{dangerous:!1,reason:null}}function inspectArtifact(e,t){const r=new Set(["sha256","attestation","code"]);for(const[n,o]of Object.entries(e)){if(null==o)continue;const e=Array.isArray(o)?o.join("\0"):String(o);if(t&&e.includes(String(t)))return{dangerous:!0,reason:`the link carries the authorship key verbatim in "${n}"`};if(!r.has(n)&&fp.longHexRun(e))return{dangerous:!0,reason:`the link carries a long hex run in "${n}"`}}return void 0===e.sha256||/^[0-9a-f]{64}$/.test(String(e.sha256))?void 0===e.attestation||/^[0-9a-f]{32}$/.test(String(e.attestation))?{dangerous:!1,reason:null}:{dangerous:!0,reason:"the link's attestation is not a 32-hex tag"}:{dangerous:!0,reason:"the link's sha256 is not a 64-hex digest"}}function assertPublishable(e,t,r={}){const n=inspect(e,t,r);if(n.dangerous)throw new Error(`vault: refusing to publish ${e} — ${n.reason}. The vault carries sealed records only: a key that reaches cloud storage can mint records indistinguishable from yours, so it is never a backup. Keep it in ${authorship.defaultKeyPath(r.env||process.env)} (0600) and back it up to a local disk or a password manager.`);return!0}function baseName(e,t=null){const r=e&&e.behaviour?String(e.behaviour):"unobserved",n=String(t||e&&e.createdAt||(new Date).toISOString()).replace(/[:.]/g,"-");return`${e.keyFingerprint}-${r}.${n}`}function driveUrl(e){return e?`https://drive.google.com/open?id=${encodeURIComponent(e)}`:null}function sha256(e){return crypto.createHash("sha256").update(e,"utf8").digest("hex")}function readRecord({file:e=null,record:t=null,secret:r=null,env:n=process.env}){if(e){const t=path.resolve(e);if(!fs.existsSync(t))throw new Error(`vault: no record at ${t}`);const o=fs.readFileSync(t,"utf8");let a;assertPublishable(t,o,{secret:r,keyPath:authorship.defaultKeyPath(n),env:n});try{a=JSON.parse(o)}catch(e){throw new Error(`vault: ${t} is not JSON — ${e.message}`)}return{text:o,record:a,file:t,serialised:o}}if(t){const e=JSON.stringify(t,null,2)+"\n";return{text:e,record:t,file:null,serialised:e}}throw new Error("vault: publish needs a record file or a record")}async function publish(e={}){const t=e.env||process.env,r=e.argv||[],n=vaultTarget(t,r),o=Boolean(e.dryRun)||has(r,"--dry-run"),a=void 0===e.index?!has(r,"--no-index"):Boolean(e.index),s=e.secret||null,{text:i,record:c,file:l}=readRecord({...e,secret:s,env:t});let u;try{u=fp.id(c)}catch(e){throw new Error(`vault: not a sealed φ(α) record — ${e&&e.message||e}`)}const d=authorship.defaultKeyPath(t);assertPublishable(path.basename(l||"record.json"),i,{secret:s,keyPath:d,env:t});const h=`${baseName(c)}.json`,p=`${h}${ANCHOR_SUFFIX}`,f=`records/${h}`,E=`records/${p}`,g=sha256(i),y={v:1,kind:ANCHOR_KIND,id:u,keyFingerprint:c.keyFingerprint,behaviour:c.behaviour||null,code:c.code||null,createdAt:c.createdAt,attestation:c.attestation,sha256:g,bytes:Buffer.byteLength(i,"utf8"),backend:n.backend,remote:n.remote,root:n.root,path:"aegiscloud"===n.backend?`${CLOUD_PREFIX}/${f}`:`${n.root}/${f}`,key:f,emittedAt:new Date(e.now||Date.now()).toISOString(),driveId:null,url:null,index:a?`${n.root}/records/${INDEX_NAME}`:null},N=transportFor(n,e);if(o)return{ok:!0,dryRun:!0,backend:n.backend,anchor:y,url:null,remotePath:y.path,commands:"aegiscloud"===n.backend?[`PUT ${n.apiBase}${CLOUD_PREFIX}/${f}`,`PUT ${n.apiBase}${CLOUD_PREFIX}/${E}`]:[`rclone copyto ${l||"<record>"} ${remoteSpec(n,f)}`,`rclone copyto <anchor> ${remoteSpec(n,E)}`]};l?await N.putFile(f,l):await N.put(f,i,{name:h});const m=(await N.list("records")).find(e=>String(e.Name)===h)||null;m&&(y.driveId=m.ID||null,y.url=m.url||("aegiscloud"===n.backend?null:driveUrl(m.ID)));const A=l?`${l}${ANCHOR_SUFFIX}`:null,v=JSON.stringify(y,null,2)+"\n";await N.put(E,v,{name:p}),A&&fs.writeFileSync(A,v);let S=null;return a&&(S=await appendIndex(n,y,N)),{ok:!0,dryRun:!1,backend:n.backend,anchor:y,url:y.url,localAnchor:A,remotePath:y.path,bytes:y.bytes,sha256:g,indexLines:S}}function rcloneCat(e,t){try{return rcloneRun(e,["cat",remoteSpecOf(e,t)])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404/i.test(e.stderr||e.message))return null;throw e}}function listRaw(e,t){let r;try{r=rcloneRun(e,["lsjson",remoteSpecOf(e,t),"--files-only"])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404|directory not found/i.test(e.stderr||e.message))return[];throw e}const n=String(r).trim();if(!n)return[];const o=JSON.parse(n);return Array.isArray(o)?o:[]}async function appendIndex(e,t,r=transportFor(e)){const n=`records/${INDEX_NAME}`,o=await r.cat(n)||"",a=JSON.stringify({kind:INDEX_KIND,id:t.id,keyFingerprint:t.keyFingerprint,sha256:t.sha256,path:t.path,url:t.url,driveId:t.driveId,emittedAt:t.emittedAt});return await r.put(n,o+a+"\n",{name:INDEX_NAME}),(o.trim()?o.trim().split("\n").length:0)+1}function localAnchor(e){const t=`${path.resolve(e)}${ANCHOR_SUFFIX}`;if(!fs.existsSync(t))return null;try{return JSON.parse(fs.readFileSync(t,"utf8"))}catch{return null}}async function checkAnchor(e={}){const t=e.env||process.env,r=e.argv||[],n=e.anchor||(e.file?localAnchor(e.file):null);if(!n)return{ok:!1,reason:"not linked — no anchor beside this record (publish it first)",present:!1,unchanged:null,attested:null};const o=transportFor(vaultTarget(t,r,n),e),a=await o.cat(n.key||n.path);if(null===a)return{ok:!1,reason:`no copy at ${n.path}`,present:!1,unchanged:!1,attested:null,anchor:n};const s=sha256(a)===n.sha256;let i=null,c=null;try{const n=e.key||authorship.resolveKey({argv:r,env:t});if(n.secret){const e=fp.verify(JSON.parse(a),n.secret);i=e.ok,c=e.reason}else c="no authorship key on this machine to recompute with"}catch(e){c=e&&e.message||String(e)}return{ok:s&&!1!==i,anchor:n,present:!0,unchanged:s,attested:i,attestationReason:c,remotePath:n.path,url:n.url,reason:s?!1===i?`the published copy does not verify: ${c}`:null:"the published copy is not the bytes that were sealed (sha256 differs)"}}async function list(e={}){const t=vaultTarget(e.env||process.env,e.argv||[]),r=transportFor(t,e),n="records",o=await r.list(n),a=o.filter(e=>String(e.Name).endsWith(ANCHOR_SUFFIX)),s=o.filter(e=>!String(e.Name).endsWith(ANCHOR_SUFFIX)&&String(e.Name).endsWith(".json")&&e.Name!==INDEX_NAME),i=[];for(const e of s){const t=a.find(t=>String(t.Name)===`${e.Name}${ANCHOR_SUFFIX}`);let o=null;if(t){const e=await r.cat(`${n}/${t.Name}`);try{o=JSON.parse(e)}catch{o={unreadable:!0}}}i.push({name:e.Name,bytes:e.Size,emittedAt:e.ModTime,id:o?o.id:null,keyFingerprint:o?o.keyFingerprint:null,sha256:o?o.sha256:null,driveId:o&&o.driveId||e.ID||null,url:o&&o.url||e.url||driveUrl(e.ID),linked:Boolean(o)})}return{ok:!0,backend:t.backend,remote:t.remote,root:t.root,where:r.describe,records:i}}async function audit(e={}){const t=e.env||process.env,r=e.argv||[],n=vaultTarget(t,r),o=transportFor(n,e),a=Number(flag(r,"--max"))||500;let s;try{s=await o.listRecursive("")}catch(e){return{ok:!1,backend:n.backend,where:o.describe,error:e&&e.message||String(e),findings:[],checked:0}}const i=e.secret||null,c=[],l=[];let u=0;for(const t of s){const r=String(t.Path||t.Name);if(u>=a){l.push({path:r,reason:`stopped after ${a} files`});continue}if(Number(t.Size)>2097152){l.push({path:r,reason:"larger than 2097152 bytes"});continue}let n;u+=1;try{n=await o.cat(r)}catch(e){l.push({path:r,reason:e&&e.message||String(e)});continue}const s=inspect(r,n,{secret:i});s.dangerous&&c.push({path:r,reason:s.reason})}return{ok:0===c.length,backend:n.backend,remote:n.remote,root:n.root,where:o.describe,checked:u,files:s.length,uninspected:l,findings:c}}function rcloneLsjsonRecursive(e,t){const r=rcloneRun(e,["lsjson",remoteSpecOf(e,t),"--files-only","--recursive"]),n=String(r).trim();if(!n)return[];const o=JSON.parse(n);return Array.isArray(o)?o:[]}module.exports={DEFAULT_REMOTE:"gdrive",DEFAULT_ROOT:"AEGIS-AGPL",DEFAULT_BACKEND:"aegiscloud",BACKEND_CLOUD:"aegiscloud",BACKEND_RCLONE:"rclone",CLOUD_PREFIX:CLOUD_PREFIX,BACKEND_ENV:BACKEND_ENV,API_BASE_ENV:API_BASE_ENV,RECORDS_DIR:"records",INDEX_NAME:INDEX_NAME,ANCHOR_SUFFIX:ANCHOR_SUFFIX,ANCHOR_KIND:ANCHOR_KIND,INDEX_KIND:INDEX_KIND,RCLONE_ENV:RCLONE_ENV,REMOTE_ENV:REMOTE_ENV,ROOT_ENV:ROOT_ENV,inspect:inspect,assertPublishable:assertPublishable,publish:publish,checkAnchor:checkAnchor,list:list,audit:audit,localAnchor:localAnchor,relativeToRoot:relativeToRoot,remoteSpecOf:remoteSpecOf,baseName:baseName,driveUrl:driveUrl,vaultTarget:vaultTarget,rcloneBinary:rcloneBinary,rcloneCat:rcloneCat,transportFor:transportFor,cloudApiKey:cloudApiKey,backendFor:backendFor,sha256:sha256,flag:flag,has:has};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const path=require("node:path"),FACE=Object.freeze({TUI:"tui",GUI:"gui"}),RUN_AS_NODE="ELECTRON_RUN_AS_NODE",FORCE_TUI=["--tui","code"],COMPAT_BIN="aegiscode";function faceRoot(e,n){return path.join(e,"faces",n)}function cliEntry(e){return path.join(faceRoot(e,"cli"),"bin","aegiscode.js")}function binName(e){return path.basename(String(e||"aegis")).replace(/\.(exe|cmd|bat|AppImage)$/i,"").replace(/\.js$/,"")}function plan(e){const n=e||{};if(!n.packaged)return null;const t=n.execPath,a=n.resourcesPath,i=Array.isArray(n.argv)?n.argv.map(String):[];if(!t||!a)return null;const r=(e,n)=>({face:FACE.TUI,exec:t,args:[cliEntry(a),...e],env:{[RUN_AS_NODE]:"1"},reason:n});if(binName(n.invokedAs)===COMPAT_BIN)return r(i,"aegiscode is the compatibility bin");const c=i.find(
|
|
3
|
+
"use strict";const path=require("node:path"),FACE=Object.freeze({TUI:"tui",GUI:"gui"}),RUN_AS_NODE="ELECTRON_RUN_AS_NODE",FORCE_TUI=["--tui","code"],COMPAT_BIN="aegiscode";function faceRoot(e,n){return path.join(e,"faces",n)}function cliEntry(e){return path.join(faceRoot(e,"cli"),"bin","aegiscode.js")}function binName(e){return path.basename(String(e||"aegis")).replace(/\.(exe|cmd|bat|AppImage)$/i,"").replace(/\.js$/,"")}function plan(e){const n=e||{};if(!n.packaged)return null;const t=n.execPath,a=n.resourcesPath,i=Array.isArray(n.argv)?n.argv.map(String):[];if(!t||!a)return null;const r=(e,n)=>({face:FACE.TUI,exec:t,args:[cliEntry(a),...e],env:{[RUN_AS_NODE]:"1"},reason:n});if(binName(n.invokedAs)===COMPAT_BIN)return r(i,"aegiscode is the compatibility bin");const c=i.find(e=>FORCE_TUI.includes(e));return c?r(i.filter(e=>e!==c),`${c} asks for the terminal face`):null}function spawnOptions(e,n){return e?{exec:e.exec,args:e.args,env:Object.assign({},n||{},e.env)}:null}module.exports={plan:plan,spawnOptions:spawnOptions,FACE:FACE,RUN_AS_NODE:RUN_AS_NODE,COMPAT_BIN:COMPAT_BIN,FORCE_TUI:FORCE_TUI,cliEntry:cliEntry,faceRoot:faceRoot,binName:binName};
|
|
@@ -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 haystack(e){if(!e||"object"!=typeof e)return"";const t=[e.title,e.summary,e.cwd,e.id].filter(
|
|
3
|
+
"use strict";function haystack(e){if(!e||"object"!=typeof e)return"";const t=[e.title,e.summary,e.cwd,e.id].filter(e=>"string"==typeof e&&e),s=Array.isArray(e.messages)?e.messages:[];for(const e of s)if(e&&"user"===e.role&&"string"==typeof e.content&&e.content){t.push(e.content.slice(0,400));break}return t.join("\n")}function scoreSession(e,t){const s=String(e||"").trim().toLowerCase();if(!s)return{matched:!0,score:0,field:"all"};const r="string"==typeof(t&&t.title)?t.title.toLowerCase():"",n=haystack(t).toLowerCase();if(r&&r===s)return{matched:!0,score:1e3,field:"title"};if(r&&r.startsWith(s))return{matched:!0,score:900,field:"title"};const o=r?r.indexOf(s):-1;if(-1!==o)return{matched:!0,score:700-o,field:"title"};const i=n.indexOf(s);if(-1!==i)return{matched:!0,score:Math.max(1,400-i),field:"body"};if(r){let e=100,t=-2,n=-1,o=!0;for(const i of s){const s=r.indexOf(i,n+1);if(-1===s){o=!1;break}e+=s===t+1?15:5,0===s&&(e+=20),t=s,n=s}if(o)return{matched:!0,score:e,field:"title"}}return{matched:!1,score:0,field:null}}function rankSessions(e,t){const s=Array.isArray(t)?t:[],r=String(e||"").trim();if(!r)return s.slice();const n=[];for(let e=0;e<s.length;e+=1){const t=s[e],o=scoreSession(r,t);o.matched&&n.push({s:t,i:e,score:o.score})}return n.sort((e,t)=>t.score-e.score||e.i-t.i),n.map(e=>e.s)}function matchReason(e,t){const s=String(e||"").trim();if(!s)return null;const r=scoreSession(s,t);return r.matched?"title"===r.field?"title":"body"===r.field?"content":null:null}module.exports={haystack:haystack,scoreSession:scoreSession,rankSessions:rankSessions,matchReason:matchReason};
|
|
@@ -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"),{aegisHome:aegisHome}=require("./credentials.js"),STORE_FILE="sessions.json",STORE_VERSION=2,MAX_MESSAGES_PER_SESSION=2e3;function storeDir(e){return e||aegisHome()}function storeFile(e){return path.join(storeDir(e),STORE_FILE)}function nextSeq(e){const t=("number"==typeof e.__seq?e.__seq:0)+1;return e.__seq=t,t}function toEpochMs(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.trim()){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function load(e){try{const t=JSON.parse(fs.readFileSync(storeFile(e),"utf8"));if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}return{}}function atomicWrite(e,t){fs.mkdirSync(path.dirname(e),{recursive:!0});const n=`${e}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),fs.renameSync(n,e);try{fs.chmodSync(e,384)}catch{}}const LOCK_STALE_MS=3e4,LOCK_WAIT_MS=(()=>{const e=Number(process.env.AEGIS_STORE_LOCK_WAIT_MS);return Number.isFinite(e)&&e>0?e:15e3})(),SLEEP_CELL=new Int32Array(new SharedArrayBuffer(4));function lockFile(e){return`${storeFile(e)}.lock`}function acquireLock(e){const t=lockFile(e);try{fs.mkdirSync(path.dirname(t),{recursive:!0})}catch{return!1}const n=Date.now()+LOCK_WAIT_MS,s=Math.max(200,Math.ceil(LOCK_WAIT_MS/5)+200);for(let e=0;e<s;e++)try{const e=fs.openSync(t,"wx");return fs.writeSync(e,String(process.pid)),fs.closeSync(e),!0}catch{let e=null;try{e=Date.now()-fs.statSync(t).mtimeMs}catch{continue}if(lockAbandoned(t,e)){try{fs.unlinkSync(t)}catch{}continue}if(Date.now()>=n)return!1;Atomics.wait(SLEEP_CELL,0,0,5)}return!1}function pidAlive(e){try{return process.kill(e,0),!0}catch(e){return e&&"EPERM"===e.code}}function lockAbandoned(e,t){let n=0;try{n=Number(String(fs.readFileSync(e,"utf8")).trim())}catch{n=0}return Number.isInteger(n)&&n>0?!pidAlive(n):t>
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),STORE_FILE="sessions.json",STORE_VERSION=2,MAX_MESSAGES_PER_SESSION=2e3;function storeDir(e){return e||aegisHome()}function storeFile(e){return path.join(storeDir(e),STORE_FILE)}function nextSeq(e){const t=("number"==typeof e.__seq?e.__seq:0)+1;return e.__seq=t,t}function toEpochMs(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.trim()){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function load(e){try{const t=JSON.parse(fs.readFileSync(storeFile(e),"utf8"));if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}return{}}function atomicWrite(e,t){fs.mkdirSync(path.dirname(e),{recursive:!0});const n=`${e}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),fs.renameSync(n,e);try{fs.chmodSync(e,384)}catch{}}const LOCK_STALE_MS=3e4,LOCK_WAIT_MS=(()=>{const e=Number(process.env.AEGIS_STORE_LOCK_WAIT_MS);return Number.isFinite(e)&&e>0?e:15e3})(),SLEEP_CELL=new Int32Array(new SharedArrayBuffer(4));function lockFile(e){return`${storeFile(e)}.lock`}function acquireLock(e){const t=lockFile(e);try{fs.mkdirSync(path.dirname(t),{recursive:!0})}catch{return!1}const n=Date.now()+LOCK_WAIT_MS,s=Math.max(200,Math.ceil(LOCK_WAIT_MS/5)+200);for(let e=0;e<s;e++)try{const e=fs.openSync(t,"wx");return fs.writeSync(e,String(process.pid)),fs.closeSync(e),!0}catch{let e=null;try{e=Date.now()-fs.statSync(t).mtimeMs}catch{continue}if(lockAbandoned(t,e)){try{fs.unlinkSync(t)}catch{}continue}if(Date.now()>=n)return!1;Atomics.wait(SLEEP_CELL,0,0,5)}return!1}function pidAlive(e){try{return process.kill(e,0),!0}catch(e){return e&&"EPERM"===e.code}}function lockAbandoned(e,t){let n=0;try{n=Number(String(fs.readFileSync(e,"utf8")).trim())}catch{n=0}return Number.isInteger(n)&&n>0?!pidAlive(n):t>3e4}function releaseLock(e){try{fs.unlinkSync(lockFile(e))}catch{}}function mutate(e,t){if(!acquireLock(e))throw new Error(`session store is locked by another writer: ${lockFile(e)} (waited ${LOCK_WAIT_MS}ms — refusing to write unlocked and overwrite it)`);try{const n=load(e),s=t(n);return save(e,n),s}finally{releaseLock(e)}}function save(e,t){atomicWrite(storeFile(e),t)}function trimMessages(e){return Array.isArray(e)?e.length<=2e3?e:e.slice(e.length-2e3):[]}function upsertSession(e,t){const n=t&&t.id;if(!n)throw new Error("session.id is required");return mutate(e,e=>{const s=e[n]||{messages:[]};e[n]={...s,...t,id:n,version:2};const r=t&&!0===t.seed,i="string"==typeof s.title&&s.title;return!0===s.named&&i?(e[n].title=s.title,e[n].named=!0):r&&i&&s.title&&(e[n].title=s.title),delete e[n].seed,!1!==t.pending&&(e[n].pending=!0),e[n].updatedAt||(e[n].updatedAt=Date.now()),e[n].seq=nextSeq(e),e[n]})}function appendMessage(e,t,n){if(!t)throw new Error("sessionId is required");return mutate(e,e=>{const s=e[t]||{id:t,messages:[]},r=Array.isArray(s.messages)?s.messages:[];return s.messages=trimMessages(r.concat(n)),s.updatedAt=Date.now(),s.pending=!0,s.seq=nextSeq(e),e[t]=s,s})}function recordExchange(e,t){const n=t||{};if(!n.sessionId)return null;const s=n.sessionId;return mutate(e,e=>{const t=e[s]||{id:s,messages:[]},r=Array.isArray(t.messages)?t.messages:[],i=n.ts||(new Date).toISOString(),o={role:"user",content:null==n.prompt?"":String(n.prompt),ts:i},a={role:"assistant",content:null==n.reply?"":String(n.reply),ts:i};return n.tokens&&(a.tokens=n.tokens),"number"==typeof n.costUsd&&(a.costUsd=n.costUsd),n.status&&(a.status=n.status),n.model&&(a.model=n.model),n.provider&&(a.provider=n.provider),n.origin&&(o.origin=n.origin,a.origin=n.origin),t.messages=trimMessages(r.concat([o,a])),t.title=t.title||String(n.prompt||"").slice(0,60),n.cwd&&(t.cwd=n.cwd),t.origin=n.origin||t.origin||"unknown",t.updatedAt=Date.now(),t.pending=!0===n.pending,t.seq=nextSeq(e),e[s]=t,t})}function setTitle(e,t,n,s){const r=String(null==n?"":n).trim().slice(0,200);if(!t||!r)return null;const i=s&&!0===s.named;return mutate(e,e=>{const n=e[t];return n?(n.title=r,i&&(n.named=!0),n.updatedAt=Date.now(),n.seq=nextSeq(e),n):null})}function listSessions(e){const t=load(e);return Object.values(t).filter(e=>e&&e.id).sort((e,t)=>(t.updatedAt||0)-(e.updatedAt||0)||(t.seq||0)-(e.seq||0))}function getSession(e,t){return load(e)[t]||null}function deleteSession(e,t){return mutate(e,e=>(delete e[t],{ok:!0}))}function markSynced(e,t,n){return mutate(e,e=>{const s=e[t];return s?(s.pending=!1,s.lastSyncedAt=Date.now(),n&&n.remoteId&&(s.remoteId=n.remoteId),s.seq=nextSeq(e),s):null})}function markPending(e,t){return mutate(e,e=>{const n=e[t];return n?(n.pending=!0,n.seq=nextSeq(e),n):null})}function listPending(e){return listSessions(e).filter(e=>!1!==e.pending)}function mergeRemoteSessions(e,t){const n=Array.isArray(t)?t:[];return n.length?mutate(e,e=>{let t=0;for(const s of n){const n=s&&(s.session_id||s.id);if(!n)continue;const r=e[n],i=toEpochMs(s.updated_at??s.updatedAt);r&&(r.pending||(r.updatedAt||0)>=i)||(e[n]={id:n,title:s.title||r&&r.title||"",messages:Array.isArray(s.messages)?s.messages:[],updatedAt:i||Date.now(),pending:!1,lastSyncedAt:Date.now(),remoteId:s.session_id||s.id,origin:s.source||r&&r.origin||"cloud",version:2},e[n].seq=nextSeq(e),t+=1)}return t}):0}function listSummaries(e,t=8){return listSessions(e).slice(0,t).map(e=>{const t=Array.isArray(e.messages)?e.messages:[],n=t.find(e=>e&&"user"===e.role);return{id:e.id,cwd:(e.cwd||"").split(/[\\/]/).filter(Boolean).pop()||"~",summary:String(e.title||n&&n.content||"").slice(0,60),time:new Date(e.updatedAt||Date.now()).toISOString(),own:!0,origin:e.origin||"unknown",messages:t.length,pending:!0===e.pending,dir:String(e.cwd||"")}})}function readTranscript(e,t){const n=getSession(e,t);return n?(Array.isArray(n.messages)?n.messages:[]).filter(e=>e&&("user"===e.role||"assistant"===e.role)).map(e=>({role:e.role,text:null==e.content?"":String(e.content)})):[]}function adopt(e,t){const n=storeFile(t);if(!(()=>{try{return fs.existsSync(n)}catch{return!1}})())return{adopted:!1,sessions:0,from:n,reason:"no legacy store"};const s=(()=>{try{const e=JSON.parse(fs.readFileSync(n,"utf8"));return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}})(),r=Object.values(s).filter(e=>e&&e.id);if(!r.length)return{adopted:!1,sessions:0,from:n,reason:"legacy store empty"};let i=0;return mutate(e,e=>{for(const t of r)e[t.id]||(e[t.id]={...t,adoptedFrom:n,version:2},e[t.id].seq=nextSeq(e),i+=1);return e.__seq=Math.max(e.__seq||0,s.__seq||0),e.version=2,null}),i?{adopted:!0,sessions:i,from:n}:{adopted:!1,sessions:0,from:n,reason:"already adopted"}}function toMarkdown(e){const t=e&&(e.title||e.id)||"session",n=e&&Array.isArray(e.messages)?e.messages:[],s=[`# ${t}`,""];for(const e of n){const t=e&&e.role||"unknown",n=t.charAt(0).toUpperCase()+t.slice(1),r=e&&(e.content||e.text)||"";s.push(`## ${n}`,"",r,"")}return s.join("\n")}function toJson(e){return JSON.stringify(e,null,2)}module.exports={STORE_FILE:STORE_FILE,STORE_VERSION:2,MAX_MESSAGES_PER_SESSION:2e3,storeDir:storeDir,storeFile:storeFile,lockFile:lockFile,LOCK_STALE_MS:3e4,LOCK_WAIT_MS:LOCK_WAIT_MS,toEpochMs:toEpochMs,load:load,save:save,upsertSession:upsertSession,appendMessage:appendMessage,recordExchange:recordExchange,setTitle:setTitle,listSessions:listSessions,getSession:getSession,deleteSession:deleteSession,markSynced:markSynced,markPending:markPending,listPending:listPending,mergeRemoteSessions:mergeRemoteSessions,listSummaries:listSummaries,readTranscript:readTranscript,adopt:adopt,toMarkdown:toMarkdown,toJson:toJson};
|