@elizaos/autonomous 2.0.0-alpha.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +2 -0
- package/LICENSE +21 -0
- package/dist/package.json +914 -0
- package/dist/packages/autonomous/src/actions/emote.d.ts +14 -0
- package/dist/packages/autonomous/src/actions/emote.d.ts.map +1 -0
- package/dist/packages/autonomous/src/actions/emote.js +85 -0
- package/dist/packages/autonomous/src/actions/restart.d.ts +19 -0
- package/dist/packages/autonomous/src/actions/restart.d.ts.map +1 -0
- package/dist/packages/autonomous/src/actions/restart.js +86 -0
- package/dist/packages/autonomous/src/actions/send-message.d.ts +3 -0
- package/dist/packages/autonomous/src/actions/send-message.d.ts.map +1 -0
- package/dist/packages/autonomous/src/actions/send-message.js +144 -0
- package/dist/packages/autonomous/src/actions/stream-control.d.ts +15 -0
- package/dist/packages/autonomous/src/actions/stream-control.d.ts.map +1 -0
- package/dist/packages/autonomous/src/actions/stream-control.js +357 -0
- package/dist/packages/autonomous/src/actions/switch-stream-source.d.ts +16 -0
- package/dist/packages/autonomous/src/actions/switch-stream-source.d.ts.map +1 -0
- package/dist/packages/autonomous/src/actions/switch-stream-source.js +94 -0
- package/dist/packages/autonomous/src/actions/terminal.d.ts +14 -0
- package/dist/packages/autonomous/src/actions/terminal.d.ts.map +1 -0
- package/dist/packages/autonomous/src/actions/terminal.js +154 -0
- package/dist/packages/autonomous/src/api/agent-admin-routes.d.ts +38 -0
- package/dist/packages/autonomous/src/api/agent-admin-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/agent-admin-routes.js +93 -0
- package/dist/packages/autonomous/src/api/agent-lifecycle-routes.d.ts +16 -0
- package/dist/packages/autonomous/src/api/agent-lifecycle-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/agent-lifecycle-routes.js +80 -0
- package/dist/packages/autonomous/src/api/agent-model.d.ts +12 -0
- package/dist/packages/autonomous/src/api/agent-model.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/agent-model.js +123 -0
- package/dist/packages/autonomous/src/api/agent-transfer-routes.d.ts +16 -0
- package/dist/packages/autonomous/src/api/agent-transfer-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/agent-transfer-routes.js +124 -0
- package/dist/packages/autonomous/src/api/apps-routes.d.ts +19 -0
- package/dist/packages/autonomous/src/api/apps-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/apps-routes.js +128 -0
- package/dist/packages/autonomous/src/api/auth-routes.d.ts +11 -0
- package/dist/packages/autonomous/src/api/auth-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/auth-routes.js +54 -0
- package/dist/packages/autonomous/src/api/bsc-trade.d.ts +34 -0
- package/dist/packages/autonomous/src/api/bsc-trade.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/bsc-trade.js +567 -0
- package/dist/packages/autonomous/src/api/bug-report-routes.d.ts +7 -0
- package/dist/packages/autonomous/src/api/bug-report-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/bug-report-routes.js +124 -0
- package/dist/packages/autonomous/src/api/character-routes.d.ts +50 -0
- package/dist/packages/autonomous/src/api/character-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/character-routes.js +302 -0
- package/dist/packages/autonomous/src/api/cloud-billing-routes.d.ts +14 -0
- package/dist/packages/autonomous/src/api/cloud-billing-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/cloud-billing-routes.js +400 -0
- package/dist/packages/autonomous/src/api/cloud-compat-routes.d.ts +15 -0
- package/dist/packages/autonomous/src/api/cloud-compat-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/cloud-compat-routes.js +131 -0
- package/dist/packages/autonomous/src/api/cloud-routes.d.ts +62 -0
- package/dist/packages/autonomous/src/api/cloud-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/cloud-routes.js +339 -0
- package/dist/packages/autonomous/src/api/cloud-status-routes.d.ts +15 -0
- package/dist/packages/autonomous/src/api/cloud-status-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/cloud-status-routes.js +165 -0
- package/dist/packages/autonomous/src/api/compat-utils.d.ts +49 -0
- package/dist/packages/autonomous/src/api/compat-utils.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/compat-utils.js +126 -0
- package/dist/packages/autonomous/src/api/connector-health.d.ts +34 -0
- package/dist/packages/autonomous/src/api/connector-health.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/connector-health.js +109 -0
- package/dist/packages/autonomous/src/api/coordinator-wiring.d.ts +46 -0
- package/dist/packages/autonomous/src/api/coordinator-wiring.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/coordinator-wiring.js +99 -0
- package/dist/packages/autonomous/src/api/credit-detection.d.ts +9 -0
- package/dist/packages/autonomous/src/api/credit-detection.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/credit-detection.js +41 -0
- package/dist/packages/autonomous/src/api/database.d.ts +33 -0
- package/dist/packages/autonomous/src/api/database.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/database.js +1019 -0
- package/dist/packages/autonomous/src/api/diagnostics-routes.d.ts +46 -0
- package/dist/packages/autonomous/src/api/diagnostics-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/diagnostics-routes.js +241 -0
- package/dist/packages/autonomous/src/api/drop-service.d.ts +26 -0
- package/dist/packages/autonomous/src/api/drop-service.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/drop-service.js +134 -0
- package/dist/packages/autonomous/src/api/early-logs.d.ts +29 -0
- package/dist/packages/autonomous/src/api/early-logs.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/early-logs.js +95 -0
- package/dist/packages/autonomous/src/api/http-helpers.d.ts +50 -0
- package/dist/packages/autonomous/src/api/http-helpers.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/http-helpers.js +145 -0
- package/dist/packages/autonomous/src/api/hyperscape-routes-loader.d.ts +12 -0
- package/dist/packages/autonomous/src/api/hyperscape-routes-loader.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/hyperscape-routes-loader.js +21 -0
- package/dist/packages/autonomous/src/api/index.d.ts +62 -0
- package/dist/packages/autonomous/src/api/index.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/index.js +60 -0
- package/dist/packages/autonomous/src/api/knowledge-routes.d.ts +23 -0
- package/dist/packages/autonomous/src/api/knowledge-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/knowledge-routes.js +887 -0
- package/dist/packages/autonomous/src/api/knowledge-service-loader.d.ts +51 -0
- package/dist/packages/autonomous/src/api/knowledge-service-loader.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/knowledge-service-loader.js +34 -0
- package/dist/packages/autonomous/src/api/memory-bounds.d.ts +51 -0
- package/dist/packages/autonomous/src/api/memory-bounds.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/memory-bounds.js +81 -0
- package/dist/packages/autonomous/src/api/memory-routes.d.ts +9 -0
- package/dist/packages/autonomous/src/api/memory-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/memory-routes.js +241 -0
- package/dist/packages/autonomous/src/api/merkle-tree.d.ts +90 -0
- package/dist/packages/autonomous/src/api/merkle-tree.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/merkle-tree.js +174 -0
- package/dist/packages/autonomous/src/api/models-routes.d.ts +14 -0
- package/dist/packages/autonomous/src/api/models-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/models-routes.js +37 -0
- package/dist/packages/autonomous/src/api/nfa-routes.d.ts +5 -0
- package/dist/packages/autonomous/src/api/nfa-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/nfa-routes.js +125 -0
- package/dist/packages/autonomous/src/api/nft-verify.d.ts +35 -0
- package/dist/packages/autonomous/src/api/nft-verify.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/nft-verify.js +130 -0
- package/dist/packages/autonomous/src/api/og-tracker.d.ts +28 -0
- package/dist/packages/autonomous/src/api/og-tracker.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/og-tracker.js +60 -0
- package/dist/packages/autonomous/src/api/parse-action-block.d.ts +36 -0
- package/dist/packages/autonomous/src/api/parse-action-block.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/parse-action-block.js +110 -0
- package/dist/packages/autonomous/src/api/permissions-routes.d.ts +32 -0
- package/dist/packages/autonomous/src/api/permissions-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/permissions-routes.js +149 -0
- package/dist/packages/autonomous/src/api/plugin-validation.d.ts +86 -0
- package/dist/packages/autonomous/src/api/plugin-validation.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/plugin-validation.js +259 -0
- package/dist/packages/autonomous/src/api/provider-switch-config.d.ts +20 -0
- package/dist/packages/autonomous/src/api/provider-switch-config.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/provider-switch-config.js +33 -0
- package/dist/packages/autonomous/src/api/registry-routes.d.ts +30 -0
- package/dist/packages/autonomous/src/api/registry-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/registry-routes.js +90 -0
- package/dist/packages/autonomous/src/api/registry-service.d.ts +77 -0
- package/dist/packages/autonomous/src/api/registry-service.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/registry-service.js +190 -0
- package/dist/packages/autonomous/src/api/route-helpers.d.ts +16 -0
- package/dist/packages/autonomous/src/api/route-helpers.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/route-helpers.js +1 -0
- package/dist/packages/autonomous/src/api/sandbox-routes.d.ts +12 -0
- package/dist/packages/autonomous/src/api/sandbox-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/sandbox-routes.js +1334 -0
- package/dist/packages/autonomous/src/api/server.d.ts +416 -0
- package/dist/packages/autonomous/src/api/server.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/server.js +13467 -0
- package/dist/packages/autonomous/src/api/signal-routes.d.ts +41 -0
- package/dist/packages/autonomous/src/api/signal-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/signal-routes.js +168 -0
- package/dist/packages/autonomous/src/api/stream-persistence.d.ts +64 -0
- package/dist/packages/autonomous/src/api/stream-persistence.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/stream-persistence.js +231 -0
- package/dist/packages/autonomous/src/api/stream-route-state.d.ts +50 -0
- package/dist/packages/autonomous/src/api/stream-route-state.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/stream-route-state.js +1 -0
- package/dist/packages/autonomous/src/api/stream-routes.d.ts +45 -0
- package/dist/packages/autonomous/src/api/stream-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/stream-routes.js +808 -0
- package/dist/packages/autonomous/src/api/stream-voice-routes.d.ts +36 -0
- package/dist/packages/autonomous/src/api/stream-voice-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/stream-voice-routes.js +119 -0
- package/dist/packages/autonomous/src/api/streaming-text.d.ts +9 -0
- package/dist/packages/autonomous/src/api/streaming-text.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/streaming-text.js +85 -0
- package/dist/packages/autonomous/src/api/streaming-types.d.ts +30 -0
- package/dist/packages/autonomous/src/api/streaming-types.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/streaming-types.js +1 -0
- package/dist/packages/autonomous/src/api/subscription-routes.d.ts +41 -0
- package/dist/packages/autonomous/src/api/subscription-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/subscription-routes.js +191 -0
- package/dist/packages/autonomous/src/api/terminal-run-limits.d.ts +5 -0
- package/dist/packages/autonomous/src/api/terminal-run-limits.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/terminal-run-limits.js +22 -0
- package/dist/packages/autonomous/src/api/training-backend-check.d.ts +8 -0
- package/dist/packages/autonomous/src/api/training-backend-check.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/training-backend-check.js +28 -0
- package/dist/packages/autonomous/src/api/training-routes.d.ts +44 -0
- package/dist/packages/autonomous/src/api/training-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/training-routes.js +195 -0
- package/dist/packages/autonomous/src/api/training-service-like.d.ts +38 -0
- package/dist/packages/autonomous/src/api/training-service-like.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/training-service-like.js +1 -0
- package/dist/packages/autonomous/src/api/trajectory-routes.d.ts +17 -0
- package/dist/packages/autonomous/src/api/trajectory-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/trajectory-routes.js +377 -0
- package/dist/packages/autonomous/src/api/trigger-routes.d.ts +75 -0
- package/dist/packages/autonomous/src/api/trigger-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/trigger-routes.js +268 -0
- package/dist/packages/autonomous/src/api/twitter-verify.d.ts +25 -0
- package/dist/packages/autonomous/src/api/twitter-verify.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/twitter-verify.js +168 -0
- package/dist/packages/autonomous/src/api/tx-service.d.ts +47 -0
- package/dist/packages/autonomous/src/api/tx-service.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/tx-service.js +156 -0
- package/dist/packages/autonomous/src/api/wallet-dex-prices.d.ts +43 -0
- package/dist/packages/autonomous/src/api/wallet-dex-prices.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/wallet-dex-prices.js +149 -0
- package/dist/packages/autonomous/src/api/wallet-evm-balance.d.ts +65 -0
- package/dist/packages/autonomous/src/api/wallet-evm-balance.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/wallet-evm-balance.js +662 -0
- package/dist/packages/autonomous/src/api/wallet-routes.d.ts +35 -0
- package/dist/packages/autonomous/src/api/wallet-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/wallet-routes.js +328 -0
- package/dist/packages/autonomous/src/api/wallet-rpc.d.ts +38 -0
- package/dist/packages/autonomous/src/api/wallet-rpc.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/wallet-rpc.js +143 -0
- package/dist/packages/autonomous/src/api/wallet-trading-profile.d.ts +51 -0
- package/dist/packages/autonomous/src/api/wallet-trading-profile.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/wallet-trading-profile.js +547 -0
- package/dist/packages/autonomous/src/api/wallet.d.ts +32 -0
- package/dist/packages/autonomous/src/api/wallet.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/wallet.js +553 -0
- package/dist/packages/autonomous/src/api/whatsapp-routes.d.ts +41 -0
- package/dist/packages/autonomous/src/api/whatsapp-routes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/whatsapp-routes.js +182 -0
- package/dist/packages/autonomous/src/api/zip-utils.d.ts +8 -0
- package/dist/packages/autonomous/src/api/zip-utils.d.ts.map +1 -0
- package/dist/packages/autonomous/src/api/zip-utils.js +115 -0
- package/dist/packages/autonomous/src/auth/anthropic.d.ts +25 -0
- package/dist/packages/autonomous/src/auth/anthropic.d.ts.map +1 -0
- package/dist/packages/autonomous/src/auth/anthropic.js +40 -0
- package/dist/packages/autonomous/src/auth/apply-stealth.d.ts +8 -0
- package/dist/packages/autonomous/src/auth/apply-stealth.d.ts.map +1 -0
- package/dist/packages/autonomous/src/auth/apply-stealth.js +34 -0
- package/dist/packages/autonomous/src/auth/claude-code-stealth.d.ts +2 -0
- package/dist/packages/autonomous/src/auth/claude-code-stealth.d.ts.map +1 -0
- package/dist/packages/autonomous/src/auth/claude-code-stealth.js +104 -0
- package/dist/packages/autonomous/src/auth/credentials.d.ts +55 -0
- package/dist/packages/autonomous/src/auth/credentials.d.ts.map +1 -0
- package/dist/packages/autonomous/src/auth/credentials.js +182 -0
- package/dist/packages/autonomous/src/auth/index.d.ts +7 -0
- package/dist/packages/autonomous/src/auth/index.d.ts.map +1 -0
- package/dist/packages/autonomous/src/auth/index.js +3 -0
- package/dist/packages/autonomous/src/auth/openai-codex.d.ts +27 -0
- package/dist/packages/autonomous/src/auth/openai-codex.d.ts.map +1 -0
- package/dist/packages/autonomous/src/auth/openai-codex.js +72 -0
- package/dist/packages/autonomous/src/auth/types.d.ts +18 -0
- package/dist/packages/autonomous/src/auth/types.d.ts.map +1 -0
- package/dist/packages/autonomous/src/auth/types.js +8 -0
- package/dist/packages/autonomous/src/awareness/registry.d.ts +27 -0
- package/dist/packages/autonomous/src/awareness/registry.d.ts.map +1 -0
- package/dist/packages/autonomous/src/awareness/registry.js +161 -0
- package/dist/packages/autonomous/src/bin.d.ts +3 -0
- package/dist/packages/autonomous/src/bin.d.ts.map +1 -0
- package/dist/packages/autonomous/src/bin.js +6 -0
- package/dist/packages/autonomous/src/cli/index.d.ts +2 -0
- package/dist/packages/autonomous/src/cli/index.d.ts.map +1 -0
- package/dist/packages/autonomous/src/cli/index.js +30 -0
- package/dist/packages/autonomous/src/cli/parse-duration.d.ts +5 -0
- package/dist/packages/autonomous/src/cli/parse-duration.d.ts.map +1 -0
- package/dist/packages/autonomous/src/cli/parse-duration.js +27 -0
- package/dist/packages/autonomous/src/cloud/base-url.d.ts +3 -0
- package/dist/packages/autonomous/src/cloud/base-url.d.ts.map +1 -0
- package/dist/packages/autonomous/src/cloud/base-url.js +40 -0
- package/dist/packages/autonomous/src/cloud/validate-url.d.ts +2 -0
- package/dist/packages/autonomous/src/cloud/validate-url.d.ts.map +1 -0
- package/dist/packages/autonomous/src/cloud/validate-url.js +158 -0
- package/dist/packages/autonomous/src/config/character-schema.d.ts +25 -0
- package/dist/packages/autonomous/src/config/character-schema.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/character-schema.js +40 -0
- package/dist/packages/autonomous/src/config/config.d.ts +9 -0
- package/dist/packages/autonomous/src/config/config.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/config.js +119 -0
- package/dist/packages/autonomous/src/config/env-vars.d.ts +3 -0
- package/dist/packages/autonomous/src/config/env-vars.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/env-vars.js +77 -0
- package/dist/packages/autonomous/src/config/includes.d.ts +26 -0
- package/dist/packages/autonomous/src/config/includes.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/includes.js +148 -0
- package/dist/packages/autonomous/src/config/index.d.ts +16 -0
- package/dist/packages/autonomous/src/config/index.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/index.js +15 -0
- package/dist/packages/autonomous/src/config/object-utils.d.ts +2 -0
- package/dist/packages/autonomous/src/config/object-utils.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/object-utils.js +6 -0
- package/dist/packages/autonomous/src/config/paths.d.ts +12 -0
- package/dist/packages/autonomous/src/config/paths.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/paths.js +62 -0
- package/dist/packages/autonomous/src/config/plugin-auto-enable.d.ts +16 -0
- package/dist/packages/autonomous/src/config/plugin-auto-enable.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/plugin-auto-enable.js +384 -0
- package/dist/packages/autonomous/src/config/schema.d.ts +87 -0
- package/dist/packages/autonomous/src/config/schema.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/schema.js +928 -0
- package/dist/packages/autonomous/src/config/telegram-custom-commands.d.ts +25 -0
- package/dist/packages/autonomous/src/config/telegram-custom-commands.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/telegram-custom-commands.js +71 -0
- package/dist/packages/autonomous/src/config/types.agent-defaults.d.ts +331 -0
- package/dist/packages/autonomous/src/config/types.agent-defaults.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/types.agent-defaults.js +1 -0
- package/dist/packages/autonomous/src/config/types.agents.d.ts +109 -0
- package/dist/packages/autonomous/src/config/types.agents.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/types.agents.js +1 -0
- package/dist/packages/autonomous/src/config/types.autonomous.d.ts +3 -0
- package/dist/packages/autonomous/src/config/types.autonomous.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/types.autonomous.js +1 -0
- package/dist/packages/autonomous/src/config/types.d.ts +8 -0
- package/dist/packages/autonomous/src/config/types.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/types.gateway.d.ts +216 -0
- package/dist/packages/autonomous/src/config/types.gateway.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/types.gateway.js +1 -0
- package/dist/packages/autonomous/src/config/types.hooks.d.ts +107 -0
- package/dist/packages/autonomous/src/config/types.hooks.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/types.hooks.js +1 -0
- package/dist/packages/autonomous/src/config/types.js +7 -0
- package/dist/packages/autonomous/src/config/types.messages.d.ts +176 -0
- package/dist/packages/autonomous/src/config/types.messages.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/types.messages.js +1 -0
- package/dist/packages/autonomous/src/config/types.milady.d.ts +631 -0
- package/dist/packages/autonomous/src/config/types.milady.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/types.milady.js +1 -0
- package/dist/packages/autonomous/src/config/types.tools.d.ts +400 -0
- package/dist/packages/autonomous/src/config/types.tools.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/types.tools.js +1 -0
- package/dist/packages/autonomous/src/config/zod-schema.agent-runtime.d.ts +1062 -0
- package/dist/packages/autonomous/src/config/zod-schema.agent-runtime.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/zod-schema.agent-runtime.js +721 -0
- package/dist/packages/autonomous/src/config/zod-schema.core.d.ts +1021 -0
- package/dist/packages/autonomous/src/config/zod-schema.core.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/zod-schema.core.js +694 -0
- package/dist/packages/autonomous/src/config/zod-schema.d.ts +4817 -0
- package/dist/packages/autonomous/src/config/zod-schema.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/zod-schema.hooks.d.ts +88 -0
- package/dist/packages/autonomous/src/config/zod-schema.hooks.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/zod-schema.hooks.js +133 -0
- package/dist/packages/autonomous/src/config/zod-schema.js +779 -0
- package/dist/packages/autonomous/src/config/zod-schema.providers-core.d.ts +2976 -0
- package/dist/packages/autonomous/src/config/zod-schema.providers-core.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/zod-schema.providers-core.js +1006 -0
- package/dist/packages/autonomous/src/config/zod-schema.session.d.ts +183 -0
- package/dist/packages/autonomous/src/config/zod-schema.session.d.ts.map +1 -0
- package/dist/packages/autonomous/src/config/zod-schema.session.js +86 -0
- package/dist/packages/autonomous/src/contracts/apps.d.ts +42 -0
- package/dist/packages/autonomous/src/contracts/apps.d.ts.map +1 -0
- package/dist/packages/autonomous/src/contracts/apps.js +4 -0
- package/dist/packages/autonomous/src/contracts/awareness.d.ts +38 -0
- package/dist/packages/autonomous/src/contracts/awareness.d.ts.map +1 -0
- package/dist/packages/autonomous/src/contracts/awareness.js +7 -0
- package/dist/packages/autonomous/src/contracts/config.d.ts +146 -0
- package/dist/packages/autonomous/src/contracts/config.d.ts.map +1 -0
- package/dist/packages/autonomous/src/contracts/config.js +4 -0
- package/dist/packages/autonomous/src/contracts/drop.d.ts +20 -0
- package/dist/packages/autonomous/src/contracts/drop.d.ts.map +1 -0
- package/dist/packages/autonomous/src/contracts/drop.js +4 -0
- package/dist/packages/autonomous/src/contracts/index.d.ts +9 -0
- package/dist/packages/autonomous/src/contracts/index.d.ts.map +1 -0
- package/dist/packages/autonomous/src/contracts/index.js +8 -0
- package/dist/packages/autonomous/src/contracts/onboarding.d.ts +24 -0
- package/dist/packages/autonomous/src/contracts/onboarding.d.ts.map +1 -0
- package/dist/packages/autonomous/src/contracts/onboarding.js +4 -0
- package/dist/packages/autonomous/src/contracts/permissions.d.ts +35 -0
- package/dist/packages/autonomous/src/contracts/permissions.d.ts.map +1 -0
- package/dist/packages/autonomous/src/contracts/permissions.js +4 -0
- package/dist/packages/autonomous/src/contracts/verification.d.ts +9 -0
- package/dist/packages/autonomous/src/contracts/verification.d.ts.map +1 -0
- package/dist/packages/autonomous/src/contracts/verification.js +4 -0
- package/dist/packages/autonomous/src/contracts/wallet.d.ts +352 -0
- package/dist/packages/autonomous/src/contracts/wallet.d.ts.map +1 -0
- package/dist/packages/autonomous/src/contracts/wallet.js +4 -0
- package/dist/packages/autonomous/src/diagnostics/integration-observability.d.ts +40 -0
- package/dist/packages/autonomous/src/diagnostics/integration-observability.d.ts.map +1 -0
- package/dist/packages/autonomous/src/diagnostics/integration-observability.js +68 -0
- package/dist/packages/autonomous/src/emotes/catalog.d.ts +31 -0
- package/dist/packages/autonomous/src/emotes/catalog.d.ts.map +1 -0
- package/dist/packages/autonomous/src/emotes/catalog.js +618 -0
- package/dist/packages/autonomous/src/hooks/discovery.d.ts +13 -0
- package/dist/packages/autonomous/src/hooks/discovery.d.ts.map +1 -0
- package/dist/packages/autonomous/src/hooks/discovery.js +184 -0
- package/dist/packages/autonomous/src/hooks/eligibility.d.ts +12 -0
- package/dist/packages/autonomous/src/hooks/eligibility.d.ts.map +1 -0
- package/dist/packages/autonomous/src/hooks/eligibility.js +100 -0
- package/dist/packages/autonomous/src/hooks/index.d.ts +3 -0
- package/dist/packages/autonomous/src/hooks/index.d.ts.map +1 -0
- package/dist/packages/autonomous/src/hooks/index.js +2 -0
- package/dist/packages/autonomous/src/hooks/loader.d.ts +34 -0
- package/dist/packages/autonomous/src/hooks/loader.d.ts.map +1 -0
- package/dist/packages/autonomous/src/hooks/loader.js +176 -0
- package/dist/packages/autonomous/src/hooks/registry.d.ts +11 -0
- package/dist/packages/autonomous/src/hooks/registry.d.ts.map +1 -0
- package/dist/packages/autonomous/src/hooks/registry.js +58 -0
- package/dist/packages/autonomous/src/hooks/types.d.ts +104 -0
- package/dist/packages/autonomous/src/hooks/types.d.ts.map +1 -0
- package/dist/packages/autonomous/src/hooks/types.js +8 -0
- package/dist/packages/autonomous/src/index.d.ts +21 -0
- package/dist/packages/autonomous/src/index.d.ts.map +1 -0
- package/dist/packages/autonomous/src/index.js +20 -0
- package/dist/packages/autonomous/src/onboarding-presets.d.ts +62 -0
- package/dist/packages/autonomous/src/onboarding-presets.d.ts.map +1 -0
- package/dist/packages/autonomous/src/onboarding-presets.js +1340 -0
- package/dist/packages/autonomous/src/plugins/custom-rtmp/index.d.ts +12 -0
- package/dist/packages/autonomous/src/plugins/custom-rtmp/index.d.ts.map +1 -0
- package/dist/packages/autonomous/src/plugins/custom-rtmp/index.js +26 -0
- package/dist/packages/autonomous/src/providers/admin-trust.d.ts +4 -0
- package/dist/packages/autonomous/src/providers/admin-trust.d.ts.map +1 -0
- package/dist/packages/autonomous/src/providers/admin-trust.js +53 -0
- package/dist/packages/autonomous/src/providers/session-bridge.d.ts +24 -0
- package/dist/packages/autonomous/src/providers/session-bridge.d.ts.map +1 -0
- package/dist/packages/autonomous/src/providers/session-bridge.js +85 -0
- package/dist/packages/autonomous/src/providers/session-utils.d.ts +20 -0
- package/dist/packages/autonomous/src/providers/session-utils.d.ts.map +1 -0
- package/dist/packages/autonomous/src/providers/session-utils.js +33 -0
- package/dist/packages/autonomous/src/providers/simple-mode.d.ts +4 -0
- package/dist/packages/autonomous/src/providers/simple-mode.d.ts.map +1 -0
- package/dist/packages/autonomous/src/providers/simple-mode.js +86 -0
- package/dist/packages/autonomous/src/providers/ui-catalog.d.ts +3 -0
- package/dist/packages/autonomous/src/providers/ui-catalog.d.ts.map +1 -0
- package/dist/packages/autonomous/src/providers/ui-catalog.js +123 -0
- package/dist/packages/autonomous/src/providers/workspace-provider.d.ts +22 -0
- package/dist/packages/autonomous/src/providers/workspace-provider.d.ts.map +1 -0
- package/dist/packages/autonomous/src/providers/workspace-provider.js +163 -0
- package/dist/packages/autonomous/src/providers/workspace.d.ts +49 -0
- package/dist/packages/autonomous/src/providers/workspace.d.ts.map +1 -0
- package/dist/packages/autonomous/src/providers/workspace.js +395 -0
- package/dist/packages/autonomous/src/runtime/agent-event-service.d.ts +35 -0
- package/dist/packages/autonomous/src/runtime/agent-event-service.d.ts.map +1 -0
- package/dist/packages/autonomous/src/runtime/agent-event-service.js +15 -0
- package/dist/packages/autonomous/src/runtime/autonomous-plugin.d.ts +2 -0
- package/dist/packages/autonomous/src/runtime/autonomous-plugin.d.ts.map +1 -0
- package/dist/packages/autonomous/src/runtime/autonomous-plugin.js +1 -0
- package/dist/packages/autonomous/src/runtime/core-plugins.d.ts +14 -0
- package/dist/packages/autonomous/src/runtime/core-plugins.d.ts.map +1 -0
- package/dist/packages/autonomous/src/runtime/core-plugins.js +51 -0
- package/dist/packages/autonomous/src/runtime/custom-actions.d.ts +40 -0
- package/dist/packages/autonomous/src/runtime/custom-actions.d.ts.map +1 -0
- package/dist/packages/autonomous/src/runtime/custom-actions.js +454 -0
- package/dist/packages/autonomous/src/runtime/eliza.d.ts +200 -0
- package/dist/packages/autonomous/src/runtime/eliza.d.ts.map +1 -0
- package/dist/packages/autonomous/src/runtime/eliza.js +3767 -0
- package/dist/packages/autonomous/src/runtime/embedding-presets.d.ts +19 -0
- package/dist/packages/autonomous/src/runtime/embedding-presets.d.ts.map +1 -0
- package/dist/packages/autonomous/src/runtime/embedding-presets.js +53 -0
- package/dist/packages/autonomous/src/runtime/index.d.ts +9 -0
- package/dist/packages/autonomous/src/runtime/index.d.ts.map +1 -0
- package/dist/packages/autonomous/src/runtime/index.js +8 -0
- package/dist/packages/autonomous/src/runtime/milady-plugin.d.ts +16 -0
- package/dist/packages/autonomous/src/runtime/milady-plugin.d.ts.map +1 -0
- package/dist/packages/autonomous/src/runtime/milady-plugin.js +128 -0
- package/dist/packages/autonomous/src/runtime/onboarding-names.d.ts +11 -0
- package/dist/packages/autonomous/src/runtime/onboarding-names.d.ts.map +1 -0
- package/dist/packages/autonomous/src/runtime/onboarding-names.js +74 -0
- package/dist/packages/autonomous/src/runtime/release-plugin-policy.d.ts +20 -0
- package/dist/packages/autonomous/src/runtime/release-plugin-policy.d.ts.map +1 -0
- package/dist/packages/autonomous/src/runtime/release-plugin-policy.js +88 -0
- package/dist/packages/autonomous/src/runtime/restart.d.ts +45 -0
- package/dist/packages/autonomous/src/runtime/restart.d.ts.map +1 -0
- package/dist/packages/autonomous/src/runtime/restart.js +45 -0
- package/dist/packages/autonomous/src/runtime/trajectory-persistence.d.ts +214 -0
- package/dist/packages/autonomous/src/runtime/trajectory-persistence.d.ts.map +1 -0
- package/dist/packages/autonomous/src/runtime/trajectory-persistence.js +1835 -0
- package/dist/packages/autonomous/src/runtime/version.d.ts +2 -0
- package/dist/packages/autonomous/src/runtime/version.d.ts.map +1 -0
- package/dist/packages/autonomous/src/runtime/version.js +5 -0
- package/dist/packages/autonomous/src/security/audit-log.d.ts +49 -0
- package/dist/packages/autonomous/src/security/audit-log.d.ts.map +1 -0
- package/dist/packages/autonomous/src/security/audit-log.js +161 -0
- package/dist/packages/autonomous/src/security/network-policy.d.ts +6 -0
- package/dist/packages/autonomous/src/security/network-policy.d.ts.map +1 -0
- package/dist/packages/autonomous/src/security/network-policy.js +85 -0
- package/dist/packages/autonomous/src/server/index.d.ts +3 -0
- package/dist/packages/autonomous/src/server/index.d.ts.map +1 -0
- package/dist/packages/autonomous/src/server/index.js +1 -0
- package/dist/packages/autonomous/src/services/agent-export.d.ts +100 -0
- package/dist/packages/autonomous/src/services/agent-export.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/agent-export.js +716 -0
- package/dist/packages/autonomous/src/services/app-manager.d.ts +34 -0
- package/dist/packages/autonomous/src/services/app-manager.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/app-manager.js +543 -0
- package/dist/packages/autonomous/src/services/browser-capture.d.ts +39 -0
- package/dist/packages/autonomous/src/services/browser-capture.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/browser-capture.js +162 -0
- package/dist/packages/autonomous/src/services/coding-agent-context.d.ts +310 -0
- package/dist/packages/autonomous/src/services/coding-agent-context.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/coding-agent-context.js +281 -0
- package/dist/packages/autonomous/src/services/fallback-training-service.d.ts +78 -0
- package/dist/packages/autonomous/src/services/fallback-training-service.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/fallback-training-service.js +126 -0
- package/dist/packages/autonomous/src/services/index.d.ts +18 -0
- package/dist/packages/autonomous/src/services/index.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/index.js +17 -0
- package/dist/packages/autonomous/src/services/mcp-marketplace.d.ts +89 -0
- package/dist/packages/autonomous/src/services/mcp-marketplace.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/mcp-marketplace.js +200 -0
- package/dist/packages/autonomous/src/services/plugin-manager-types.d.ts +139 -0
- package/dist/packages/autonomous/src/services/plugin-manager-types.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/plugin-manager-types.js +18 -0
- package/dist/packages/autonomous/src/services/privy-wallets.d.ts +18 -0
- package/dist/packages/autonomous/src/services/privy-wallets.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/privy-wallets.js +225 -0
- package/dist/packages/autonomous/src/services/registry-client-app-meta.d.ts +6 -0
- package/dist/packages/autonomous/src/services/registry-client-app-meta.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/registry-client-app-meta.js +164 -0
- package/dist/packages/autonomous/src/services/registry-client-endpoints.d.ts +7 -0
- package/dist/packages/autonomous/src/services/registry-client-endpoints.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/registry-client-endpoints.js +183 -0
- package/dist/packages/autonomous/src/services/registry-client-local.d.ts +4 -0
- package/dist/packages/autonomous/src/services/registry-client-local.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/registry-client-local.js +377 -0
- package/dist/packages/autonomous/src/services/registry-client-network.d.ts +9 -0
- package/dist/packages/autonomous/src/services/registry-client-network.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/registry-client-network.js +109 -0
- package/dist/packages/autonomous/src/services/registry-client-queries.d.ts +15 -0
- package/dist/packages/autonomous/src/services/registry-client-queries.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/registry-client-queries.js +150 -0
- package/dist/packages/autonomous/src/services/registry-client-types.d.ts +115 -0
- package/dist/packages/autonomous/src/services/registry-client-types.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/registry-client-types.js +1 -0
- package/dist/packages/autonomous/src/services/registry-client.d.ts +39 -0
- package/dist/packages/autonomous/src/services/registry-client.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/registry-client.js +249 -0
- package/dist/packages/autonomous/src/services/remote-signing-service.d.ts +58 -0
- package/dist/packages/autonomous/src/services/remote-signing-service.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/remote-signing-service.js +185 -0
- package/dist/packages/autonomous/src/services/sandbox-engine.d.ts +96 -0
- package/dist/packages/autonomous/src/services/sandbox-engine.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/sandbox-engine.js +604 -0
- package/dist/packages/autonomous/src/services/sandbox-manager.d.ts +104 -0
- package/dist/packages/autonomous/src/services/sandbox-manager.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/sandbox-manager.js +353 -0
- package/dist/packages/autonomous/src/services/self-updater.d.ts +21 -0
- package/dist/packages/autonomous/src/services/self-updater.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/self-updater.js +162 -0
- package/dist/packages/autonomous/src/services/signal-pairing.d.ts +37 -0
- package/dist/packages/autonomous/src/services/signal-pairing.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/signal-pairing.js +124 -0
- package/dist/packages/autonomous/src/services/signing-policy.d.ts +44 -0
- package/dist/packages/autonomous/src/services/signing-policy.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/signing-policy.js +165 -0
- package/dist/packages/autonomous/src/services/skill-catalog-client.d.ts +47 -0
- package/dist/packages/autonomous/src/services/skill-catalog-client.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/skill-catalog-client.js +130 -0
- package/dist/packages/autonomous/src/services/skill-marketplace.d.ts +42 -0
- package/dist/packages/autonomous/src/services/skill-marketplace.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/skill-marketplace.js +680 -0
- package/dist/packages/autonomous/src/services/stream-manager.d.ts +121 -0
- package/dist/packages/autonomous/src/services/stream-manager.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/stream-manager.js +604 -0
- package/dist/packages/autonomous/src/services/tts-stream-bridge.d.ts +83 -0
- package/dist/packages/autonomous/src/services/tts-stream-bridge.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/tts-stream-bridge.js +349 -0
- package/dist/packages/autonomous/src/services/update-checker.d.ts +29 -0
- package/dist/packages/autonomous/src/services/update-checker.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/update-checker.js +134 -0
- package/dist/packages/autonomous/src/services/version-compat.d.ts +105 -0
- package/dist/packages/autonomous/src/services/version-compat.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/version-compat.js +274 -0
- package/dist/packages/autonomous/src/services/whatsapp-pairing.d.ts +41 -0
- package/dist/packages/autonomous/src/services/whatsapp-pairing.d.ts.map +1 -0
- package/dist/packages/autonomous/src/services/whatsapp-pairing.js +209 -0
- package/dist/packages/autonomous/src/shared/ui-catalog-prompt.d.ts +52 -0
- package/dist/packages/autonomous/src/shared/ui-catalog-prompt.d.ts.map +1 -0
- package/dist/packages/autonomous/src/shared/ui-catalog-prompt.js +1028 -0
- package/dist/packages/autonomous/src/test-support/process-helpers.d.ts +13 -0
- package/dist/packages/autonomous/src/test-support/process-helpers.d.ts.map +1 -0
- package/dist/packages/autonomous/src/test-support/process-helpers.js +23 -0
- package/dist/packages/autonomous/src/test-support/route-test-helpers.d.ts +37 -0
- package/dist/packages/autonomous/src/test-support/route-test-helpers.d.ts.map +1 -0
- package/dist/packages/autonomous/src/test-support/route-test-helpers.js +54 -0
- package/dist/packages/autonomous/src/test-support/test-helpers.d.ts +77 -0
- package/dist/packages/autonomous/src/test-support/test-helpers.d.ts.map +1 -0
- package/dist/packages/autonomous/src/test-support/test-helpers.js +210 -0
- package/dist/packages/autonomous/src/testing/index.d.ts +4 -0
- package/dist/packages/autonomous/src/testing/index.d.ts.map +1 -0
- package/dist/packages/autonomous/src/testing/index.js +3 -0
- package/dist/packages/autonomous/src/triggers/action.d.ts +3 -0
- package/dist/packages/autonomous/src/triggers/action.d.ts.map +1 -0
- package/dist/packages/autonomous/src/triggers/action.js +267 -0
- package/dist/packages/autonomous/src/triggers/runtime.d.ts +24 -0
- package/dist/packages/autonomous/src/triggers/runtime.d.ts.map +1 -0
- package/dist/packages/autonomous/src/triggers/runtime.js +319 -0
- package/dist/packages/autonomous/src/triggers/scheduling.d.ts +70 -0
- package/dist/packages/autonomous/src/triggers/scheduling.d.ts.map +1 -0
- package/dist/packages/autonomous/src/triggers/scheduling.js +355 -0
- package/dist/packages/autonomous/src/triggers/types.d.ts +115 -0
- package/dist/packages/autonomous/src/triggers/types.d.ts.map +1 -0
- package/dist/packages/autonomous/src/triggers/types.js +1 -0
- package/dist/packages/autonomous/src/utils/exec-safety.d.ts +2 -0
- package/dist/packages/autonomous/src/utils/exec-safety.d.ts.map +1 -0
- package/dist/packages/autonomous/src/utils/exec-safety.js +21 -0
- package/dist/packages/autonomous/src/utils/number-parsing.d.ts +26 -0
- package/dist/packages/autonomous/src/utils/number-parsing.d.ts.map +1 -0
- package/dist/packages/autonomous/src/utils/number-parsing.js +52 -0
- package/dist/packages/autonomous/src/utils/spoken-text.d.ts +2 -0
- package/dist/packages/autonomous/src/utils/spoken-text.d.ts.map +1 -0
- package/dist/packages/autonomous/src/utils/spoken-text.js +56 -0
- package/dist/packages/autonomous/src/version-resolver.d.ts +2 -0
- package/dist/packages/autonomous/src/version-resolver.d.ts.map +1 -0
- package/dist/packages/autonomous/src/version-resolver.js +50 -0
- package/package.json +235 -0
- package/src/actions/emote.ts +101 -0
- package/src/actions/restart.ts +101 -0
- package/src/actions/send-message.ts +168 -0
- package/src/actions/stream-control.ts +439 -0
- package/src/actions/switch-stream-source.ts +126 -0
- package/src/actions/terminal.ts +186 -0
- package/src/api/agent-admin-routes.ts +178 -0
- package/src/api/agent-lifecycle-routes.ts +120 -0
- package/src/api/agent-model.ts +143 -0
- package/src/api/agent-transfer-routes.ts +211 -0
- package/src/api/apps-routes.ts +207 -0
- package/src/api/auth-routes.ts +90 -0
- package/src/api/bsc-trade.ts +736 -0
- package/src/api/bug-report-routes.ts +161 -0
- package/src/api/character-routes.ts +423 -0
- package/src/api/cloud-billing-routes.ts +600 -0
- package/src/api/cloud-compat-routes.ts +194 -0
- package/src/api/cloud-routes.ts +529 -0
- package/src/api/cloud-status-routes.ts +234 -0
- package/src/api/compat-utils.ts +154 -0
- package/src/api/connector-health.ts +135 -0
- package/src/api/coordinator-wiring.ts +179 -0
- package/src/api/credit-detection.ts +47 -0
- package/src/api/database.ts +1357 -0
- package/src/api/diagnostics-routes.ts +389 -0
- package/src/api/drop-service.ts +205 -0
- package/src/api/early-logs.ts +111 -0
- package/src/api/http-helpers.ts +252 -0
- package/src/api/hyperscape-routes-loader.ts +38 -0
- package/src/api/index.ts +81 -0
- package/src/api/knowledge-routes.ts +1189 -0
- package/src/api/knowledge-service-loader.ts +92 -0
- package/src/api/memory-bounds.ts +121 -0
- package/src/api/memory-routes.ts +349 -0
- package/src/api/merkle-tree.ts +239 -0
- package/src/api/models-routes.ts +72 -0
- package/src/api/nfa-routes.ts +169 -0
- package/src/api/nft-verify.ts +188 -0
- package/src/api/og-tracker.ts +72 -0
- package/src/api/parse-action-block.ts +145 -0
- package/src/api/permissions-routes.ts +222 -0
- package/src/api/plugin-validation.ts +355 -0
- package/src/api/provider-switch-config.ts +47 -0
- package/src/api/registry-routes.ts +165 -0
- package/src/api/registry-service.ts +292 -0
- package/src/api/route-helpers.ts +21 -0
- package/src/api/sandbox-routes.ts +1481 -0
- package/src/api/server.ts +17590 -0
- package/src/api/signal-routes.ts +265 -0
- package/src/api/stream-persistence.ts +297 -0
- package/src/api/stream-route-state.ts +48 -0
- package/src/api/stream-routes.ts +1052 -0
- package/src/api/stream-voice-routes.ts +208 -0
- package/src/api/streaming-text.ts +129 -0
- package/src/api/streaming-types.ts +23 -0
- package/src/api/subscription-routes.ts +283 -0
- package/src/api/terminal-run-limits.ts +31 -0
- package/src/api/training-backend-check.ts +40 -0
- package/src/api/training-routes.ts +314 -0
- package/src/api/training-service-like.ts +46 -0
- package/src/api/trajectory-routes.ts +714 -0
- package/src/api/trigger-routes.ts +444 -0
- package/src/api/twitter-verify.ts +226 -0
- package/src/api/tx-service.ts +193 -0
- package/src/api/wallet-dex-prices.ts +206 -0
- package/src/api/wallet-evm-balance.ts +991 -0
- package/src/api/wallet-routes.ts +450 -0
- package/src/api/wallet-rpc.ts +235 -0
- package/src/api/wallet-trading-profile.ts +694 -0
- package/src/api/wallet.ts +745 -0
- package/src/api/whatsapp-routes.ts +282 -0
- package/src/api/zip-utils.ts +130 -0
- package/src/auth/anthropic.ts +63 -0
- package/src/auth/apply-stealth.ts +38 -0
- package/src/auth/claude-code-stealth.ts +141 -0
- package/src/auth/credentials.ts +226 -0
- package/src/auth/index.ts +18 -0
- package/src/auth/openai-codex.ts +94 -0
- package/src/auth/types.ts +24 -0
- package/src/awareness/registry.ts +220 -0
- package/src/bin.ts +10 -0
- package/src/cli/index.ts +38 -0
- package/src/cli/parse-duration.ts +43 -0
- package/src/cloud/base-url.ts +45 -0
- package/src/cloud/validate-url.ts +176 -0
- package/src/config/character-schema.ts +45 -0
- package/src/config/config.ts +153 -0
- package/src/config/env-vars.ts +86 -0
- package/src/config/includes.ts +196 -0
- package/src/config/index.ts +15 -0
- package/src/config/object-utils.ts +10 -0
- package/src/config/paths.ts +92 -0
- package/src/config/plugin-auto-enable.ts +520 -0
- package/src/config/schema.ts +1342 -0
- package/src/config/telegram-custom-commands.ts +99 -0
- package/src/config/types.agent-defaults.ts +342 -0
- package/src/config/types.agents.ts +111 -0
- package/src/config/types.autonomous.ts +16 -0
- package/src/config/types.gateway.ts +243 -0
- package/src/config/types.hooks.ts +124 -0
- package/src/config/types.messages.ts +201 -0
- package/src/config/types.milady.ts +787 -0
- package/src/config/types.tools.ts +416 -0
- package/src/config/types.ts +7 -0
- package/src/config/zod-schema.agent-runtime.ts +777 -0
- package/src/config/zod-schema.core.ts +778 -0
- package/src/config/zod-schema.hooks.ts +139 -0
- package/src/config/zod-schema.providers-core.ts +1126 -0
- package/src/config/zod-schema.session.ts +98 -0
- package/src/config/zod-schema.ts +866 -0
- package/src/contracts/apps.ts +46 -0
- package/src/contracts/awareness.ts +56 -0
- package/src/contracts/config.ts +172 -0
- package/src/contracts/drop.ts +21 -0
- package/src/contracts/index.ts +8 -0
- package/src/contracts/onboarding.ts +24 -0
- package/src/contracts/permissions.ts +52 -0
- package/src/contracts/verification.ts +9 -0
- package/src/contracts/wallet.ts +389 -0
- package/src/diagnostics/integration-observability.ts +132 -0
- package/src/emotes/catalog.ts +655 -0
- package/src/external-modules.d.ts +7 -0
- package/src/hooks/discovery.test.ts +357 -0
- package/src/hooks/discovery.ts +231 -0
- package/src/hooks/eligibility.ts +146 -0
- package/src/hooks/hooks.test.ts +320 -0
- package/src/hooks/index.ts +8 -0
- package/src/hooks/loader.test.ts +418 -0
- package/src/hooks/loader.ts +256 -0
- package/src/hooks/registry.test.ts +168 -0
- package/src/hooks/registry.ts +74 -0
- package/src/hooks/types.ts +121 -0
- package/src/index.ts +20 -0
- package/src/onboarding-presets.ts +1384 -0
- package/src/plugins/custom-rtmp/index.ts +40 -0
- package/src/providers/admin-trust.ts +76 -0
- package/src/providers/session-bridge.ts +143 -0
- package/src/providers/session-utils.ts +42 -0
- package/src/providers/simple-mode.ts +113 -0
- package/src/providers/ui-catalog.ts +135 -0
- package/src/providers/workspace-provider.ts +213 -0
- package/src/providers/workspace.ts +497 -0
- package/src/runtime/agent-event-service.ts +57 -0
- package/src/runtime/autonomous-plugin.ts +4 -0
- package/src/runtime/core-plugins.ts +53 -0
- package/src/runtime/custom-actions.ts +605 -0
- package/src/runtime/eliza.ts +4716 -0
- package/src/runtime/embedding-presets.ts +73 -0
- package/src/runtime/index.ts +8 -0
- package/src/runtime/milady-plugin.ts +180 -0
- package/src/runtime/onboarding-names.ts +76 -0
- package/src/runtime/release-plugin-policy.ts +119 -0
- package/src/runtime/restart.ts +59 -0
- package/src/runtime/trajectory-persistence.ts +2584 -0
- package/src/runtime/version.ts +6 -0
- package/src/security/audit-log.ts +222 -0
- package/src/security/network-policy.ts +91 -0
- package/src/server/index.ts +2 -0
- package/src/services/agent-export.ts +976 -0
- package/src/services/app-manager.ts +755 -0
- package/src/services/browser-capture.ts +215 -0
- package/src/services/coding-agent-context.ts +355 -0
- package/src/services/fallback-training-service.ts +196 -0
- package/src/services/index.ts +17 -0
- package/src/services/mcp-marketplace.ts +327 -0
- package/src/services/plugin-manager-types.ts +185 -0
- package/src/services/privy-wallets.ts +352 -0
- package/src/services/registry-client-app-meta.ts +201 -0
- package/src/services/registry-client-endpoints.ts +253 -0
- package/src/services/registry-client-local.ts +485 -0
- package/src/services/registry-client-network.ts +173 -0
- package/src/services/registry-client-queries.ts +176 -0
- package/src/services/registry-client-types.ts +104 -0
- package/src/services/registry-client.ts +366 -0
- package/src/services/remote-signing-service.ts +261 -0
- package/src/services/sandbox-engine.ts +753 -0
- package/src/services/sandbox-manager.ts +503 -0
- package/src/services/self-updater.ts +213 -0
- package/src/services/signal-pairing.ts +189 -0
- package/src/services/signing-policy.ts +230 -0
- package/src/services/skill-catalog-client.ts +195 -0
- package/src/services/skill-marketplace.ts +909 -0
- package/src/services/stream-manager.ts +707 -0
- package/src/services/tts-stream-bridge.ts +465 -0
- package/src/services/update-checker.ts +163 -0
- package/src/services/version-compat.ts +367 -0
- package/src/services/whatsapp-pairing.ts +282 -0
- package/src/shared/ui-catalog-prompt.ts +1158 -0
- package/src/test-support/process-helpers.ts +35 -0
- package/src/test-support/route-test-helpers.ts +113 -0
- package/src/test-support/test-helpers.ts +304 -0
- package/src/testing/index.ts +3 -0
- package/src/triggers/action.ts +342 -0
- package/src/triggers/runtime.ts +432 -0
- package/src/triggers/scheduling.ts +472 -0
- package/src/triggers/types.ts +133 -0
- package/src/types/app-hyperscape-routes-shim.d.ts +29 -0
- package/src/types/eliza-core-compat.d.ts +122 -0
- package/src/types/external-modules.d.ts +9 -0
- package/src/utils/exec-safety.ts +23 -0
- package/src/utils/number-parsing.ts +112 -0
- package/src/utils/spoken-text.ts +65 -0
- package/src/version-resolver.ts +60 -0
- package/test/api/lifecycle.test.ts +342 -0
- package/tsconfig.build.json +21 -0
- package/tsconfig.json +19 -0
|
@@ -0,0 +1,3767 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* elizaOS runtime entry point for Milady.
|
|
3
|
+
*
|
|
4
|
+
* Starts the elizaOS agent runtime with Milady's plugin configuration.
|
|
5
|
+
* Can be run directly via: node --import tsx src/runtime/eliza.ts
|
|
6
|
+
* Or via the CLI: milady start
|
|
7
|
+
*
|
|
8
|
+
* @module eliza
|
|
9
|
+
*/
|
|
10
|
+
import crypto from "node:crypto";
|
|
11
|
+
import { existsSync, mkdirSync, readFileSync, symlinkSync, unlinkSync, } from "node:fs";
|
|
12
|
+
import fs from "node:fs/promises";
|
|
13
|
+
import { createRequire } from "node:module";
|
|
14
|
+
import os from "node:os";
|
|
15
|
+
import path from "node:path";
|
|
16
|
+
import process from "node:process";
|
|
17
|
+
import * as readline from "node:readline";
|
|
18
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
19
|
+
let _clack = null;
|
|
20
|
+
async function loadClack() {
|
|
21
|
+
if (!_clack)
|
|
22
|
+
_clack = await import("@clack/prompts");
|
|
23
|
+
return _clack;
|
|
24
|
+
}
|
|
25
|
+
import { AgentRuntime, AutonomyService, addLogListener, ChannelType, createMessageMemory, logger,
|
|
26
|
+
// loggerScope, // removed
|
|
27
|
+
mergeCharacterDefaults, stringToUuid, } from "@elizaos/core";
|
|
28
|
+
import * as pluginAgentOrchestrator from "@elizaos/plugin-agent-orchestrator";
|
|
29
|
+
import * as pluginAgentSkills from "@elizaos/plugin-agent-skills";
|
|
30
|
+
import * as pluginAnthropic from "@elizaos/plugin-anthropic";
|
|
31
|
+
import * as pluginCron from "@elizaos/plugin-cron";
|
|
32
|
+
import * as pluginElizacloud from "@elizaos/plugin-elizacloud";
|
|
33
|
+
import * as pluginExperience from "@elizaos/plugin-experience";
|
|
34
|
+
import * as pluginForm from "@elizaos/plugin-form";
|
|
35
|
+
import * as pluginKnowledge from "@elizaos/plugin-knowledge";
|
|
36
|
+
import * as pluginLocalEmbedding from "@elizaos/plugin-local-embedding";
|
|
37
|
+
import * as pluginOllama from "@elizaos/plugin-ollama";
|
|
38
|
+
import * as pluginOpenai from "@elizaos/plugin-openai";
|
|
39
|
+
import * as pluginPdf from "@elizaos/plugin-pdf";
|
|
40
|
+
import * as pluginPersonality from "@elizaos/plugin-personality";
|
|
41
|
+
import * as pluginPluginManager from "@elizaos/plugin-plugin-manager";
|
|
42
|
+
import * as pluginRolodex from "@elizaos/plugin-rolodex";
|
|
43
|
+
import * as pluginSecretsManager from "@elizaos/plugin-secrets-manager";
|
|
44
|
+
import * as pluginShell from "@elizaos/plugin-shell";
|
|
45
|
+
import * as pluginSql from "@elizaos/plugin-sql";
|
|
46
|
+
import * as pluginTodo from "@elizaos/plugin-todo";
|
|
47
|
+
import * as pluginTrajectoryLogger from "@elizaos/plugin-trajectory-logger";
|
|
48
|
+
import * as pluginTrust from "@elizaos/plugin-trust";
|
|
49
|
+
import { debugLogResolvedContext, validateRuntimeContext, } from "../api/plugin-validation";
|
|
50
|
+
import { configFileExists, loadMiladyConfig, saveMiladyConfig, } from "../config/config";
|
|
51
|
+
import { collectConfigEnvVars } from "../config/env-vars";
|
|
52
|
+
import { resolveStateDir, resolveUserPath } from "../config/paths";
|
|
53
|
+
import { applyPluginAutoEnable, } from "../config/plugin-auto-enable";
|
|
54
|
+
import { createHookEvent, loadHooks, triggerHook, } from "../hooks/index";
|
|
55
|
+
import { ensureAgentWorkspace, resolveDefaultAgentWorkspaceDir, } from "../providers/workspace";
|
|
56
|
+
import { SandboxAuditLog } from "../security/audit-log";
|
|
57
|
+
import { SandboxManager } from "../services/sandbox-manager";
|
|
58
|
+
import { diagnoseNoAIProvider } from "../services/version-compat";
|
|
59
|
+
import { createAutonomousPlugin } from "./autonomous-plugin";
|
|
60
|
+
import { CORE_PLUGINS, OPTIONAL_CORE_PLUGINS } from "./core-plugins";
|
|
61
|
+
import { detectEmbeddingPreset } from "./embedding-presets";
|
|
62
|
+
import { installDatabaseTrajectoryLogger, shouldEnableTrajectoryLoggingByDefault, } from "./trajectory-persistence";
|
|
63
|
+
/**
|
|
64
|
+
* Map of baseline bundled @elizaos plugin names to their statically imported
|
|
65
|
+
* modules.
|
|
66
|
+
*
|
|
67
|
+
* Post-release plugins are intentionally excluded so the packaged runtime can
|
|
68
|
+
* ship a smaller baseline bundle. Those plugins fall through to dynamic
|
|
69
|
+
* import() and can be installed later via the plugin installer.
|
|
70
|
+
*/
|
|
71
|
+
const STATIC_ELIZA_PLUGINS = {
|
|
72
|
+
"@elizaos/plugin-sql": pluginSql,
|
|
73
|
+
"@elizaos/plugin-local-embedding": pluginLocalEmbedding,
|
|
74
|
+
"@elizaos/plugin-secrets-manager": pluginSecretsManager,
|
|
75
|
+
"@elizaos/plugin-form": pluginForm,
|
|
76
|
+
"@elizaos/plugin-knowledge": pluginKnowledge,
|
|
77
|
+
"@elizaos/plugin-rolodex": pluginRolodex,
|
|
78
|
+
"@elizaos/plugin-trajectory-logger": pluginTrajectoryLogger,
|
|
79
|
+
"@elizaos/plugin-agent-orchestrator": pluginAgentOrchestrator,
|
|
80
|
+
"@elizaos/plugin-cron": pluginCron,
|
|
81
|
+
"@elizaos/plugin-shell": pluginShell,
|
|
82
|
+
"@elizaos/plugin-plugin-manager": pluginPluginManager,
|
|
83
|
+
"@elizaos/plugin-agent-skills": pluginAgentSkills,
|
|
84
|
+
"@elizaos/plugin-pdf": pluginPdf,
|
|
85
|
+
"@elizaos/plugin-openai": pluginOpenai,
|
|
86
|
+
"@elizaos/plugin-anthropic": pluginAnthropic,
|
|
87
|
+
"@elizaos/plugin-ollama": pluginOllama,
|
|
88
|
+
"@elizaos/plugin-elizacloud": pluginElizacloud,
|
|
89
|
+
"@elizaos/plugin-trust": pluginTrust,
|
|
90
|
+
"@elizaos/plugin-todo": pluginTodo,
|
|
91
|
+
"@elizaos/plugin-personality": pluginPersonality,
|
|
92
|
+
"@elizaos/plugin-experience": pluginExperience,
|
|
93
|
+
};
|
|
94
|
+
// NODE_PATH so dynamic plugin imports (e.g. @elizaos/plugin-agent-orchestrator) resolve.
|
|
95
|
+
// WHY: When eliza is loaded from dist/ or by a test runner, Node's resolution does not
|
|
96
|
+
// search repo root node_modules; import("@elizaos/plugin-*") then fails. We prepend
|
|
97
|
+
// repo root node_modules only if not already in NODE_PATH (run-node.mjs may have set it)
|
|
98
|
+
// to avoid duplicate entries; _initPaths() makes Node re-read NODE_PATH. See docs/plugin-resolution-and-node-path.md.
|
|
99
|
+
// We walk up from this file to find node_modules ā we do not assume a fixed depth
|
|
100
|
+
// (e.g. two levels for src/runtime/ or dist/runtime/) so we still work if build
|
|
101
|
+
// output structure changes (e.g. flat dist). First directory with node_modules wins.
|
|
102
|
+
const _elizaDir = path.dirname(fileURLToPath(import.meta.url));
|
|
103
|
+
let _dir = _elizaDir;
|
|
104
|
+
let _rootModules = null;
|
|
105
|
+
while (_dir !== path.dirname(_dir)) {
|
|
106
|
+
const candidate = path.join(_dir, "node_modules");
|
|
107
|
+
if (existsSync(candidate)) {
|
|
108
|
+
_rootModules = candidate;
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
_dir = path.dirname(_dir);
|
|
112
|
+
}
|
|
113
|
+
if (_rootModules) {
|
|
114
|
+
const prev = process.env.NODE_PATH ?? "";
|
|
115
|
+
const entries = prev ? prev.split(path.delimiter) : [];
|
|
116
|
+
const normalizedRoot = path.resolve(_rootModules);
|
|
117
|
+
if (!entries.some((e) => path.resolve(e) === normalizedRoot)) {
|
|
118
|
+
process.env.NODE_PATH = prev
|
|
119
|
+
? `${_rootModules}${path.delimiter}${prev}`
|
|
120
|
+
: _rootModules;
|
|
121
|
+
createRequire(import.meta.url)("node:module").Module._initPaths();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
export function configureLocalEmbeddingPlugin(_plugin, config) {
|
|
125
|
+
const detectedPreset = detectEmbeddingPreset();
|
|
126
|
+
const embeddingConfig = config?.embedding;
|
|
127
|
+
const configuredModel = embeddingConfig?.model?.trim();
|
|
128
|
+
const configuredRepo = embeddingConfig?.modelRepo?.trim();
|
|
129
|
+
const configuredDimensions = typeof embeddingConfig?.dimensions === "number" &&
|
|
130
|
+
Number.isInteger(embeddingConfig.dimensions) &&
|
|
131
|
+
embeddingConfig.dimensions > 0
|
|
132
|
+
? String(embeddingConfig.dimensions)
|
|
133
|
+
: undefined;
|
|
134
|
+
const configuredContextSize = typeof embeddingConfig?.contextSize === "number" &&
|
|
135
|
+
Number.isInteger(embeddingConfig.contextSize) &&
|
|
136
|
+
embeddingConfig.contextSize > 0
|
|
137
|
+
? String(embeddingConfig.contextSize)
|
|
138
|
+
: undefined;
|
|
139
|
+
const configuredGpuLayers = (() => {
|
|
140
|
+
const value = embeddingConfig?.gpuLayers;
|
|
141
|
+
if (typeof value === "number" && Number.isInteger(value) && value >= 0) {
|
|
142
|
+
return String(value);
|
|
143
|
+
}
|
|
144
|
+
if (value === "auto" || value === "max") {
|
|
145
|
+
// plugin-local-embedding understands "auto" and treats it as runtime max
|
|
146
|
+
return "auto";
|
|
147
|
+
}
|
|
148
|
+
return undefined;
|
|
149
|
+
})();
|
|
150
|
+
const setEnvIfMissing = (key, value) => {
|
|
151
|
+
if (!value || process.env[key])
|
|
152
|
+
return;
|
|
153
|
+
process.env[key] = value;
|
|
154
|
+
};
|
|
155
|
+
const setEnvFromConfig = (key, value) => {
|
|
156
|
+
if (!value)
|
|
157
|
+
return;
|
|
158
|
+
process.env[key] = value;
|
|
159
|
+
};
|
|
160
|
+
// Keep plugin-local-embedding aligned with Milady's hardware-adaptive preset
|
|
161
|
+
// selection. Hard-coding the standard preset here forces slower first-run
|
|
162
|
+
// downloads on Windows and low-spec machines.
|
|
163
|
+
setEnvIfMissing("LOCAL_EMBEDDING_MODEL", configuredModel || detectedPreset.model);
|
|
164
|
+
if (configuredRepo) {
|
|
165
|
+
setEnvFromConfig("LOCAL_EMBEDDING_MODEL_REPO", configuredRepo);
|
|
166
|
+
}
|
|
167
|
+
else if (!configuredModel) {
|
|
168
|
+
setEnvIfMissing("LOCAL_EMBEDDING_MODEL_REPO", detectedPreset.modelRepo);
|
|
169
|
+
}
|
|
170
|
+
if (configuredDimensions) {
|
|
171
|
+
setEnvFromConfig("LOCAL_EMBEDDING_DIMENSIONS", configuredDimensions);
|
|
172
|
+
}
|
|
173
|
+
else if (!configuredModel) {
|
|
174
|
+
setEnvIfMissing("LOCAL_EMBEDDING_DIMENSIONS", String(detectedPreset.dimensions));
|
|
175
|
+
}
|
|
176
|
+
if (configuredContextSize) {
|
|
177
|
+
setEnvFromConfig("LOCAL_EMBEDDING_CONTEXT_SIZE", configuredContextSize);
|
|
178
|
+
}
|
|
179
|
+
else if (!configuredModel) {
|
|
180
|
+
setEnvIfMissing("LOCAL_EMBEDDING_CONTEXT_SIZE", String(detectedPreset.contextSize));
|
|
181
|
+
}
|
|
182
|
+
if (configuredGpuLayers) {
|
|
183
|
+
process.env.LOCAL_EMBEDDING_GPU_LAYERS = configuredGpuLayers;
|
|
184
|
+
}
|
|
185
|
+
else if (!process.env.LOCAL_EMBEDDING_GPU_LAYERS) {
|
|
186
|
+
process.env.LOCAL_EMBEDDING_GPU_LAYERS = String(detectedPreset.gpuLayers);
|
|
187
|
+
}
|
|
188
|
+
// Performance tuning
|
|
189
|
+
// Disable mmap on Metal to prevent "different text" errors with some models
|
|
190
|
+
setEnvIfMissing("LOCAL_EMBEDDING_USE_MMAP", detectedPreset.gpuLayers === "auto" ? "false" : "true");
|
|
191
|
+
// Set default models directory if not present
|
|
192
|
+
setEnvIfMissing("MODELS_DIR", path.join(os.homedir(), ".eliza", "models"));
|
|
193
|
+
// Normalize Google AI API key aliases ā the elizaOS plugin and @google/genai
|
|
194
|
+
// SDK expect different env var names. Canonicalize to the long form that
|
|
195
|
+
// @elizaos/plugin-google-genai reads via runtime.getSetting(). Users can set
|
|
196
|
+
// any of: GEMINI_API_KEY, GOOGLE_API_KEY, GOOGLE_GENERATIVE_AI_API_KEY.
|
|
197
|
+
setEnvIfMissing("GOOGLE_GENERATIVE_AI_API_KEY", process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY);
|
|
198
|
+
// Default Google model names ā the Google GenAI plugin's getSetting() returns
|
|
199
|
+
// null (not undefined) for missing keys, but the plugin checks !== undefined
|
|
200
|
+
// causing String(null) = "null" to be sent as the model name. Set sensible
|
|
201
|
+
// defaults so the plugin always has valid model names.
|
|
202
|
+
setEnvIfMissing("GOOGLE_SMALL_MODEL", "gemini-3-flash-preview");
|
|
203
|
+
setEnvIfMissing("GOOGLE_LARGE_MODEL", "gemini-3.1-pro-preview");
|
|
204
|
+
logger.info(`[milady] Configured local embedding env: ${process.env.LOCAL_EMBEDDING_MODEL} (repo: ${process.env.LOCAL_EMBEDDING_MODEL_REPO ?? "auto"}, dims: ${process.env.LOCAL_EMBEDDING_DIMENSIONS ?? "auto"}, ctx: ${process.env.LOCAL_EMBEDDING_CONTEXT_SIZE ?? "auto"}, GPU: ${process.env.LOCAL_EMBEDDING_GPU_LAYERS}, mmap: ${process.env.LOCAL_EMBEDDING_USE_MMAP})`);
|
|
205
|
+
}
|
|
206
|
+
// ---------------------------------------------------------------------------
|
|
207
|
+
// Helpers
|
|
208
|
+
// ---------------------------------------------------------------------------
|
|
209
|
+
/** Extract a human-readable error message from an unknown thrown value. */
|
|
210
|
+
function formatError(err) {
|
|
211
|
+
return err instanceof Error ? err.message : String(err);
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Best-effort runtime shutdown that also closes the database adapter.
|
|
215
|
+
*
|
|
216
|
+
* AgentRuntime.stop() only stops services. plugin-sql keeps a process-global
|
|
217
|
+
* PGlite manager, so restarts must close the adapter or the next runtime can
|
|
218
|
+
* silently reuse the same broken manager instance.
|
|
219
|
+
*/
|
|
220
|
+
export async function shutdownRuntime(runtime, context) {
|
|
221
|
+
if (!runtime)
|
|
222
|
+
return;
|
|
223
|
+
const adapter = runtime.adapter;
|
|
224
|
+
let firstError = null;
|
|
225
|
+
try {
|
|
226
|
+
await runtime.stop();
|
|
227
|
+
}
|
|
228
|
+
catch (err) {
|
|
229
|
+
firstError = err;
|
|
230
|
+
logger.warn(`[milady] ${context}: runtime stop failed: ${formatError(err)}`);
|
|
231
|
+
}
|
|
232
|
+
if (adapter && typeof adapter.close === "function") {
|
|
233
|
+
try {
|
|
234
|
+
await adapter.close();
|
|
235
|
+
}
|
|
236
|
+
catch (err) {
|
|
237
|
+
if (!firstError) {
|
|
238
|
+
firstError = err;
|
|
239
|
+
}
|
|
240
|
+
logger.warn(`[milady] ${context}: database adapter close failed: ${formatError(err)}`);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
if (firstError) {
|
|
244
|
+
throw firstError;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Remove duplicate actions across an ordered list of plugins.
|
|
249
|
+
*
|
|
250
|
+
* When multiple plugins define an action with the same `name`, only the first
|
|
251
|
+
* occurrence is kept. This prevents "Action already registered" warnings from
|
|
252
|
+
* elizaOS core. The function mutates each plugin's `actions` array in-place.
|
|
253
|
+
*/
|
|
254
|
+
export function deduplicatePluginActions(plugins) {
|
|
255
|
+
const seen = new Set();
|
|
256
|
+
for (const plugin of plugins) {
|
|
257
|
+
if (plugin.actions) {
|
|
258
|
+
plugin.actions = plugin.actions.filter((action) => {
|
|
259
|
+
if (seen.has(action.name)) {
|
|
260
|
+
logger.debug(`[milady] Skipping duplicate action "${action.name}" from plugin "${plugin.name}"`);
|
|
261
|
+
return false;
|
|
262
|
+
}
|
|
263
|
+
seen.add(action.name);
|
|
264
|
+
return true;
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
function collectTrajectoryLoggerCandidates(runtimeLike) {
|
|
270
|
+
const candidates = [];
|
|
271
|
+
if (typeof runtimeLike.getServicesByType === "function") {
|
|
272
|
+
const byType = runtimeLike.getServicesByType("trajectory_logger");
|
|
273
|
+
if (Array.isArray(byType) && byType.length > 0) {
|
|
274
|
+
for (const service of byType) {
|
|
275
|
+
if (service)
|
|
276
|
+
candidates.push(service);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
else if (byType && !Array.isArray(byType)) {
|
|
280
|
+
candidates.push(byType);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
if (typeof runtimeLike.getService === "function") {
|
|
284
|
+
const single = runtimeLike.getService("trajectory_logger");
|
|
285
|
+
if (single)
|
|
286
|
+
candidates.push(single);
|
|
287
|
+
}
|
|
288
|
+
return candidates;
|
|
289
|
+
}
|
|
290
|
+
async function waitForTrajectoryLoggerService(runtime, context, timeoutMs = 3000) {
|
|
291
|
+
const runtimeLike = runtime;
|
|
292
|
+
if (collectTrajectoryLoggerCandidates(runtimeLike).length > 0)
|
|
293
|
+
return;
|
|
294
|
+
const registrationStatus = typeof runtimeLike.getServiceRegistrationStatus === "function"
|
|
295
|
+
? runtimeLike.getServiceRegistrationStatus("trajectory_logger")
|
|
296
|
+
: "unknown";
|
|
297
|
+
if (registrationStatus !== "pending" &&
|
|
298
|
+
registrationStatus !== "registering") {
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
if (typeof runtimeLike.getServiceLoadPromise !== "function")
|
|
302
|
+
return;
|
|
303
|
+
let timedOut = false;
|
|
304
|
+
let timeoutHandle;
|
|
305
|
+
const timeoutPromise = new Promise((resolve) => {
|
|
306
|
+
timeoutHandle = setTimeout(() => {
|
|
307
|
+
timedOut = true;
|
|
308
|
+
resolve();
|
|
309
|
+
}, timeoutMs);
|
|
310
|
+
});
|
|
311
|
+
try {
|
|
312
|
+
await Promise.race([
|
|
313
|
+
runtimeLike.getServiceLoadPromise("trajectory_logger").then(() => { }),
|
|
314
|
+
timeoutPromise,
|
|
315
|
+
]);
|
|
316
|
+
if (timedOut) {
|
|
317
|
+
logger.debug(`[milady] trajectory_logger still ${registrationStatus} after ${timeoutMs}ms (${context})`);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
catch (err) {
|
|
321
|
+
logger.debug(`[milady] trajectory_logger registration failed while waiting (${context}): ${formatError(err)}`);
|
|
322
|
+
}
|
|
323
|
+
finally {
|
|
324
|
+
if (timeoutHandle)
|
|
325
|
+
clearTimeout(timeoutHandle);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
function ensureTrajectoryLoggerEnabled(runtime, context) {
|
|
329
|
+
const runtimeLike = runtime;
|
|
330
|
+
const candidates = collectTrajectoryLoggerCandidates(runtimeLike);
|
|
331
|
+
let trajectoryLogger = null;
|
|
332
|
+
let bestScore = -1;
|
|
333
|
+
for (const candidate of candidates) {
|
|
334
|
+
const candidateWithRuntime = candidate;
|
|
335
|
+
let score = 0;
|
|
336
|
+
if (typeof candidate.isEnabled === "function")
|
|
337
|
+
score += 2;
|
|
338
|
+
if (typeof candidateWithRuntime.setEnabled === "function")
|
|
339
|
+
score += 2;
|
|
340
|
+
if (candidateWithRuntime.initialized === true)
|
|
341
|
+
score += 3;
|
|
342
|
+
if (candidateWithRuntime.runtime?.adapter)
|
|
343
|
+
score += 3;
|
|
344
|
+
const enabled = typeof candidate.isEnabled === "function" ? candidate.isEnabled() : true;
|
|
345
|
+
if (enabled)
|
|
346
|
+
score += 1;
|
|
347
|
+
if (score > bestScore) {
|
|
348
|
+
trajectoryLogger = candidate;
|
|
349
|
+
bestScore = score;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
if (!trajectoryLogger) {
|
|
353
|
+
logger.warn(`[milady] trajectory_logger service unavailable (${context}); trajectory capture disabled`);
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
const isEnabled = typeof trajectoryLogger.isEnabled === "function"
|
|
357
|
+
? trajectoryLogger.isEnabled()
|
|
358
|
+
: shouldEnableTrajectoryLoggingByDefault();
|
|
359
|
+
const shouldEnable = shouldEnableTrajectoryLoggingByDefault();
|
|
360
|
+
if (isEnabled !== shouldEnable &&
|
|
361
|
+
typeof trajectoryLogger.setEnabled === "function") {
|
|
362
|
+
trajectoryLogger.setEnabled(shouldEnable);
|
|
363
|
+
logger.info(`[milady] trajectory_logger defaulted ${shouldEnable ? "on" : "off"} (${context})`);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
function patchTrajectoryLoggerAliasCompatibility(runtime) {
|
|
367
|
+
const runtimeLike = runtime;
|
|
368
|
+
const primary = collectTrajectoryLoggerCandidates(runtimeLike)[0];
|
|
369
|
+
if (!primary)
|
|
370
|
+
return;
|
|
371
|
+
if (typeof runtimeLike.getService !== "function")
|
|
372
|
+
return;
|
|
373
|
+
const aliases = [
|
|
374
|
+
runtimeLike.getService("logger5"),
|
|
375
|
+
runtimeLike.getService("logger"),
|
|
376
|
+
];
|
|
377
|
+
for (const alias of aliases) {
|
|
378
|
+
if (!alias || typeof alias !== "object" || alias === primary)
|
|
379
|
+
continue;
|
|
380
|
+
const aliasOps = alias;
|
|
381
|
+
if (typeof aliasOps.startTrajectory !== "function") {
|
|
382
|
+
aliasOps.startTrajectory = async (...args) => {
|
|
383
|
+
if (typeof primary.startTrajectory === "function") {
|
|
384
|
+
return primary.startTrajectory(...args);
|
|
385
|
+
}
|
|
386
|
+
return `step-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
if (typeof aliasOps.startStep !== "function") {
|
|
390
|
+
aliasOps.startStep = (trajectoryId) => {
|
|
391
|
+
if (typeof primary.startStep === "function") {
|
|
392
|
+
return primary.startStep(trajectoryId);
|
|
393
|
+
}
|
|
394
|
+
return `step-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
if (typeof aliasOps.endTrajectory !== "function") {
|
|
398
|
+
aliasOps.endTrajectory = async (...args) => {
|
|
399
|
+
if (typeof primary.endTrajectory === "function") {
|
|
400
|
+
await primary.endTrajectory(...args);
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Cancel the onboarding flow and exit cleanly.
|
|
408
|
+
* Extracted to avoid duplicating the cancel+exit pattern 7 times.
|
|
409
|
+
*/
|
|
410
|
+
function cancelOnboarding() {
|
|
411
|
+
// _clack is guaranteed to be loaded by the time onboarding calls this.
|
|
412
|
+
_clack?.cancel("Maybe next time!");
|
|
413
|
+
process.exit(0);
|
|
414
|
+
}
|
|
415
|
+
// ---------------------------------------------------------------------------
|
|
416
|
+
// Channel secret mapping
|
|
417
|
+
// ---------------------------------------------------------------------------
|
|
418
|
+
/**
|
|
419
|
+
* Maps Milady channel config fields to the environment variable names
|
|
420
|
+
* that elizaOS plugins expect.
|
|
421
|
+
*
|
|
422
|
+
* Milady stores channel credentials under `config.channels.<name>.<field>`,
|
|
423
|
+
* while elizaOS plugins read them from process.env.
|
|
424
|
+
*/
|
|
425
|
+
const RETAKE_CHANNEL_ACCESS_TOKEN_ENV = "RETAKE_AGENT_TOKEN";
|
|
426
|
+
const CHANNEL_ENV_MAP = {
|
|
427
|
+
discord: {
|
|
428
|
+
token: "DISCORD_API_TOKEN",
|
|
429
|
+
botToken: "DISCORD_API_TOKEN",
|
|
430
|
+
applicationId: "DISCORD_APPLICATION_ID",
|
|
431
|
+
},
|
|
432
|
+
telegram: {
|
|
433
|
+
botToken: "TELEGRAM_BOT_TOKEN",
|
|
434
|
+
},
|
|
435
|
+
slack: {
|
|
436
|
+
botToken: "SLACK_BOT_TOKEN",
|
|
437
|
+
appToken: "SLACK_APP_TOKEN",
|
|
438
|
+
userToken: "SLACK_USER_TOKEN",
|
|
439
|
+
},
|
|
440
|
+
signal: {
|
|
441
|
+
authDir: "SIGNAL_AUTH_DIR",
|
|
442
|
+
account: "SIGNAL_ACCOUNT_NUMBER",
|
|
443
|
+
httpUrl: "SIGNAL_HTTP_URL",
|
|
444
|
+
cliPath: "SIGNAL_CLI_PATH",
|
|
445
|
+
},
|
|
446
|
+
msteams: {
|
|
447
|
+
appId: "MSTEAMS_APP_ID",
|
|
448
|
+
appPassword: "MSTEAMS_APP_PASSWORD",
|
|
449
|
+
},
|
|
450
|
+
mattermost: {
|
|
451
|
+
botToken: "MATTERMOST_BOT_TOKEN",
|
|
452
|
+
baseUrl: "MATTERMOST_BASE_URL",
|
|
453
|
+
},
|
|
454
|
+
googlechat: {
|
|
455
|
+
serviceAccountKey: "GOOGLE_CHAT_SERVICE_ACCOUNT_KEY",
|
|
456
|
+
},
|
|
457
|
+
blooio: {
|
|
458
|
+
apiKey: "BLOOIO_API_KEY",
|
|
459
|
+
fromNumber: "BLOOIO_PHONE_NUMBER",
|
|
460
|
+
webhookSecret: "BLOOIO_WEBHOOK_SECRET",
|
|
461
|
+
webhookUrl: "BLOOIO_WEBHOOK_URL",
|
|
462
|
+
webhookPort: "BLOOIO_WEBHOOK_PORT",
|
|
463
|
+
},
|
|
464
|
+
retake: {
|
|
465
|
+
accessToken: RETAKE_CHANNEL_ACCESS_TOKEN_ENV,
|
|
466
|
+
apiUrl: "RETAKE_API_URL",
|
|
467
|
+
},
|
|
468
|
+
};
|
|
469
|
+
// ---------------------------------------------------------------------------
|
|
470
|
+
// Plugin resolution
|
|
471
|
+
// ---------------------------------------------------------------------------
|
|
472
|
+
export { CORE_PLUGINS, OPTIONAL_CORE_PLUGINS };
|
|
473
|
+
/**
|
|
474
|
+
* Optional plugins that require native binaries or specific config.
|
|
475
|
+
* These are only loaded when explicitly enabled via features config,
|
|
476
|
+
* NOT by default ā they crash if their prerequisites are missing.
|
|
477
|
+
*/
|
|
478
|
+
const _OPTIONAL_NATIVE_PLUGINS = [
|
|
479
|
+
"@elizaos/plugin-browser", // requires browser server binary
|
|
480
|
+
"@elizaos/plugin-vision", // requires @tensorflow/tfjs-node native addon
|
|
481
|
+
"@elizaos/plugin-computeruse", // requires platform-specific binaries
|
|
482
|
+
];
|
|
483
|
+
/** Maps Milady channel names to plugin package names. */
|
|
484
|
+
export const CHANNEL_PLUGIN_MAP = {
|
|
485
|
+
discord: "@elizaos/plugin-discord",
|
|
486
|
+
telegram: "@elizaos/plugin-telegram",
|
|
487
|
+
slack: "@elizaos/plugin-slack",
|
|
488
|
+
twitter: "@elizaos/plugin-twitter",
|
|
489
|
+
// Internal connector built from src/plugins/whatsapp (not an npm package).
|
|
490
|
+
whatsapp: "@elizaos/plugin-whatsapp",
|
|
491
|
+
// Internal connector built from src/plugins/signal (not an npm package).
|
|
492
|
+
signal: "@elizaos/plugin-signal",
|
|
493
|
+
imessage: "@elizaos/plugin-imessage",
|
|
494
|
+
bluebubbles: "@elizaos/plugin-bluebubbles",
|
|
495
|
+
farcaster: "@elizaos/plugin-farcaster",
|
|
496
|
+
lens: "@elizaos/plugin-lens",
|
|
497
|
+
msteams: "@elizaos/plugin-msteams",
|
|
498
|
+
mattermost: "@elizaos/plugin-mattermost",
|
|
499
|
+
googlechat: "@elizaos/plugin-google-chat",
|
|
500
|
+
feishu: "@elizaos/plugin-feishu",
|
|
501
|
+
matrix: "@elizaos/plugin-matrix",
|
|
502
|
+
nostr: "@elizaos/plugin-nostr",
|
|
503
|
+
retake: "@elizaos/plugin-retake",
|
|
504
|
+
blooio: "@elizaos/plugin-blooio",
|
|
505
|
+
twitch: "@elizaos/plugin-twitch",
|
|
506
|
+
};
|
|
507
|
+
const PI_AI_PLUGIN_PACKAGE = "@elizaos/plugin-pi-ai";
|
|
508
|
+
function isPiAiEnabledFromEnv(env = process.env) {
|
|
509
|
+
const raw = env.MILADY_USE_PI_AI;
|
|
510
|
+
if (!raw)
|
|
511
|
+
return false;
|
|
512
|
+
const value = String(raw).trim().toLowerCase();
|
|
513
|
+
return value === "1" || value === "true" || value === "yes";
|
|
514
|
+
}
|
|
515
|
+
/** Maps environment variable names to model-provider plugin packages. */
|
|
516
|
+
const PROVIDER_PLUGIN_MAP = {
|
|
517
|
+
ANTHROPIC_API_KEY: "@elizaos/plugin-anthropic",
|
|
518
|
+
OPENAI_API_KEY: "@elizaos/plugin-openai",
|
|
519
|
+
GEMINI_API_KEY: "@elizaos/plugin-google-genai",
|
|
520
|
+
GOOGLE_API_KEY: "@elizaos/plugin-google-genai",
|
|
521
|
+
GOOGLE_GENERATIVE_AI_API_KEY: "@elizaos/plugin-google-genai",
|
|
522
|
+
GROQ_API_KEY: "@elizaos/plugin-groq",
|
|
523
|
+
XAI_API_KEY: "@elizaos/plugin-xai",
|
|
524
|
+
OPENROUTER_API_KEY: "@elizaos/plugin-openrouter",
|
|
525
|
+
AI_GATEWAY_API_KEY: "@elizaos/plugin-vercel-ai-gateway",
|
|
526
|
+
AIGATEWAY_API_KEY: "@elizaos/plugin-vercel-ai-gateway",
|
|
527
|
+
OLLAMA_BASE_URL: "@elizaos/plugin-ollama",
|
|
528
|
+
ZAI_API_KEY: "@homunculuslabs/plugin-zai",
|
|
529
|
+
MILADY_USE_PI_AI: PI_AI_PLUGIN_PACKAGE,
|
|
530
|
+
// ElizaCloud ā loaded when API key is present OR cloud is explicitly enabled
|
|
531
|
+
ELIZAOS_CLOUD_API_KEY: "@elizaos/plugin-elizacloud",
|
|
532
|
+
ELIZAOS_CLOUD_ENABLED: "@elizaos/plugin-elizacloud",
|
|
533
|
+
};
|
|
534
|
+
/**
|
|
535
|
+
* Optional feature plugins keyed by feature name.
|
|
536
|
+
*
|
|
537
|
+
* Mappings here support short IDs in allow-lists and feature toggles.
|
|
538
|
+
* Keep this map in sync with optional plugin registration and tests.
|
|
539
|
+
*/
|
|
540
|
+
const OPTIONAL_PLUGIN_MAP = {
|
|
541
|
+
browser: "@elizaos/plugin-browser",
|
|
542
|
+
vision: "@elizaos/plugin-vision",
|
|
543
|
+
cron: "@elizaos/plugin-cron",
|
|
544
|
+
cua: "@elizaos/plugin-cua",
|
|
545
|
+
computeruse: "@elizaos/plugin-computeruse",
|
|
546
|
+
obsidian: "@elizaos/plugin-obsidian",
|
|
547
|
+
repoprompt: "@elizaos/plugin-repoprompt",
|
|
548
|
+
repoPrompt: "@elizaos/plugin-repoprompt",
|
|
549
|
+
"pi-ai": PI_AI_PLUGIN_PACKAGE,
|
|
550
|
+
piAi: PI_AI_PLUGIN_PACKAGE,
|
|
551
|
+
x402: "@elizaos/plugin-x402",
|
|
552
|
+
"coding-agent": "@elizaos/plugin-agent-orchestrator",
|
|
553
|
+
"streaming-base": "@elizaos/plugin-streaming-base",
|
|
554
|
+
"twitch-streaming": "@elizaos/plugin-twitch-streaming",
|
|
555
|
+
"youtube-streaming": "@elizaos/plugin-youtube-streaming",
|
|
556
|
+
"custom-rtmp": "@elizaos/plugin-custom-rtmp",
|
|
557
|
+
"pumpfun-streaming": "@elizaos/plugin-pumpfun-streaming",
|
|
558
|
+
"x-streaming": "@elizaos/plugin-x-streaming",
|
|
559
|
+
};
|
|
560
|
+
function looksLikePlugin(value) {
|
|
561
|
+
if (!value || typeof value !== "object")
|
|
562
|
+
return false;
|
|
563
|
+
const obj = value;
|
|
564
|
+
if (typeof obj.name !== "string" || typeof obj.description !== "string") {
|
|
565
|
+
return false;
|
|
566
|
+
}
|
|
567
|
+
// Providers also expose { name, description } so we require at least one
|
|
568
|
+
// plugin-like capability field before accepting named exports as plugins.
|
|
569
|
+
return (Array.isArray(obj.services) ||
|
|
570
|
+
Array.isArray(obj.providers) ||
|
|
571
|
+
Array.isArray(obj.actions) ||
|
|
572
|
+
Array.isArray(obj.routes) ||
|
|
573
|
+
Array.isArray(obj.events) ||
|
|
574
|
+
typeof obj.init === "function");
|
|
575
|
+
}
|
|
576
|
+
function looksLikePluginBasic(value) {
|
|
577
|
+
if (!value || typeof value !== "object")
|
|
578
|
+
return false;
|
|
579
|
+
const obj = value;
|
|
580
|
+
return typeof obj.name === "string" && typeof obj.description === "string";
|
|
581
|
+
}
|
|
582
|
+
export function findRuntimePluginExport(mod) {
|
|
583
|
+
// 1. Prefer explicit default export
|
|
584
|
+
if (looksLikePlugin(mod.default))
|
|
585
|
+
return mod.default;
|
|
586
|
+
// 2. Check for a named `plugin` export
|
|
587
|
+
if (looksLikePlugin(mod.plugin))
|
|
588
|
+
return mod.plugin;
|
|
589
|
+
// 3. Check if the module itself looks like a Plugin (CJS default pattern).
|
|
590
|
+
if (looksLikePlugin(mod))
|
|
591
|
+
return mod;
|
|
592
|
+
// 4. Scan named exports in a deterministic order.
|
|
593
|
+
// Prefer keys ending with "Plugin" before generic exports like providers.
|
|
594
|
+
const namedKeys = Object.keys(mod).filter((key) => key !== "default" && key !== "plugin");
|
|
595
|
+
const preferredKeys = namedKeys.filter((key) => /plugin$/i.test(key) || /^plugin/i.test(key));
|
|
596
|
+
const fallbackKeys = namedKeys.filter((key) => !preferredKeys.includes(key));
|
|
597
|
+
for (const key of [...preferredKeys, ...fallbackKeys]) {
|
|
598
|
+
const value = mod[key];
|
|
599
|
+
if (looksLikePlugin(value))
|
|
600
|
+
return value;
|
|
601
|
+
}
|
|
602
|
+
// 5. Final compatibility fallback: accept minimal plugin-like exports only
|
|
603
|
+
// when the export name itself indicates it's a plugin.
|
|
604
|
+
for (const key of preferredKeys) {
|
|
605
|
+
const value = mod[key];
|
|
606
|
+
if (looksLikePluginBasic(value))
|
|
607
|
+
return value;
|
|
608
|
+
}
|
|
609
|
+
// 6. Legacy CJS compatibility for modules that export only { name, description }.
|
|
610
|
+
if (looksLikePluginBasic(mod))
|
|
611
|
+
return mod;
|
|
612
|
+
if (looksLikePluginBasic(mod.default))
|
|
613
|
+
return mod.default;
|
|
614
|
+
if (looksLikePluginBasic(mod.plugin))
|
|
615
|
+
return mod.plugin;
|
|
616
|
+
return null;
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* Collect the set of plugin package names that should be loaded
|
|
620
|
+
* based on config, environment variables, and feature flags.
|
|
621
|
+
*/
|
|
622
|
+
/** @internal Exported for testing. */
|
|
623
|
+
export function collectPluginNames(config) {
|
|
624
|
+
const shellPluginDisabled = config.features?.shellEnabled === false;
|
|
625
|
+
const cloudMode = config.cloud?.enabled;
|
|
626
|
+
const cloudHasApiKey = Boolean(config.cloud?.apiKey);
|
|
627
|
+
const cloudExplicitlyDisabled = cloudMode === false;
|
|
628
|
+
// Note: this is intentionally broader than the inference-path check in
|
|
629
|
+
// applyCloudConfigToEnv (which requires explicit `enabled: true`). Here
|
|
630
|
+
// hasApiKey acts as an implicit enable signal so the cloud *plugin* gets
|
|
631
|
+
// loaded for RPC/services (auth, credits, billing) even when inference
|
|
632
|
+
// itself is handled by the user's own keys (BYOK). The inference and
|
|
633
|
+
// persistence paths gate on `cloud.enabled === true` separately.
|
|
634
|
+
const cloudEffectivelyEnabled = cloudMode === true || (!cloudExplicitlyDisabled && cloudHasApiKey);
|
|
635
|
+
// When inferenceMode is "byok" or "local", OR services.inference is false,
|
|
636
|
+
// the user wants their own AI provider keys ā cloud stays enabled for
|
|
637
|
+
// RPC/services but does NOT hijack model inference.
|
|
638
|
+
//
|
|
639
|
+
// If the user chose a subscription provider (e.g. anthropic-subscription)
|
|
640
|
+
// during onboarding and never explicitly set inferenceMode, treat that as
|
|
641
|
+
// "byok" ā the subscription IS the user's inference choice.
|
|
642
|
+
const hasSubscriptionProvider = Boolean(config.agents?.defaults?.subscriptionProvider);
|
|
643
|
+
const explicitInferenceMode = config.cloud?.inferenceMode;
|
|
644
|
+
const cloudInferenceMode = explicitInferenceMode ?? (hasSubscriptionProvider ? "byok" : "cloud");
|
|
645
|
+
const cloudInferenceToggle = config.cloud?.services?.inference ?? true;
|
|
646
|
+
const cloudHandlesInference = cloudEffectivelyEnabled &&
|
|
647
|
+
cloudInferenceMode === "cloud" &&
|
|
648
|
+
cloudInferenceToggle !== false;
|
|
649
|
+
const configEnv = config.env;
|
|
650
|
+
const configPiAiFlag = (configEnv?.vars &&
|
|
651
|
+
typeof configEnv.vars === "object" &&
|
|
652
|
+
!Array.isArray(configEnv.vars)
|
|
653
|
+
? configEnv.vars.MILADY_USE_PI_AI
|
|
654
|
+
: undefined) ?? configEnv?.MILADY_USE_PI_AI;
|
|
655
|
+
const piAiEnabled = isPiAiEnabledFromEnv(process.env) ||
|
|
656
|
+
(typeof configPiAiFlag === "string" &&
|
|
657
|
+
isPiAiEnabledFromEnv({
|
|
658
|
+
MILADY_USE_PI_AI: configPiAiFlag,
|
|
659
|
+
}));
|
|
660
|
+
const pluginEntries = config.plugins
|
|
661
|
+
?.entries;
|
|
662
|
+
const isPluginExplicitlyDisabled = (pluginPackageName) => {
|
|
663
|
+
const marker = "/plugin-";
|
|
664
|
+
const markerIndex = pluginPackageName.lastIndexOf(marker);
|
|
665
|
+
const pluginId = markerIndex >= 0
|
|
666
|
+
? pluginPackageName.slice(markerIndex + marker.length)
|
|
667
|
+
: pluginPackageName;
|
|
668
|
+
return pluginEntries?.[pluginId]?.enabled === false;
|
|
669
|
+
};
|
|
670
|
+
const providerPluginIdSet = new Set(Object.values(PROVIDER_PLUGIN_MAP).map((pluginPackageName) => {
|
|
671
|
+
const marker = "/plugin-";
|
|
672
|
+
const markerIndex = pluginPackageName.lastIndexOf(marker);
|
|
673
|
+
return markerIndex >= 0
|
|
674
|
+
? pluginPackageName.slice(markerIndex + marker.length)
|
|
675
|
+
: pluginPackageName;
|
|
676
|
+
}));
|
|
677
|
+
const explicitProviderEntries = Object.entries(pluginEntries ?? {}).filter(([pluginId]) => providerPluginIdSet.has(pluginId));
|
|
678
|
+
const hasExplicitEnabledProvider = explicitProviderEntries.some(([, entry]) => entry?.enabled === true);
|
|
679
|
+
// Allow-list entries are additive (extra plugins), not exclusive.
|
|
680
|
+
const allowList = config.plugins?.allow;
|
|
681
|
+
const pluginsToLoad = new Set(CORE_PLUGINS);
|
|
682
|
+
// Allow list is additive ā extra plugins on top of auto-detection,
|
|
683
|
+
// not an exclusive whitelist that blocks everything else.
|
|
684
|
+
if (allowList && allowList.length > 0) {
|
|
685
|
+
for (const item of allowList) {
|
|
686
|
+
const pluginName = CHANNEL_PLUGIN_MAP[item] ?? OPTIONAL_PLUGIN_MAP[item] ?? item;
|
|
687
|
+
pluginsToLoad.add(pluginName);
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
// Connector plugins ā load when connector has config entries
|
|
691
|
+
// Prefer config.connectors, fall back to config.channels for backward compatibility
|
|
692
|
+
const connectors = config.connectors ?? config.channels ?? {};
|
|
693
|
+
for (const [channelName, channelConfig] of Object.entries(connectors)) {
|
|
694
|
+
if (channelConfig && typeof channelConfig === "object") {
|
|
695
|
+
const pluginName = CHANNEL_PLUGIN_MAP[channelName];
|
|
696
|
+
if (pluginName) {
|
|
697
|
+
pluginsToLoad.add(pluginName);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
// Model-provider plugins ā load when env key is present
|
|
702
|
+
for (const [envKey, pluginName] of Object.entries(PROVIDER_PLUGIN_MAP)) {
|
|
703
|
+
if (envKey === "MILADY_USE_PI_AI") {
|
|
704
|
+
// pi-ai enablement uses dedicated boolean parsing + precedence logic below.
|
|
705
|
+
continue;
|
|
706
|
+
}
|
|
707
|
+
if (cloudExplicitlyDisabled &&
|
|
708
|
+
(envKey === "ELIZAOS_CLOUD_API_KEY" || envKey === "ELIZAOS_CLOUD_ENABLED")) {
|
|
709
|
+
continue;
|
|
710
|
+
}
|
|
711
|
+
if (isPluginExplicitlyDisabled(pluginName)) {
|
|
712
|
+
continue;
|
|
713
|
+
}
|
|
714
|
+
if (hasExplicitEnabledProvider) {
|
|
715
|
+
const marker = "/plugin-";
|
|
716
|
+
const markerIndex = pluginName.lastIndexOf(marker);
|
|
717
|
+
const pluginId = markerIndex >= 0
|
|
718
|
+
? pluginName.slice(markerIndex + marker.length)
|
|
719
|
+
: pluginName;
|
|
720
|
+
if (pluginEntries?.[pluginId]?.enabled !== true) {
|
|
721
|
+
continue;
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
if (process.env[envKey]?.trim()) {
|
|
725
|
+
pluginsToLoad.add(pluginName);
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
const shouldEnablePiAi = piAiEnabled && pluginEntries?.["pi-ai"]?.enabled !== false;
|
|
729
|
+
const applyProviderPrecedence = () => {
|
|
730
|
+
// Provider precedence:
|
|
731
|
+
// 1) ElizaCloud for inference (when enabled AND inferenceMode is "cloud")
|
|
732
|
+
// 2) pi-ai (when enabled and cloud inference is not active)
|
|
733
|
+
// 3) direct provider plugins (api-key/env based)
|
|
734
|
+
//
|
|
735
|
+
// When inferenceMode is "byok" or "local", cloud stays loaded for
|
|
736
|
+
// RPC/services but direct AI provider plugins are preserved so the
|
|
737
|
+
// user's own API keys (e.g. Anthropic) handle model inference.
|
|
738
|
+
if (cloudEffectivelyEnabled) {
|
|
739
|
+
pluginsToLoad.add("@elizaos/plugin-elizacloud");
|
|
740
|
+
if (cloudHandlesInference) {
|
|
741
|
+
// Cloud handles ALL model calls ā remove direct AI provider plugins.
|
|
742
|
+
const directProviders = new Set(Object.values(PROVIDER_PLUGIN_MAP));
|
|
743
|
+
directProviders.delete("@elizaos/plugin-elizacloud");
|
|
744
|
+
for (const p of directProviders) {
|
|
745
|
+
pluginsToLoad.delete(p);
|
|
746
|
+
}
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
// inferenceMode is "byok" or "local" ā keep direct provider plugins.
|
|
750
|
+
// Cloud plugin stays loaded for non-inference cloud services (RPC, media, etc.)
|
|
751
|
+
// Pi-ai takes priority over direct providers when cloud inference is disabled.
|
|
752
|
+
if (shouldEnablePiAi) {
|
|
753
|
+
pluginsToLoad.add(PI_AI_PLUGIN_PACKAGE);
|
|
754
|
+
// Remove direct provider plugins ā pi-ai handles inference selection.
|
|
755
|
+
const directProviders = new Set(Object.values(PROVIDER_PLUGIN_MAP));
|
|
756
|
+
directProviders.delete(PI_AI_PLUGIN_PACKAGE);
|
|
757
|
+
directProviders.delete("@elizaos/plugin-elizacloud");
|
|
758
|
+
for (const p of directProviders) {
|
|
759
|
+
pluginsToLoad.delete(p);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
if (shouldEnablePiAi) {
|
|
765
|
+
pluginsToLoad.add(PI_AI_PLUGIN_PACKAGE);
|
|
766
|
+
// When pi-ai is active, remove direct provider plugins + cloud plugin.
|
|
767
|
+
// pi-ai performs the upstream provider selection itself.
|
|
768
|
+
const directProviders = new Set(Object.values(PROVIDER_PLUGIN_MAP));
|
|
769
|
+
directProviders.delete(PI_AI_PLUGIN_PACKAGE);
|
|
770
|
+
for (const p of directProviders) {
|
|
771
|
+
pluginsToLoad.delete(p);
|
|
772
|
+
}
|
|
773
|
+
pluginsToLoad.delete("@elizaos/plugin-elizacloud");
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
if (cloudExplicitlyDisabled) {
|
|
777
|
+
// Cloud was explicitly disabled ā remove elizacloud even though it's
|
|
778
|
+
// in CORE_PLUGINS, so it cannot intercept model calls.
|
|
779
|
+
pluginsToLoad.delete("@elizaos/plugin-elizacloud");
|
|
780
|
+
}
|
|
781
|
+
};
|
|
782
|
+
// Apply once before additive plugin-entry/feature paths.
|
|
783
|
+
applyProviderPrecedence();
|
|
784
|
+
// Optional feature plugins from config.plugins.entries
|
|
785
|
+
const pluginsConfig = config.plugins;
|
|
786
|
+
if (pluginsConfig?.entries) {
|
|
787
|
+
for (const [key, entry] of Object.entries(pluginsConfig.entries)) {
|
|
788
|
+
if (entry &&
|
|
789
|
+
typeof entry === "object" &&
|
|
790
|
+
entry.enabled !== false) {
|
|
791
|
+
// Connector keys (telegram, discord, etc.) must use CHANNEL_PLUGIN_MAP
|
|
792
|
+
// so the correct variant loads.
|
|
793
|
+
const pluginName = CHANNEL_PLUGIN_MAP[key] ??
|
|
794
|
+
OPTIONAL_PLUGIN_MAP[key] ??
|
|
795
|
+
(key.includes("/") ? key : `@elizaos/plugin-${key}`);
|
|
796
|
+
pluginsToLoad.add(pluginName);
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
// Feature flags (config.features)
|
|
801
|
+
const features = config.features;
|
|
802
|
+
if (features && typeof features === "object") {
|
|
803
|
+
for (const [featureName, featureValue] of Object.entries(features)) {
|
|
804
|
+
const isEnabled = featureValue === true ||
|
|
805
|
+
(typeof featureValue === "object" &&
|
|
806
|
+
featureValue !== null &&
|
|
807
|
+
featureValue.enabled !== false);
|
|
808
|
+
if (isEnabled) {
|
|
809
|
+
const pluginName = OPTIONAL_PLUGIN_MAP[featureName];
|
|
810
|
+
if (pluginName) {
|
|
811
|
+
pluginsToLoad.add(pluginName);
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
// x402 plugin ā auto-load when config section enabled
|
|
817
|
+
if (config.x402?.enabled) {
|
|
818
|
+
pluginsToLoad.add("@elizaos/plugin-x402");
|
|
819
|
+
}
|
|
820
|
+
// Opinion plugin ā auto-load when API key is present.
|
|
821
|
+
// NOT in PROVIDER_PLUGIN_MAP because it is a feature plugin, not a model
|
|
822
|
+
// provider, and would be incorrectly removed during provider precedence.
|
|
823
|
+
if (process.env.OPINION_API_KEY?.trim()) {
|
|
824
|
+
pluginsToLoad.add("@elizaos/plugin-opinion");
|
|
825
|
+
}
|
|
826
|
+
// User-installed plugins from config.plugins.installs
|
|
827
|
+
// These are plugins that were installed via the plugin-manager at runtime
|
|
828
|
+
// and tracked in milady.json so they persist across restarts.
|
|
829
|
+
const installs = config.plugins?.installs;
|
|
830
|
+
if (installs && typeof installs === "object") {
|
|
831
|
+
for (const [packageName, record] of Object.entries(installs)) {
|
|
832
|
+
if (record && typeof record === "object") {
|
|
833
|
+
pluginsToLoad.add(packageName);
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
// Re-apply provider precedence so later additive paths (entries, features,
|
|
838
|
+
// installs) cannot accidentally re-introduce suppressed providers.
|
|
839
|
+
applyProviderPrecedence();
|
|
840
|
+
// Enforce feature gating last so allow-list entries cannot bypass it.
|
|
841
|
+
if (shellPluginDisabled) {
|
|
842
|
+
pluginsToLoad.delete("@elizaos/plugin-shell");
|
|
843
|
+
}
|
|
844
|
+
if (isPluginExplicitlyDisabled("@elizaos/plugin-agent-orchestrator")) {
|
|
845
|
+
pluginsToLoad.delete("@elizaos/plugin-agent-orchestrator");
|
|
846
|
+
}
|
|
847
|
+
return pluginsToLoad;
|
|
848
|
+
}
|
|
849
|
+
// ---------------------------------------------------------------------------
|
|
850
|
+
// Custom / drop-in plugin discovery
|
|
851
|
+
// ---------------------------------------------------------------------------
|
|
852
|
+
/** Subdirectory under the Milady state dir for drop-in custom plugins. */
|
|
853
|
+
export const CUSTOM_PLUGINS_DIRNAME = "plugins/custom";
|
|
854
|
+
/** Subdirectory under the Milady state dir for ejected plugins. */
|
|
855
|
+
export const EJECTED_PLUGINS_DIRNAME = "plugins/ejected";
|
|
856
|
+
/**
|
|
857
|
+
* Scan a directory for drop-in plugin packages. Each immediate subdirectory
|
|
858
|
+
* is treated as a plugin; name comes from package.json or the directory name.
|
|
859
|
+
*/
|
|
860
|
+
export async function scanDropInPlugins(dir) {
|
|
861
|
+
const records = {};
|
|
862
|
+
let entries;
|
|
863
|
+
try {
|
|
864
|
+
entries = await fs.readdir(dir, { withFileTypes: true });
|
|
865
|
+
}
|
|
866
|
+
catch (err) {
|
|
867
|
+
if (err.code === "ENOENT") {
|
|
868
|
+
return records;
|
|
869
|
+
}
|
|
870
|
+
throw err;
|
|
871
|
+
}
|
|
872
|
+
for (const entry of entries) {
|
|
873
|
+
if (!entry.isDirectory())
|
|
874
|
+
continue;
|
|
875
|
+
const pluginDir = path.join(dir, entry.name);
|
|
876
|
+
let pluginName = entry.name;
|
|
877
|
+
let version = "0.0.0";
|
|
878
|
+
try {
|
|
879
|
+
const raw = await fs.readFile(path.join(pluginDir, "package.json"), "utf-8");
|
|
880
|
+
const pkg = JSON.parse(raw);
|
|
881
|
+
if (typeof pkg.name === "string" && pkg.name.trim())
|
|
882
|
+
pluginName = pkg.name.trim();
|
|
883
|
+
if (typeof pkg.version === "string" && pkg.version.trim())
|
|
884
|
+
version = pkg.version.trim();
|
|
885
|
+
}
|
|
886
|
+
catch (err) {
|
|
887
|
+
if (err.code !== "ENOENT" &&
|
|
888
|
+
!(err instanceof SyntaxError)) {
|
|
889
|
+
throw err;
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
records[pluginName] = { source: "path", installPath: pluginDir, version };
|
|
893
|
+
}
|
|
894
|
+
return records;
|
|
895
|
+
}
|
|
896
|
+
/**
|
|
897
|
+
* Merge drop-in plugins into the load set. Filters out denied, core-colliding,
|
|
898
|
+
* and already-installed names. Mutates `pluginsToLoad` and `installRecords`.
|
|
899
|
+
*/
|
|
900
|
+
export function mergeDropInPlugins(params) {
|
|
901
|
+
const { dropInRecords, installRecords, corePluginNames, denyList, pluginsToLoad, } = params;
|
|
902
|
+
const accepted = [];
|
|
903
|
+
const skipped = [];
|
|
904
|
+
for (const [name, record] of Object.entries(dropInRecords)) {
|
|
905
|
+
if (denyList.has(name) || installRecords[name])
|
|
906
|
+
continue;
|
|
907
|
+
if (corePluginNames.has(name)) {
|
|
908
|
+
skipped.push(`[milady] Custom plugin "${name}" collides with core plugin ā skipping`);
|
|
909
|
+
continue;
|
|
910
|
+
}
|
|
911
|
+
pluginsToLoad.add(name);
|
|
912
|
+
installRecords[name] = record;
|
|
913
|
+
accepted.push(name);
|
|
914
|
+
}
|
|
915
|
+
return { accepted, skipped };
|
|
916
|
+
}
|
|
917
|
+
const WORKSPACE_PLUGIN_OVERRIDES = new Set([
|
|
918
|
+
// "@elizaos/plugin-trajectory-logger",
|
|
919
|
+
// "@elizaos/plugin-plugin-manager",
|
|
920
|
+
// "@elizaos/plugin-media-generation",
|
|
921
|
+
"@elizaos/plugin-twitch-streaming",
|
|
922
|
+
"@elizaos/plugin-youtube-streaming",
|
|
923
|
+
"@elizaos/plugin-retake",
|
|
924
|
+
]);
|
|
925
|
+
function getWorkspacePluginOverridePath(pluginName) {
|
|
926
|
+
if (process.env.MILADY_DISABLE_WORKSPACE_PLUGIN_OVERRIDES === "1") {
|
|
927
|
+
return null;
|
|
928
|
+
}
|
|
929
|
+
if (!WORKSPACE_PLUGIN_OVERRIDES.has(pluginName)) {
|
|
930
|
+
return null;
|
|
931
|
+
}
|
|
932
|
+
const pluginSegmentMatch = pluginName.match(/^@[^/]+\/(plugin-[^/]+)$/);
|
|
933
|
+
const pluginSegment = pluginSegmentMatch?.[1];
|
|
934
|
+
if (!pluginSegment)
|
|
935
|
+
return null;
|
|
936
|
+
const thisDir = path.dirname(fileURLToPath(import.meta.url));
|
|
937
|
+
const miladyRoot = path.resolve(thisDir, "..", "..");
|
|
938
|
+
const workspaceRoot = path.resolve(miladyRoot, "..");
|
|
939
|
+
const candidates = [
|
|
940
|
+
path.join(miladyRoot, "plugins", pluginSegment, "typescript"),
|
|
941
|
+
path.join(workspaceRoot, "plugins", pluginSegment, "typescript"),
|
|
942
|
+
path.join(miladyRoot, "plugins", pluginSegment),
|
|
943
|
+
path.join(workspaceRoot, "plugins", pluginSegment),
|
|
944
|
+
path.join(miladyRoot, "packages", pluginSegment),
|
|
945
|
+
path.join(workspaceRoot, "packages", pluginSegment),
|
|
946
|
+
];
|
|
947
|
+
for (const candidate of candidates) {
|
|
948
|
+
if (existsSync(path.join(candidate, "package.json"))) {
|
|
949
|
+
return candidate;
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
return null;
|
|
953
|
+
}
|
|
954
|
+
export function resolveMiladyPluginImportSpecifier(pluginName, runtimeModuleUrl = import.meta.url) {
|
|
955
|
+
if (!pluginName.startsWith("@elizaos/plugin-")) {
|
|
956
|
+
return pluginName;
|
|
957
|
+
}
|
|
958
|
+
const shortName = pluginName.replace("@elizaos/plugin-", "");
|
|
959
|
+
const thisDir = path.dirname(fileURLToPath(runtimeModuleUrl));
|
|
960
|
+
const distRoot = thisDir.endsWith("runtime")
|
|
961
|
+
? path.resolve(thisDir, "..")
|
|
962
|
+
: thisDir;
|
|
963
|
+
const indexPath = path.resolve(distRoot, "plugins", shortName, "index.js");
|
|
964
|
+
return existsSync(indexPath) ? pathToFileURL(indexPath).href : pluginName;
|
|
965
|
+
}
|
|
966
|
+
export function shouldIgnoreMissingPluginExport(pluginName) {
|
|
967
|
+
return pluginName === "@elizaos/plugin-streaming-base";
|
|
968
|
+
}
|
|
969
|
+
// ---------------------------------------------------------------------------
|
|
970
|
+
// Plugin resolution
|
|
971
|
+
// ---------------------------------------------------------------------------
|
|
972
|
+
// ---------------------------------------------------------------------------
|
|
973
|
+
// Browser server pre-flight
|
|
974
|
+
// ---------------------------------------------------------------------------
|
|
975
|
+
/**
|
|
976
|
+
* The `@elizaos/plugin-browser` npm package expects a `dist/server/` directory
|
|
977
|
+
* containing the compiled stagehand-server, but the npm publish doesn't include
|
|
978
|
+
* it. The actual source/build lives in the workspace at
|
|
979
|
+
* `plugins/plugin-browser/stagehand-server/`.
|
|
980
|
+
*
|
|
981
|
+
* This function checks whether the server is reachable from the installed
|
|
982
|
+
* package and, if not, creates a symlink so the plugin's process-manager can
|
|
983
|
+
* find it. Returns `true` when the server index.js is available (or was made
|
|
984
|
+
* available via symlink), `false` otherwise.
|
|
985
|
+
*/
|
|
986
|
+
/**
|
|
987
|
+
* Returns true if the given env var key is safe to forward to runtime.settings.
|
|
988
|
+
* Blocks blockchain private keys, secrets, passwords, tokens, credentials,
|
|
989
|
+
* mnemonics, and seed phrases while allowing API keys that plugins need.
|
|
990
|
+
*/
|
|
991
|
+
export function isEnvKeyAllowedForForwarding(key) {
|
|
992
|
+
const upper = key.toUpperCase();
|
|
993
|
+
// Block blockchain private keys
|
|
994
|
+
if (upper.includes("PRIVATE_KEY"))
|
|
995
|
+
return false;
|
|
996
|
+
if (upper.startsWith("EVM_") || upper.startsWith("SOLANA_"))
|
|
997
|
+
return false;
|
|
998
|
+
// Block secrets, passwords, tokens, and seed phrases (but not API_KEY which plugins need)
|
|
999
|
+
if (/(SECRET|PASSWORD|CREDENTIAL|MNEMONIC|SEED_PHRASE)/i.test(key))
|
|
1000
|
+
return false;
|
|
1001
|
+
if (/(ACCESS_TOKEN|REFRESH_TOKEN|SESSION_TOKEN|AUTH_TOKEN)$/i.test(key))
|
|
1002
|
+
return false;
|
|
1003
|
+
return true;
|
|
1004
|
+
}
|
|
1005
|
+
export function ensureBrowserServerLink() {
|
|
1006
|
+
try {
|
|
1007
|
+
// Resolve the plugin-browser package root via its package.json.
|
|
1008
|
+
const req = createRequire(import.meta.url);
|
|
1009
|
+
const pkgJsonPath = req.resolve("@elizaos/plugin-browser/package.json");
|
|
1010
|
+
const pluginRoot = path.dirname(pkgJsonPath);
|
|
1011
|
+
const serverDir = path.join(pluginRoot, "dist", "server");
|
|
1012
|
+
const serverIndex = path.join(serverDir, "dist", "index");
|
|
1013
|
+
// Already linked / available ā nothing to do.
|
|
1014
|
+
if (existsSync(serverIndex))
|
|
1015
|
+
return true;
|
|
1016
|
+
// Walk upward from this file to find the eliza-workspace root.
|
|
1017
|
+
// Layout: <workspace>/milady/src/runtime/eliza.ts
|
|
1018
|
+
const thisDir = path.dirname(fileURLToPath(import.meta.url));
|
|
1019
|
+
const miladyRoot = path.resolve(thisDir, "..", "..");
|
|
1020
|
+
const workspaceRoot = path.resolve(miladyRoot, "..");
|
|
1021
|
+
const stagehandDir = path.join(workspaceRoot, "plugins", "plugin-browser", "stagehand-server");
|
|
1022
|
+
const stagehandIndex = path.join(stagehandDir, "dist", "index");
|
|
1023
|
+
if (!existsSync(stagehandIndex)) {
|
|
1024
|
+
logger.info(`[milady] Browser server not found at ${stagehandDir} ā ` +
|
|
1025
|
+
`@elizaos/plugin-browser will not be loaded`);
|
|
1026
|
+
return false;
|
|
1027
|
+
}
|
|
1028
|
+
// Create symlink: dist/server -> stagehand-server
|
|
1029
|
+
symlinkSync(stagehandDir, serverDir, "dir");
|
|
1030
|
+
logger.info(`[milady] Linked browser server: ${serverDir} -> ${stagehandDir}`);
|
|
1031
|
+
return true;
|
|
1032
|
+
}
|
|
1033
|
+
catch (err) {
|
|
1034
|
+
logger.debug(`[milady] Could not link browser server: ${formatError(err)}`);
|
|
1035
|
+
return false;
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
// ---------------------------------------------------------------------------
|
|
1039
|
+
// Plugin resolution
|
|
1040
|
+
// ---------------------------------------------------------------------------
|
|
1041
|
+
/**
|
|
1042
|
+
* Resolve Milady plugins from config and auto-enable logic.
|
|
1043
|
+
* Returns an array of elizaOS Plugin instances ready for AgentRuntime.
|
|
1044
|
+
*
|
|
1045
|
+
* Handles three categories of plugins:
|
|
1046
|
+
* 1. Built-in/npm plugins ā imported by package name
|
|
1047
|
+
* 2. User-installed plugins ā from ~/.milady/plugins/installed/
|
|
1048
|
+
* 3. Custom/drop-in plugins ā from ~/.milady/plugins/custom/ and plugins.load.paths
|
|
1049
|
+
*
|
|
1050
|
+
* Each plugin is loaded inside an error boundary so a single failing plugin
|
|
1051
|
+
* cannot crash the entire agent startup.
|
|
1052
|
+
*/
|
|
1053
|
+
/**
|
|
1054
|
+
* Resolve a statically-imported @elizaos plugin by name.
|
|
1055
|
+
* Returns the module if found in STATIC_ELIZA_PLUGINS, otherwise null.
|
|
1056
|
+
*/
|
|
1057
|
+
function resolveStaticElizaPlugin(pluginName) {
|
|
1058
|
+
return STATIC_ELIZA_PLUGINS[pluginName] ?? null;
|
|
1059
|
+
}
|
|
1060
|
+
async function resolvePlugins(config, opts) {
|
|
1061
|
+
const plugins = [];
|
|
1062
|
+
const failedPlugins = [];
|
|
1063
|
+
const repairedInstallRecords = new Set();
|
|
1064
|
+
applyPluginAutoEnable({
|
|
1065
|
+
config,
|
|
1066
|
+
env: process.env,
|
|
1067
|
+
});
|
|
1068
|
+
const pluginsToLoad = collectPluginNames(config);
|
|
1069
|
+
const corePluginSet = new Set(CORE_PLUGINS);
|
|
1070
|
+
// Build a mutable map of install records so we can merge drop-in discoveries
|
|
1071
|
+
const installRecords = {
|
|
1072
|
+
...(config.plugins?.installs ?? {}),
|
|
1073
|
+
};
|
|
1074
|
+
const denyList = new Set(config.plugins?.deny ?? []);
|
|
1075
|
+
// āā Auto-discover ejected plugins āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
|
|
1076
|
+
// Ejected plugins override npm/core versions, so they are tracked
|
|
1077
|
+
// separately and consulted first at import time.
|
|
1078
|
+
const ejectedRecords = await scanDropInPlugins(path.join(resolveStateDir(), EJECTED_PLUGINS_DIRNAME));
|
|
1079
|
+
const ejectedPluginNames = [];
|
|
1080
|
+
for (const [name, _record] of Object.entries(ejectedRecords)) {
|
|
1081
|
+
if (denyList.has(name))
|
|
1082
|
+
continue;
|
|
1083
|
+
pluginsToLoad.add(name);
|
|
1084
|
+
ejectedPluginNames.push(name);
|
|
1085
|
+
}
|
|
1086
|
+
if (ejectedPluginNames.length > 0) {
|
|
1087
|
+
logger.info(`[milady] Discovered ${ejectedPluginNames.length} ejected plugin(s): ${ejectedPluginNames.join(", ")}`);
|
|
1088
|
+
}
|
|
1089
|
+
// āā Auto-discover drop-in custom plugins āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
|
|
1090
|
+
// Scan well-known dir + any extra dirs from plugins.load.paths (first wins).
|
|
1091
|
+
const scanDirs = [
|
|
1092
|
+
path.join(resolveStateDir(), CUSTOM_PLUGINS_DIRNAME),
|
|
1093
|
+
...(config.plugins?.load?.paths ?? []).map(resolveUserPath),
|
|
1094
|
+
];
|
|
1095
|
+
const dropInRecords = {};
|
|
1096
|
+
for (const dir of scanDirs) {
|
|
1097
|
+
for (const [name, record] of Object.entries(await scanDropInPlugins(dir))) {
|
|
1098
|
+
if (!dropInRecords[name])
|
|
1099
|
+
dropInRecords[name] = record;
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
// Merge into load set ā deny list and core collisions are filtered out.
|
|
1103
|
+
const { accepted: customPluginNames, skipped } = mergeDropInPlugins({
|
|
1104
|
+
dropInRecords,
|
|
1105
|
+
installRecords,
|
|
1106
|
+
corePluginNames: corePluginSet,
|
|
1107
|
+
denyList,
|
|
1108
|
+
pluginsToLoad,
|
|
1109
|
+
});
|
|
1110
|
+
for (const msg of skipped)
|
|
1111
|
+
logger.warn(msg);
|
|
1112
|
+
if (customPluginNames.length > 0) {
|
|
1113
|
+
logger.info(`[milady] Discovered ${customPluginNames.length} custom plugin(s): ${customPluginNames.join(", ")}`);
|
|
1114
|
+
}
|
|
1115
|
+
logger.info(`[milady] Resolving ${pluginsToLoad.size} plugins...`);
|
|
1116
|
+
const loadStartTime = Date.now();
|
|
1117
|
+
// Built once so we don't rebuild on every optional plugin failure.
|
|
1118
|
+
const optionalPluginNames = new Set([
|
|
1119
|
+
...Object.values(OPTIONAL_PLUGIN_MAP),
|
|
1120
|
+
...Object.values(CHANNEL_PLUGIN_MAP),
|
|
1121
|
+
...OPTIONAL_CORE_PLUGINS,
|
|
1122
|
+
]);
|
|
1123
|
+
// Load a single plugin - returns result or null on skip/failure
|
|
1124
|
+
async function loadSinglePlugin(pluginName) {
|
|
1125
|
+
const isCore = corePluginSet.has(pluginName);
|
|
1126
|
+
const ejectedRecord = ejectedRecords[pluginName];
|
|
1127
|
+
const installRecord = installRecords[pluginName];
|
|
1128
|
+
const workspaceOverridePath = getWorkspacePluginOverridePath(pluginName);
|
|
1129
|
+
// Pre-flight: ensure native dependencies are available for special plugins.
|
|
1130
|
+
if (pluginName === "@elizaos/plugin-browser") {
|
|
1131
|
+
if (!ensureBrowserServerLink()) {
|
|
1132
|
+
failedPlugins.push({
|
|
1133
|
+
name: pluginName,
|
|
1134
|
+
error: "browser server binary not found",
|
|
1135
|
+
});
|
|
1136
|
+
logger.warn(`[milady] Skipping ${pluginName}: browser server not available. ` +
|
|
1137
|
+
`Build the stagehand-server or remove the plugin from plugins.allow.`);
|
|
1138
|
+
return null;
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
try {
|
|
1142
|
+
let mod;
|
|
1143
|
+
if (ejectedRecord?.installPath) {
|
|
1144
|
+
// Ejected plugin ā always prefer local source over npm/core.
|
|
1145
|
+
logger.debug(`[milady] Loading ejected plugin: ${pluginName} from ${ejectedRecord.installPath}`);
|
|
1146
|
+
mod = await importFromPath(ejectedRecord.installPath, pluginName);
|
|
1147
|
+
}
|
|
1148
|
+
else if (workspaceOverridePath) {
|
|
1149
|
+
logger.debug(`[milady] Loading workspace plugin override: ${pluginName} from ${workspaceOverridePath}`);
|
|
1150
|
+
mod = await importFromPath(workspaceOverridePath, pluginName);
|
|
1151
|
+
}
|
|
1152
|
+
else if (installRecord?.installPath) {
|
|
1153
|
+
// Prefer bundled/node_modules copies for official Eliza plugins.
|
|
1154
|
+
const isOfficialElizaPlugin = pluginName.startsWith("@elizaos/plugin-");
|
|
1155
|
+
if (isOfficialElizaPlugin) {
|
|
1156
|
+
try {
|
|
1157
|
+
const staticMod = await resolveStaticElizaPlugin(pluginName);
|
|
1158
|
+
mod = staticMod
|
|
1159
|
+
? staticMod
|
|
1160
|
+
: (await import(pluginName));
|
|
1161
|
+
if (repairBrokenInstallRecord(config, pluginName)) {
|
|
1162
|
+
repairedInstallRecords.add(pluginName);
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
catch (npmErr) {
|
|
1166
|
+
logger.warn(`[milady] Node_modules resolution failed for ${pluginName} (${formatError(npmErr)}). Trying installed path at ${installRecord.installPath}.`);
|
|
1167
|
+
mod = await importFromPath(installRecord.installPath, pluginName);
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
else {
|
|
1171
|
+
// User-installed plugin ā load from its install directory on disk.
|
|
1172
|
+
try {
|
|
1173
|
+
mod = await importFromPath(installRecord.installPath, pluginName);
|
|
1174
|
+
}
|
|
1175
|
+
catch (installErr) {
|
|
1176
|
+
logger.warn(`[milady] Installed plugin ${pluginName} failed at ${installRecord.installPath} (${formatError(installErr)}). Falling back to node_modules resolution.`);
|
|
1177
|
+
const staticMod = await resolveStaticElizaPlugin(pluginName);
|
|
1178
|
+
mod = staticMod
|
|
1179
|
+
? staticMod
|
|
1180
|
+
: (await import(pluginName));
|
|
1181
|
+
if (repairBrokenInstallRecord(config, pluginName)) {
|
|
1182
|
+
repairedInstallRecords.add(pluginName);
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
else if (pluginName.startsWith("@elizaos/plugin-")) {
|
|
1188
|
+
// Milady plugins can resolve either from bundled local wrappers
|
|
1189
|
+
// under milady-dist/plugins/* or from packaged node_modules.
|
|
1190
|
+
mod = (await import(resolveMiladyPluginImportSpecifier(pluginName)));
|
|
1191
|
+
}
|
|
1192
|
+
else {
|
|
1193
|
+
// Built-in/npm plugin ā try bundled static import first, then
|
|
1194
|
+
// fall back to bare node_modules resolution.
|
|
1195
|
+
const staticMod = pluginName.startsWith("@elizaos/plugin-")
|
|
1196
|
+
? await resolveStaticElizaPlugin(pluginName)
|
|
1197
|
+
: null;
|
|
1198
|
+
mod = staticMod
|
|
1199
|
+
? staticMod
|
|
1200
|
+
: (await import(pluginName));
|
|
1201
|
+
}
|
|
1202
|
+
const pluginInstance = findRuntimePluginExport(mod);
|
|
1203
|
+
if (pluginInstance) {
|
|
1204
|
+
// Wrap the plugin's init function with an error boundary
|
|
1205
|
+
const wrappedPlugin = wrapPluginWithErrorBoundary(pluginName, pluginInstance);
|
|
1206
|
+
logger.debug(`[milady] ā Loaded plugin: ${pluginName}`);
|
|
1207
|
+
return { name: pluginName, plugin: wrappedPlugin };
|
|
1208
|
+
}
|
|
1209
|
+
else {
|
|
1210
|
+
if (shouldIgnoreMissingPluginExport(pluginName)) {
|
|
1211
|
+
logger.info(`[milady] Skipping helper package ${pluginName}: no Plugin export is expected`);
|
|
1212
|
+
return null;
|
|
1213
|
+
}
|
|
1214
|
+
const msg = `[milady] Plugin ${pluginName} did not export a valid Plugin object`;
|
|
1215
|
+
failedPlugins.push({
|
|
1216
|
+
name: pluginName,
|
|
1217
|
+
error: "no valid Plugin export",
|
|
1218
|
+
});
|
|
1219
|
+
if (isCore) {
|
|
1220
|
+
logger.error(msg);
|
|
1221
|
+
}
|
|
1222
|
+
else {
|
|
1223
|
+
logger.warn(msg);
|
|
1224
|
+
}
|
|
1225
|
+
return null;
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
catch (err) {
|
|
1229
|
+
const msg = formatError(err);
|
|
1230
|
+
failedPlugins.push({ name: pluginName, error: msg });
|
|
1231
|
+
if (isCore) {
|
|
1232
|
+
logger.error(`[milady] Failed to load core plugin ${pluginName}: ${msg}`);
|
|
1233
|
+
}
|
|
1234
|
+
else {
|
|
1235
|
+
if (optionalPluginNames.has(pluginName)) {
|
|
1236
|
+
logger.debug(`[milady] Optional plugin ${pluginName} not available: ${msg}`);
|
|
1237
|
+
}
|
|
1238
|
+
else {
|
|
1239
|
+
logger.info(`[milady] Could not load plugin ${pluginName}: ${msg}`);
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
return null;
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
// Load all plugins in parallel for faster startup
|
|
1246
|
+
const pluginResults = await Promise.all(Array.from(pluginsToLoad).map(loadSinglePlugin));
|
|
1247
|
+
// Collect successful loads
|
|
1248
|
+
for (const result of pluginResults) {
|
|
1249
|
+
if (result) {
|
|
1250
|
+
plugins.push(result);
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
const loadDuration = Date.now() - loadStartTime;
|
|
1254
|
+
logger.info(`[milady] Plugin loading took ${loadDuration}ms`);
|
|
1255
|
+
// Summary logging
|
|
1256
|
+
logger.info(`[milady] Plugin resolution complete: ${plugins.length}/${pluginsToLoad.size} loaded` +
|
|
1257
|
+
(failedPlugins.length > 0 ? `, ${failedPlugins.length} failed` : ""));
|
|
1258
|
+
if (failedPlugins.length > 0) {
|
|
1259
|
+
logger.info(`[milady] Failed plugins: ${failedPlugins.map((f) => `${f.name} (${f.error})`).join(", ")}`);
|
|
1260
|
+
}
|
|
1261
|
+
// Diagnose version-skew issues when AI providers failed to load (#10)
|
|
1262
|
+
const loadedNames = plugins.map((p) => p.name);
|
|
1263
|
+
const diagnostic = diagnoseNoAIProvider(loadedNames, failedPlugins);
|
|
1264
|
+
if (diagnostic) {
|
|
1265
|
+
if (opts?.quiet) {
|
|
1266
|
+
// In headless/GUI mode before onboarding, this is expected ā the user
|
|
1267
|
+
// will configure a provider through the onboarding wizard and restart.
|
|
1268
|
+
logger.info(`[milady] ${diagnostic}`);
|
|
1269
|
+
}
|
|
1270
|
+
else {
|
|
1271
|
+
logger.error(`[milady] ${diagnostic}`);
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
// Persist repaired install records so future startups do not keep trying
|
|
1275
|
+
// to import from stale install directories.
|
|
1276
|
+
if (repairedInstallRecords.size > 0) {
|
|
1277
|
+
try {
|
|
1278
|
+
saveMiladyConfig(config);
|
|
1279
|
+
logger.info(`[milady] Repaired ${repairedInstallRecords.size} plugin install record(s): ${Array.from(repairedInstallRecords).join(", ")}`);
|
|
1280
|
+
}
|
|
1281
|
+
catch (err) {
|
|
1282
|
+
logger.warn(`[milady] Failed to persist plugin install repairs: ${formatError(err)}`);
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
return plugins;
|
|
1286
|
+
}
|
|
1287
|
+
/** @internal Exported for testing. */
|
|
1288
|
+
export function repairBrokenInstallRecord(config, pluginName) {
|
|
1289
|
+
const record = config.plugins?.installs?.[pluginName];
|
|
1290
|
+
if (!record || typeof record.installPath !== "string")
|
|
1291
|
+
return false;
|
|
1292
|
+
if (!record.installPath.trim())
|
|
1293
|
+
return false;
|
|
1294
|
+
// Keep the plugin listed as installed but force node_modules resolution.
|
|
1295
|
+
record.installPath = "";
|
|
1296
|
+
record.source = "npm";
|
|
1297
|
+
return true;
|
|
1298
|
+
}
|
|
1299
|
+
/**
|
|
1300
|
+
* Wrap a plugin's `init` and `providers` with error boundaries so that a
|
|
1301
|
+
* crash in any single plugin does not take down the entire agent or GUI.
|
|
1302
|
+
*
|
|
1303
|
+
* NOTE: Actions are NOT wrapped here because elizaOS's action dispatch
|
|
1304
|
+
* already has its own error boundary. Only `init` (startup) and
|
|
1305
|
+
* `providers` (called every turn) need protection at this layer.
|
|
1306
|
+
*
|
|
1307
|
+
* The wrapper catches errors, logs them with the plugin name for easy
|
|
1308
|
+
* debugging, and continues execution.
|
|
1309
|
+
*/
|
|
1310
|
+
function wrapPluginWithErrorBoundary(pluginName, plugin) {
|
|
1311
|
+
const wrapped = { ...plugin };
|
|
1312
|
+
// Wrap init if present
|
|
1313
|
+
if (plugin.init) {
|
|
1314
|
+
const originalInit = plugin.init;
|
|
1315
|
+
wrapped.init = async (...args) => {
|
|
1316
|
+
try {
|
|
1317
|
+
return await originalInit(...args);
|
|
1318
|
+
}
|
|
1319
|
+
catch (err) {
|
|
1320
|
+
logger.error(`[milady] Plugin "${pluginName}" crashed during init: ${formatError(err)}`);
|
|
1321
|
+
// Surface the error but don't rethrow ā the agent continues
|
|
1322
|
+
// without this plugin's init having completed.
|
|
1323
|
+
logger.warn(`[milady] Plugin "${pluginName}" will run in degraded mode (init failed)`);
|
|
1324
|
+
}
|
|
1325
|
+
};
|
|
1326
|
+
}
|
|
1327
|
+
// Wrap providers with error boundaries
|
|
1328
|
+
if (plugin.providers && plugin.providers.length > 0) {
|
|
1329
|
+
wrapped.providers = plugin.providers.map((provider) => ({
|
|
1330
|
+
...provider,
|
|
1331
|
+
get: async (...args) => {
|
|
1332
|
+
try {
|
|
1333
|
+
return await provider.get(...args);
|
|
1334
|
+
}
|
|
1335
|
+
catch (err) {
|
|
1336
|
+
const msg = formatError(err);
|
|
1337
|
+
logger.error(`[milady] Provider "${provider.name}" (plugin: ${pluginName}) crashed: ${msg}`);
|
|
1338
|
+
// Return an error marker so downstream consumers can detect
|
|
1339
|
+
// the failure rather than silently using empty data.
|
|
1340
|
+
return {
|
|
1341
|
+
text: `[Provider ${provider.name} error: ${msg}]`,
|
|
1342
|
+
data: { _providerError: true },
|
|
1343
|
+
};
|
|
1344
|
+
}
|
|
1345
|
+
},
|
|
1346
|
+
}));
|
|
1347
|
+
}
|
|
1348
|
+
return wrapped;
|
|
1349
|
+
}
|
|
1350
|
+
/**
|
|
1351
|
+
* Import a plugin module from its install directory on disk.
|
|
1352
|
+
*
|
|
1353
|
+
* Handles two install layouts:
|
|
1354
|
+
* 1. npm layout: <installPath>/node_modules/@scope/package/ (from `bun add`)
|
|
1355
|
+
* 2. git layout: <installPath>/ is the package root directly (from `git clone`)
|
|
1356
|
+
*
|
|
1357
|
+
* @param installPath Root directory of the installation (e.g. ~/.milady/plugins/installed/foo/).
|
|
1358
|
+
* @param packageName The npm package name (e.g. "@elizaos/plugin-discord") ā used
|
|
1359
|
+
* to navigate directly into node_modules when present.
|
|
1360
|
+
*/
|
|
1361
|
+
async function importFromPath(installPath, packageName) {
|
|
1362
|
+
const absPath = path.resolve(installPath);
|
|
1363
|
+
// npm/bun layout: installPath/node_modules/@scope/name/
|
|
1364
|
+
// git layout: installPath/ is the package itself
|
|
1365
|
+
const nmCandidate = path.join(absPath, "node_modules", ...packageName.split("/"));
|
|
1366
|
+
let pkgRoot = absPath;
|
|
1367
|
+
try {
|
|
1368
|
+
if ((await fs.stat(nmCandidate)).isDirectory())
|
|
1369
|
+
pkgRoot = nmCandidate;
|
|
1370
|
+
}
|
|
1371
|
+
catch (err) {
|
|
1372
|
+
if (err.code !== "ENOENT") {
|
|
1373
|
+
throw err;
|
|
1374
|
+
}
|
|
1375
|
+
/* git layout ā pkgRoot stays as absPath */
|
|
1376
|
+
}
|
|
1377
|
+
// Resolve entry point from package.json
|
|
1378
|
+
const entryPoint = await resolvePackageEntry(pkgRoot);
|
|
1379
|
+
return (await import(pathToFileURL(entryPoint).href));
|
|
1380
|
+
}
|
|
1381
|
+
/** Read package.json exports/main to find the importable entry file. */
|
|
1382
|
+
/** @internal Exported for testing. */
|
|
1383
|
+
export async function resolvePackageEntry(pkgRoot) {
|
|
1384
|
+
const fallback = path.join(pkgRoot, "dist", "index");
|
|
1385
|
+
const fallbackCandidates = [
|
|
1386
|
+
fallback,
|
|
1387
|
+
path.join(pkgRoot, "index"),
|
|
1388
|
+
path.join(pkgRoot, "index.mjs"),
|
|
1389
|
+
path.join(pkgRoot, "index.ts"),
|
|
1390
|
+
path.join(pkgRoot, "src", "index"),
|
|
1391
|
+
path.join(pkgRoot, "src", "index.mjs"),
|
|
1392
|
+
path.join(pkgRoot, "src", "index.ts"),
|
|
1393
|
+
];
|
|
1394
|
+
const chooseExisting = (...paths) => {
|
|
1395
|
+
const seen = new Set();
|
|
1396
|
+
for (const p of paths) {
|
|
1397
|
+
const resolved = path.resolve(p);
|
|
1398
|
+
if (seen.has(resolved))
|
|
1399
|
+
continue;
|
|
1400
|
+
seen.add(resolved);
|
|
1401
|
+
if (existsSync(resolved))
|
|
1402
|
+
return resolved;
|
|
1403
|
+
}
|
|
1404
|
+
// Return first candidate even when missing so callers still get a useful path in errors.
|
|
1405
|
+
return path.resolve(paths[0] ?? fallback);
|
|
1406
|
+
};
|
|
1407
|
+
try {
|
|
1408
|
+
const raw = await fs.readFile(path.join(pkgRoot, "package.json"), "utf-8");
|
|
1409
|
+
const pkg = JSON.parse(raw);
|
|
1410
|
+
if (typeof pkg.exports === "object" && pkg.exports["."] !== undefined) {
|
|
1411
|
+
const dot = pkg.exports["."];
|
|
1412
|
+
const resolved = typeof dot === "string" ? dot : dot.import || dot.default;
|
|
1413
|
+
if (typeof resolved === "string") {
|
|
1414
|
+
return chooseExisting(path.resolve(pkgRoot, resolved), ...fallbackCandidates);
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
if (typeof pkg.exports === "string") {
|
|
1418
|
+
return chooseExisting(path.resolve(pkgRoot, pkg.exports), ...fallbackCandidates);
|
|
1419
|
+
}
|
|
1420
|
+
if (pkg.main) {
|
|
1421
|
+
return chooseExisting(path.resolve(pkgRoot, pkg.main), ...fallbackCandidates);
|
|
1422
|
+
}
|
|
1423
|
+
return chooseExisting(...fallbackCandidates);
|
|
1424
|
+
}
|
|
1425
|
+
catch (err) {
|
|
1426
|
+
if (err.code === "ENOENT") {
|
|
1427
|
+
return chooseExisting(...fallbackCandidates);
|
|
1428
|
+
}
|
|
1429
|
+
throw err;
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
// ---------------------------------------------------------------------------
|
|
1433
|
+
// Config ā Character mapping
|
|
1434
|
+
// ---------------------------------------------------------------------------
|
|
1435
|
+
/**
|
|
1436
|
+
* Propagate channel credentials from Milady config into process.env so
|
|
1437
|
+
* that elizaOS plugins can find them.
|
|
1438
|
+
*/
|
|
1439
|
+
/** @internal Exported for testing. */
|
|
1440
|
+
export function applyConnectorSecretsToEnv(config) {
|
|
1441
|
+
// Prefer config.connectors, fall back to config.channels for backward compatibility
|
|
1442
|
+
const connectors = config.connectors ?? config.channels ?? {};
|
|
1443
|
+
for (const [channelName, channelConfig] of Object.entries(connectors)) {
|
|
1444
|
+
if (!channelConfig || typeof channelConfig !== "object")
|
|
1445
|
+
continue;
|
|
1446
|
+
const configObj = channelConfig;
|
|
1447
|
+
// Discord plugins in the ecosystem use both DISCORD_API_TOKEN and
|
|
1448
|
+
// DISCORD_BOT_TOKEN across versions. Mirror to both when available.
|
|
1449
|
+
if (channelName === "discord") {
|
|
1450
|
+
const tokenValue = (typeof configObj.token === "string" && configObj.token.trim()) ||
|
|
1451
|
+
(typeof configObj.botToken === "string" && configObj.botToken.trim()) ||
|
|
1452
|
+
"";
|
|
1453
|
+
if (tokenValue) {
|
|
1454
|
+
if (!process.env.DISCORD_API_TOKEN) {
|
|
1455
|
+
process.env.DISCORD_API_TOKEN = tokenValue;
|
|
1456
|
+
}
|
|
1457
|
+
if (!process.env.DISCORD_BOT_TOKEN) {
|
|
1458
|
+
process.env.DISCORD_BOT_TOKEN = tokenValue;
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
const envMap = CHANNEL_ENV_MAP[channelName];
|
|
1463
|
+
if (!envMap)
|
|
1464
|
+
continue;
|
|
1465
|
+
for (const [configField, envKey] of Object.entries(envMap)) {
|
|
1466
|
+
const value = configObj[configField];
|
|
1467
|
+
if (typeof value === "string" && value.trim()) {
|
|
1468
|
+
// Set if unset, or overwrite stale [REDACTED] placeholders
|
|
1469
|
+
const existing = process.env[envKey];
|
|
1470
|
+
if (!existing || existing.startsWith("[REDACT")) {
|
|
1471
|
+
process.env[envKey] = value;
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
/**
|
|
1478
|
+
* Auto-resolve Discord Application ID from the bot token via Discord API.
|
|
1479
|
+
* Called during async runtime init so that users only need a bot token.
|
|
1480
|
+
*/
|
|
1481
|
+
/** @internal Exported for testing. */
|
|
1482
|
+
export async function autoResolveDiscordAppId() {
|
|
1483
|
+
if (process.env.DISCORD_APPLICATION_ID)
|
|
1484
|
+
return;
|
|
1485
|
+
const discordToken = process.env.DISCORD_API_TOKEN || process.env.DISCORD_BOT_TOKEN;
|
|
1486
|
+
if (!discordToken)
|
|
1487
|
+
return;
|
|
1488
|
+
try {
|
|
1489
|
+
const res = await fetch("https://discord.com/api/v10/oauth2/applications/@me", { headers: { Authorization: `Bot ${discordToken}` } });
|
|
1490
|
+
if (!res.ok) {
|
|
1491
|
+
logger.warn(`[milady] Failed to auto-resolve Discord Application ID: ${res.status}`);
|
|
1492
|
+
return;
|
|
1493
|
+
}
|
|
1494
|
+
const app = (await res.json());
|
|
1495
|
+
if (!app.id)
|
|
1496
|
+
return;
|
|
1497
|
+
process.env.DISCORD_APPLICATION_ID = app.id;
|
|
1498
|
+
logger.info(`[milady] Auto-resolved Discord Application ID: ${app.id}`);
|
|
1499
|
+
}
|
|
1500
|
+
catch (err) {
|
|
1501
|
+
logger.warn(`[milady] Could not auto-resolve Discord Application ID: ${err}`);
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
/**
|
|
1505
|
+
* Propagate cloud config from Milady config into process.env so the
|
|
1506
|
+
* ElizaCloud plugin can discover settings at startup.
|
|
1507
|
+
*/
|
|
1508
|
+
/** @internal Exported for testing. */
|
|
1509
|
+
export function applyCloudConfigToEnv(config) {
|
|
1510
|
+
const cloud = config.cloud;
|
|
1511
|
+
if (!cloud)
|
|
1512
|
+
return;
|
|
1513
|
+
const cloudMode = cloud.enabled;
|
|
1514
|
+
// Require explicit cloud.enabled = true. Previously, undefined + apiKey
|
|
1515
|
+
// would count as enabled, causing the model to revert to cloud on restart.
|
|
1516
|
+
const effectivelyEnabled = cloudMode === true;
|
|
1517
|
+
if (effectivelyEnabled) {
|
|
1518
|
+
process.env.ELIZAOS_CLOUD_ENABLED = "true";
|
|
1519
|
+
logger.info(`[milady] Cloud config: enabled=${cloud.enabled}, hasApiKey=${Boolean(cloud.apiKey)}, baseUrl=${cloud.baseUrl ?? "(default)"}`);
|
|
1520
|
+
}
|
|
1521
|
+
else {
|
|
1522
|
+
delete process.env.ELIZAOS_CLOUD_ENABLED;
|
|
1523
|
+
delete process.env.ELIZAOS_CLOUD_SMALL_MODEL;
|
|
1524
|
+
delete process.env.ELIZAOS_CLOUD_LARGE_MODEL;
|
|
1525
|
+
}
|
|
1526
|
+
if (cloud.apiKey) {
|
|
1527
|
+
process.env.ELIZAOS_CLOUD_API_KEY = cloud.apiKey;
|
|
1528
|
+
}
|
|
1529
|
+
else {
|
|
1530
|
+
delete process.env.ELIZAOS_CLOUD_API_KEY;
|
|
1531
|
+
}
|
|
1532
|
+
if (cloud.baseUrl) {
|
|
1533
|
+
process.env.ELIZAOS_CLOUD_BASE_URL = cloud.baseUrl;
|
|
1534
|
+
}
|
|
1535
|
+
else {
|
|
1536
|
+
delete process.env.ELIZAOS_CLOUD_BASE_URL;
|
|
1537
|
+
}
|
|
1538
|
+
// Propagate model names so the cloud plugin picks them up. Falls back to
|
|
1539
|
+
// sensible defaults when cloud is enabled but no explicit selection exists.
|
|
1540
|
+
// Skip when inferenceMode is "byok"/"local" or services.inference is off ā
|
|
1541
|
+
// user's own keys handle models.
|
|
1542
|
+
// If the user chose a subscription provider, treat that as "byok" unless
|
|
1543
|
+
// they explicitly set inferenceMode to "cloud".
|
|
1544
|
+
const hasSubProvider = Boolean(config.agents?.defaults?.subscriptionProvider);
|
|
1545
|
+
const explicitMode = cloud.inferenceMode;
|
|
1546
|
+
const inferenceMode = explicitMode ?? (hasSubProvider ? "byok" : "cloud");
|
|
1547
|
+
const inferenceToggle = cloud.services?.inference ?? true;
|
|
1548
|
+
const cloudDoesInference = inferenceMode === "cloud" && inferenceToggle !== false;
|
|
1549
|
+
const models = config.models;
|
|
1550
|
+
if (effectivelyEnabled && cloudDoesInference) {
|
|
1551
|
+
const small = models?.small || "openai/gpt-5-mini";
|
|
1552
|
+
const large = models?.large || "anthropic/claude-sonnet-4.5";
|
|
1553
|
+
process.env.SMALL_MODEL = small;
|
|
1554
|
+
process.env.LARGE_MODEL = large;
|
|
1555
|
+
process.env.ELIZAOS_CLOUD_SMALL_MODEL = small;
|
|
1556
|
+
process.env.ELIZAOS_CLOUD_LARGE_MODEL = large;
|
|
1557
|
+
}
|
|
1558
|
+
else if (effectivelyEnabled) {
|
|
1559
|
+
// Cloud enabled but inference handled by user's own keys ā clean cloud
|
|
1560
|
+
// model env vars so the cloud plugin doesn't intercept model calls.
|
|
1561
|
+
delete process.env.ELIZAOS_CLOUD_SMALL_MODEL;
|
|
1562
|
+
delete process.env.ELIZAOS_CLOUD_LARGE_MODEL;
|
|
1563
|
+
}
|
|
1564
|
+
// Propagate per-service disable flags so downstream code can check them
|
|
1565
|
+
// without needing direct access to the MiladyConfig object.
|
|
1566
|
+
const services = cloud.services;
|
|
1567
|
+
if (services) {
|
|
1568
|
+
if (services.tts === false) {
|
|
1569
|
+
process.env.MILADY_CLOUD_TTS_DISABLED = "true";
|
|
1570
|
+
}
|
|
1571
|
+
else {
|
|
1572
|
+
delete process.env.MILADY_CLOUD_TTS_DISABLED;
|
|
1573
|
+
}
|
|
1574
|
+
if (services.media === false) {
|
|
1575
|
+
process.env.MILADY_CLOUD_MEDIA_DISABLED = "true";
|
|
1576
|
+
}
|
|
1577
|
+
else {
|
|
1578
|
+
delete process.env.MILADY_CLOUD_MEDIA_DISABLED;
|
|
1579
|
+
}
|
|
1580
|
+
if (services.embeddings === false) {
|
|
1581
|
+
process.env.MILADY_CLOUD_EMBEDDINGS_DISABLED = "true";
|
|
1582
|
+
}
|
|
1583
|
+
else {
|
|
1584
|
+
delete process.env.MILADY_CLOUD_EMBEDDINGS_DISABLED;
|
|
1585
|
+
}
|
|
1586
|
+
if (services.rpc === false) {
|
|
1587
|
+
process.env.MILADY_CLOUD_RPC_DISABLED = "true";
|
|
1588
|
+
}
|
|
1589
|
+
else {
|
|
1590
|
+
delete process.env.MILADY_CLOUD_RPC_DISABLED;
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
/**
|
|
1595
|
+
* Translate `config.database` into the environment variables that
|
|
1596
|
+
* `@elizaos/plugin-sql` reads at init time (`POSTGRES_URL`, `PGLITE_DATA_DIR`).
|
|
1597
|
+
*
|
|
1598
|
+
* When the provider is "postgres", we build a connection string from the
|
|
1599
|
+
* credentials (or use the explicit `connectionString` field) and set
|
|
1600
|
+
* `POSTGRES_URL`. When the provider is "pglite" (the default), we set
|
|
1601
|
+
* `PGLITE_DATA_DIR` to either the configured value or a stable workspace
|
|
1602
|
+
* default (`~/.milady/workspace/.eliza/.elizadb`) and remove any stale
|
|
1603
|
+
* `POSTGRES_URL`.
|
|
1604
|
+
*/
|
|
1605
|
+
/** @internal Exported for testing. */
|
|
1606
|
+
export function applyX402ConfigToEnv(config) {
|
|
1607
|
+
const x402 = config.x402;
|
|
1608
|
+
if (!x402?.enabled)
|
|
1609
|
+
return;
|
|
1610
|
+
if (!process.env.X402_ENABLED)
|
|
1611
|
+
process.env.X402_ENABLED = "true";
|
|
1612
|
+
if (x402.apiKey && !process.env.X402_API_KEY)
|
|
1613
|
+
process.env.X402_API_KEY = x402.apiKey;
|
|
1614
|
+
if (x402.baseUrl && !process.env.X402_BASE_URL)
|
|
1615
|
+
process.env.X402_BASE_URL = x402.baseUrl;
|
|
1616
|
+
}
|
|
1617
|
+
function resolveDefaultPgliteDataDir(config) {
|
|
1618
|
+
const workspaceDir = config.agents?.defaults?.workspace ?? resolveDefaultAgentWorkspaceDir();
|
|
1619
|
+
return path.join(resolveUserPath(workspaceDir), ".eliza", ".elizadb");
|
|
1620
|
+
}
|
|
1621
|
+
/** @internal Exported for testing. */
|
|
1622
|
+
export function applyDatabaseConfigToEnv(config) {
|
|
1623
|
+
const db = config.database;
|
|
1624
|
+
const provider = db?.provider ?? "pglite";
|
|
1625
|
+
if (provider === "postgres" && db?.postgres) {
|
|
1626
|
+
const pg = db.postgres;
|
|
1627
|
+
let url = pg.connectionString;
|
|
1628
|
+
if (!url) {
|
|
1629
|
+
const host = pg.host ?? "localhost";
|
|
1630
|
+
const port = pg.port ?? 5432;
|
|
1631
|
+
const user = encodeURIComponent(pg.user ?? "postgres");
|
|
1632
|
+
const password = pg.password ? encodeURIComponent(pg.password) : "";
|
|
1633
|
+
const database = pg.database ?? "postgres";
|
|
1634
|
+
const auth = password ? `${user}:${password}` : user;
|
|
1635
|
+
const sslParam = pg.ssl ? "?sslmode=require" : "";
|
|
1636
|
+
url = `postgresql://${auth}@${host}:${port}/${database}${sslParam}`;
|
|
1637
|
+
}
|
|
1638
|
+
process.env.POSTGRES_URL = url;
|
|
1639
|
+
// Clear PGLite dir so plugin-sql does not fall back to PGLite
|
|
1640
|
+
delete process.env.PGLITE_DATA_DIR;
|
|
1641
|
+
}
|
|
1642
|
+
else {
|
|
1643
|
+
// PGLite mode (default): ensure no leftover POSTGRES_URL and pin
|
|
1644
|
+
// PGLite to the workspace path unless overridden by config/env.
|
|
1645
|
+
delete process.env.POSTGRES_URL;
|
|
1646
|
+
const configuredDataDir = db?.pglite?.dataDir?.trim();
|
|
1647
|
+
if (configuredDataDir) {
|
|
1648
|
+
process.env.PGLITE_DATA_DIR = resolveUserPath(configuredDataDir);
|
|
1649
|
+
// Fall through to directory creation below instead of returning early
|
|
1650
|
+
}
|
|
1651
|
+
const envDataDir = process.env.PGLITE_DATA_DIR?.trim();
|
|
1652
|
+
if (!envDataDir) {
|
|
1653
|
+
process.env.PGLITE_DATA_DIR = resolveDefaultPgliteDataDir(config);
|
|
1654
|
+
}
|
|
1655
|
+
// Ensure the PGlite data directory exists before init so PGlite does
|
|
1656
|
+
// not silently fall back to in-memory mode on first run.
|
|
1657
|
+
const dataDir = process.env.PGLITE_DATA_DIR;
|
|
1658
|
+
if (dataDir) {
|
|
1659
|
+
const alreadyExisted = existsSync(dataDir);
|
|
1660
|
+
mkdirSync(dataDir, { recursive: true });
|
|
1661
|
+
logger.info(`[milady] PGlite data dir: ${dataDir} (${alreadyExisted ? "existed" : "created"})`);
|
|
1662
|
+
// Remove stale postmaster.pid left by a crashed process. Without this,
|
|
1663
|
+
// PGlite sees the lock and either fails or triggers the destructive
|
|
1664
|
+
// resetPgliteDataDir path, wiping all conversation history.
|
|
1665
|
+
cleanStalePglitePid(dataDir);
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
}
|
|
1669
|
+
function reconcilePglitePidFile(dataDir) {
|
|
1670
|
+
const pidPath = path.join(dataDir, "postmaster.pid");
|
|
1671
|
+
if (!existsSync(pidPath))
|
|
1672
|
+
return "missing";
|
|
1673
|
+
try {
|
|
1674
|
+
const content = readFileSync(pidPath, "utf-8");
|
|
1675
|
+
const firstLine = content.split("\n")[0]?.trim();
|
|
1676
|
+
const pid = parseInt(firstLine, 10);
|
|
1677
|
+
if (Number.isNaN(pid) || pid <= 0) {
|
|
1678
|
+
// Malformed pid file ā remove it
|
|
1679
|
+
unlinkSync(pidPath);
|
|
1680
|
+
logger.warn(`[milady] Removed malformed PGlite postmaster.pid`);
|
|
1681
|
+
return "cleared-malformed";
|
|
1682
|
+
}
|
|
1683
|
+
// Check if the process is still alive
|
|
1684
|
+
try {
|
|
1685
|
+
process.kill(pid, 0); // signal 0 = existence check, doesn't kill
|
|
1686
|
+
// Process exists ā pid file is NOT stale, leave it alone
|
|
1687
|
+
logger.info(`[milady] PGlite postmaster.pid references running process ${pid} ā leaving intact`);
|
|
1688
|
+
return "active";
|
|
1689
|
+
}
|
|
1690
|
+
catch (killErr) {
|
|
1691
|
+
const code = killErr.code;
|
|
1692
|
+
if (code === "ESRCH") {
|
|
1693
|
+
// Process doesn't exist ā stale pid file, safe to remove
|
|
1694
|
+
unlinkSync(pidPath);
|
|
1695
|
+
logger.warn(`[milady] Removed stale PGlite postmaster.pid (process ${pid} not running)`);
|
|
1696
|
+
return "cleared-stale";
|
|
1697
|
+
}
|
|
1698
|
+
else {
|
|
1699
|
+
// EPERM or other ā process may be alive under a different user,
|
|
1700
|
+
// leave the file alone to avoid data directory corruption
|
|
1701
|
+
logger.warn(`[milady] Cannot confirm postmaster.pid staleness (${code}) ā leaving intact`);
|
|
1702
|
+
return "active-unconfirmed";
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
catch (err) {
|
|
1707
|
+
logger.warn(`[milady] Failed to check PGlite postmaster.pid: ${formatError(err)}`);
|
|
1708
|
+
return "check-failed";
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
/**
|
|
1712
|
+
* Check for and remove a stale postmaster.pid in the PGlite data directory.
|
|
1713
|
+
* The pid file is stale if the recorded process is no longer running.
|
|
1714
|
+
*/
|
|
1715
|
+
export function cleanStalePglitePid(dataDir) {
|
|
1716
|
+
void reconcilePglitePidFile(dataDir);
|
|
1717
|
+
}
|
|
1718
|
+
function collectErrorMessages(err) {
|
|
1719
|
+
const messages = [];
|
|
1720
|
+
const seen = new Set();
|
|
1721
|
+
let current = err;
|
|
1722
|
+
while (current && !seen.has(current)) {
|
|
1723
|
+
seen.add(current);
|
|
1724
|
+
if (typeof current === "string") {
|
|
1725
|
+
messages.push(current);
|
|
1726
|
+
break;
|
|
1727
|
+
}
|
|
1728
|
+
if (current instanceof Error) {
|
|
1729
|
+
if (current.message)
|
|
1730
|
+
messages.push(current.message);
|
|
1731
|
+
if (current.stack)
|
|
1732
|
+
messages.push(current.stack);
|
|
1733
|
+
current = current.cause;
|
|
1734
|
+
continue;
|
|
1735
|
+
}
|
|
1736
|
+
if (typeof current === "object") {
|
|
1737
|
+
const maybeErr = current;
|
|
1738
|
+
if (typeof maybeErr.message === "string" && maybeErr.message) {
|
|
1739
|
+
messages.push(maybeErr.message);
|
|
1740
|
+
}
|
|
1741
|
+
if (maybeErr.cause !== undefined) {
|
|
1742
|
+
current = maybeErr.cause;
|
|
1743
|
+
continue;
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
break;
|
|
1747
|
+
}
|
|
1748
|
+
return messages;
|
|
1749
|
+
}
|
|
1750
|
+
function isPgliteLockError(err) {
|
|
1751
|
+
const haystack = collectErrorMessages(err).join("\n").toLowerCase();
|
|
1752
|
+
if (!haystack)
|
|
1753
|
+
return false;
|
|
1754
|
+
const hasPglite = haystack.includes("pglite");
|
|
1755
|
+
const hasSqlite = haystack.includes("sqlite");
|
|
1756
|
+
const hasLockSignal = haystack.includes("database is locked") ||
|
|
1757
|
+
haystack.includes("lock file already exists");
|
|
1758
|
+
return hasLockSignal && (hasPglite || hasSqlite);
|
|
1759
|
+
}
|
|
1760
|
+
/** @internal Exported for testing. */
|
|
1761
|
+
export function isRecoverablePgliteInitError(err) {
|
|
1762
|
+
const haystack = collectErrorMessages(err).join("\n").toLowerCase();
|
|
1763
|
+
if (!haystack)
|
|
1764
|
+
return false;
|
|
1765
|
+
const hasAbort = haystack.includes("aborted(). build with -sassertions");
|
|
1766
|
+
const hasPglite = haystack.includes("pglite");
|
|
1767
|
+
const hasSqlite = haystack.includes("sqlite");
|
|
1768
|
+
const hasMigrationsSchema = haystack.includes("create schema if not exists migrations") ||
|
|
1769
|
+
haystack.includes("failed query: create schema if not exists migrations");
|
|
1770
|
+
const hasRecoverableStorageSignal = [
|
|
1771
|
+
"database disk image is malformed",
|
|
1772
|
+
"file is not a database",
|
|
1773
|
+
"malformed database schema",
|
|
1774
|
+
"database is locked",
|
|
1775
|
+
"lock file already exists",
|
|
1776
|
+
"wal file",
|
|
1777
|
+
"checkpoint failed",
|
|
1778
|
+
"checksum mismatch",
|
|
1779
|
+
"corrupt",
|
|
1780
|
+
].some((needle) => haystack.includes(needle));
|
|
1781
|
+
if (hasMigrationsSchema)
|
|
1782
|
+
return true;
|
|
1783
|
+
if (hasAbort && hasPglite)
|
|
1784
|
+
return true;
|
|
1785
|
+
if (hasRecoverableStorageSignal && (hasPglite || hasSqlite))
|
|
1786
|
+
return true;
|
|
1787
|
+
return false;
|
|
1788
|
+
}
|
|
1789
|
+
/** @internal Exported for testing. */
|
|
1790
|
+
export function getPgliteRecoveryAction(err, dataDir) {
|
|
1791
|
+
if (!isRecoverablePgliteInitError(err))
|
|
1792
|
+
return "none";
|
|
1793
|
+
if (!isPgliteLockError(err))
|
|
1794
|
+
return "reset-data-dir";
|
|
1795
|
+
const pidStatus = reconcilePglitePidFile(dataDir);
|
|
1796
|
+
if (pidStatus === "active" ||
|
|
1797
|
+
pidStatus === "active-unconfirmed" ||
|
|
1798
|
+
pidStatus === "check-failed") {
|
|
1799
|
+
return "fail-active-lock";
|
|
1800
|
+
}
|
|
1801
|
+
if (pidStatus === "cleared-stale" || pidStatus === "cleared-malformed") {
|
|
1802
|
+
return "retry-without-reset";
|
|
1803
|
+
}
|
|
1804
|
+
return "reset-data-dir";
|
|
1805
|
+
}
|
|
1806
|
+
function createActivePgliteLockError(dataDir, err) {
|
|
1807
|
+
return new Error(`PGLite data dir is already in use at ${dataDir}. Close the other Milady process or set a different PGLITE_DATA_DIR before retrying.`, { cause: err });
|
|
1808
|
+
}
|
|
1809
|
+
function resolveActivePgliteDataDir(config) {
|
|
1810
|
+
const provider = config.database?.provider ?? "pglite";
|
|
1811
|
+
if (provider === "postgres")
|
|
1812
|
+
return null;
|
|
1813
|
+
const configured = process.env.PGLITE_DATA_DIR?.trim();
|
|
1814
|
+
const dataDir = configured || resolveDefaultPgliteDataDir(config);
|
|
1815
|
+
return resolveUserPath(dataDir);
|
|
1816
|
+
}
|
|
1817
|
+
async function resetPgliteDataDir(dataDir) {
|
|
1818
|
+
const normalized = path.resolve(dataDir);
|
|
1819
|
+
const root = path.parse(normalized).root;
|
|
1820
|
+
if (normalized === root) {
|
|
1821
|
+
throw new Error(`Refusing to reset unsafe PGLite path: ${normalized}`);
|
|
1822
|
+
}
|
|
1823
|
+
const stamp = new Date()
|
|
1824
|
+
.toISOString()
|
|
1825
|
+
.replace(/[-:]/g, "")
|
|
1826
|
+
.replace(/\..*$/, "")
|
|
1827
|
+
.replace("T", "-");
|
|
1828
|
+
const backupDir = `${normalized}.corrupt-${stamp}`;
|
|
1829
|
+
if (existsSync(normalized)) {
|
|
1830
|
+
try {
|
|
1831
|
+
await fs.rename(normalized, backupDir);
|
|
1832
|
+
logger.warn(`[milady] Backed up existing PGLite data dir to ${backupDir}`);
|
|
1833
|
+
}
|
|
1834
|
+
catch (err) {
|
|
1835
|
+
logger.warn(`[milady] Failed to back up PGLite data dir (${formatError(err)}); deleting ${normalized} instead`);
|
|
1836
|
+
await fs.rm(normalized, { recursive: true, force: true });
|
|
1837
|
+
}
|
|
1838
|
+
}
|
|
1839
|
+
await fs.mkdir(normalized, { recursive: true });
|
|
1840
|
+
}
|
|
1841
|
+
async function initializeDatabaseAdapter(runtime, config) {
|
|
1842
|
+
if (!runtime.adapter || (await runtime.adapter.isReady()))
|
|
1843
|
+
return;
|
|
1844
|
+
try {
|
|
1845
|
+
await runtime.adapter.init();
|
|
1846
|
+
logger.info("[milady] Database adapter initialized early (before plugin inits)");
|
|
1847
|
+
}
|
|
1848
|
+
catch (err) {
|
|
1849
|
+
const pgliteDataDir = resolveActivePgliteDataDir(config);
|
|
1850
|
+
if (!pgliteDataDir) {
|
|
1851
|
+
throw err;
|
|
1852
|
+
}
|
|
1853
|
+
const recoveryAction = getPgliteRecoveryAction(err, pgliteDataDir);
|
|
1854
|
+
if (recoveryAction === "none") {
|
|
1855
|
+
throw err;
|
|
1856
|
+
}
|
|
1857
|
+
if (recoveryAction === "fail-active-lock") {
|
|
1858
|
+
throw createActivePgliteLockError(pgliteDataDir, err);
|
|
1859
|
+
}
|
|
1860
|
+
if (recoveryAction === "retry-without-reset") {
|
|
1861
|
+
logger.warn(`[milady] PGLite init failed (${formatError(err)}). Cleared a stale PGLite lock in ${pgliteDataDir} and retrying without resetting data.`);
|
|
1862
|
+
}
|
|
1863
|
+
else {
|
|
1864
|
+
logger.warn(`[milady] PGLite init failed (${formatError(err)}). Resetting local DB at ${pgliteDataDir} and retrying once.`);
|
|
1865
|
+
await resetPgliteDataDir(pgliteDataDir);
|
|
1866
|
+
process.env.PGLITE_DATA_DIR = pgliteDataDir;
|
|
1867
|
+
}
|
|
1868
|
+
await runtime.adapter.init();
|
|
1869
|
+
logger.info(recoveryAction === "retry-without-reset"
|
|
1870
|
+
? "[milady] Database adapter recovered after clearing a stale PGLite lock"
|
|
1871
|
+
: "[milady] Database adapter recovered after resetting PGLite data");
|
|
1872
|
+
}
|
|
1873
|
+
// Health check: verify PGlite data directory has files after init.
|
|
1874
|
+
// Runs on BOTH the happy path and the recovery path.
|
|
1875
|
+
await verifyPgliteDataDir(config);
|
|
1876
|
+
}
|
|
1877
|
+
/**
|
|
1878
|
+
* Verify PGlite data directory contains files after init.
|
|
1879
|
+
* Warns if the directory is empty (suggests ephemeral/in-memory fallback).
|
|
1880
|
+
*/
|
|
1881
|
+
async function verifyPgliteDataDir(config) {
|
|
1882
|
+
const pgliteDataDir = resolveActivePgliteDataDir(config);
|
|
1883
|
+
if (!pgliteDataDir || !existsSync(pgliteDataDir))
|
|
1884
|
+
return;
|
|
1885
|
+
try {
|
|
1886
|
+
const files = await fs.readdir(pgliteDataDir);
|
|
1887
|
+
logger.info(`[milady] PGlite health check: ${files.length} file(s) in ${pgliteDataDir}`);
|
|
1888
|
+
if (files.length === 0) {
|
|
1889
|
+
logger.warn(`[milady] PGlite data directory is empty after init ā data may not persist across restarts`);
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1892
|
+
catch (err) {
|
|
1893
|
+
logger.warn(`[milady] PGlite health check failed: ${formatError(err)}`);
|
|
1894
|
+
}
|
|
1895
|
+
}
|
|
1896
|
+
function isPluginAlreadyRegisteredError(err) {
|
|
1897
|
+
return formatError(err).toLowerCase().includes("already registered");
|
|
1898
|
+
}
|
|
1899
|
+
function getConstraintName(error) {
|
|
1900
|
+
if (!error || typeof error !== "object")
|
|
1901
|
+
return null;
|
|
1902
|
+
const err = error;
|
|
1903
|
+
if (typeof err.constraint === "string" && err.constraint.length > 0) {
|
|
1904
|
+
return err.constraint;
|
|
1905
|
+
}
|
|
1906
|
+
if (err.cause)
|
|
1907
|
+
return getConstraintName(err.cause);
|
|
1908
|
+
return null;
|
|
1909
|
+
}
|
|
1910
|
+
function isComponentsWorldFkViolation(error) {
|
|
1911
|
+
return getConstraintName(error) === "components_world_id_worlds_id_fk";
|
|
1912
|
+
}
|
|
1913
|
+
function toErrorDetails(error, depth = 0) {
|
|
1914
|
+
if (!error || typeof error !== "object") {
|
|
1915
|
+
return { value: String(error) };
|
|
1916
|
+
}
|
|
1917
|
+
const err = error;
|
|
1918
|
+
const details = {};
|
|
1919
|
+
for (const key of [
|
|
1920
|
+
"name",
|
|
1921
|
+
"message",
|
|
1922
|
+
"code",
|
|
1923
|
+
"detail",
|
|
1924
|
+
"hint",
|
|
1925
|
+
"constraint",
|
|
1926
|
+
"schema",
|
|
1927
|
+
"table",
|
|
1928
|
+
"column",
|
|
1929
|
+
"where",
|
|
1930
|
+
]) {
|
|
1931
|
+
const value = err[key];
|
|
1932
|
+
if (typeof value === "string" || typeof value === "number") {
|
|
1933
|
+
details[key] = value;
|
|
1934
|
+
}
|
|
1935
|
+
}
|
|
1936
|
+
if (depth < 2 && err.cause) {
|
|
1937
|
+
details.cause = toErrorDetails(err.cause, depth + 1);
|
|
1938
|
+
}
|
|
1939
|
+
return details;
|
|
1940
|
+
}
|
|
1941
|
+
async function withEntityCreateMutex(runtimeWithBindings, fn) {
|
|
1942
|
+
const previous = runtimeWithBindings.__miladyEntityCreateMutex;
|
|
1943
|
+
let release = () => { };
|
|
1944
|
+
runtimeWithBindings.__miladyEntityCreateMutex = new Promise((resolve) => {
|
|
1945
|
+
release = resolve;
|
|
1946
|
+
});
|
|
1947
|
+
if (previous) {
|
|
1948
|
+
await previous;
|
|
1949
|
+
}
|
|
1950
|
+
try {
|
|
1951
|
+
return await fn();
|
|
1952
|
+
}
|
|
1953
|
+
finally {
|
|
1954
|
+
release();
|
|
1955
|
+
}
|
|
1956
|
+
}
|
|
1957
|
+
function summarizeComponentWrite(input) {
|
|
1958
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) {
|
|
1959
|
+
return { inputType: typeof input };
|
|
1960
|
+
}
|
|
1961
|
+
const record = input;
|
|
1962
|
+
const data = record.data;
|
|
1963
|
+
const dataKeys = data && typeof data === "object" && !Array.isArray(data)
|
|
1964
|
+
? Object.keys(data).slice(0, 20)
|
|
1965
|
+
: [];
|
|
1966
|
+
return {
|
|
1967
|
+
id: record.id,
|
|
1968
|
+
type: record.type,
|
|
1969
|
+
entityId: record.entityId ?? record.entity_id,
|
|
1970
|
+
sourceEntityId: record.sourceEntityId ?? record.source_entity_id,
|
|
1971
|
+
roomId: record.roomId ?? record.room_id,
|
|
1972
|
+
worldId: record.worldId ?? record.world_id,
|
|
1973
|
+
agentId: record.agentId ?? record.agent_id,
|
|
1974
|
+
dataKeys,
|
|
1975
|
+
};
|
|
1976
|
+
}
|
|
1977
|
+
export function installRuntimeMethodBindings(runtime) {
|
|
1978
|
+
const runtimeWithBindings = runtime;
|
|
1979
|
+
if (runtimeWithBindings.__miladyMethodBindingsInstalled) {
|
|
1980
|
+
return;
|
|
1981
|
+
}
|
|
1982
|
+
// Some plugin builds store this method and invoke it later without the
|
|
1983
|
+
// runtime receiver, which breaks private-field access in AgentRuntime.
|
|
1984
|
+
runtime.getConversationLength = runtime.getConversationLength.bind(runtime);
|
|
1985
|
+
// Wrap getSetting() to fall back to process.env for known keys when the
|
|
1986
|
+
// core returns null. elizaOS core returns null for missing keys, but some
|
|
1987
|
+
// plugins (e.g. @elizaos/plugin-google-genai) check `!== undefined` and
|
|
1988
|
+
// convert null to the string "null", causing API calls like `models/null`.
|
|
1989
|
+
// Scoped to an allowlist to avoid leaking arbitrary env vars to plugins.
|
|
1990
|
+
const GETSETTING_ENV_ALLOWLIST = new Set([
|
|
1991
|
+
// Model provider API keys
|
|
1992
|
+
"ANTHROPIC_API_KEY",
|
|
1993
|
+
"OPENAI_API_KEY",
|
|
1994
|
+
"GOOGLE_GENERATIVE_AI_API_KEY",
|
|
1995
|
+
"GOOGLE_API_KEY",
|
|
1996
|
+
"GEMINI_API_KEY",
|
|
1997
|
+
"GROQ_API_KEY",
|
|
1998
|
+
"XAI_API_KEY",
|
|
1999
|
+
"DEEPSEEK_API_KEY",
|
|
2000
|
+
"OPENROUTER_API_KEY",
|
|
2001
|
+
// Google model defaults
|
|
2002
|
+
"GOOGLE_SMALL_MODEL",
|
|
2003
|
+
"GOOGLE_LARGE_MODEL",
|
|
2004
|
+
// GitHub
|
|
2005
|
+
"GITHUB_TOKEN",
|
|
2006
|
+
"GITHUB_OAUTH_CLIENT_ID",
|
|
2007
|
+
// Coding agent model preferences
|
|
2008
|
+
"PARALLAX_CLAUDE_MODEL_POWERFUL",
|
|
2009
|
+
"PARALLAX_CLAUDE_MODEL_FAST",
|
|
2010
|
+
"PARALLAX_GEMINI_MODEL_POWERFUL",
|
|
2011
|
+
"PARALLAX_GEMINI_MODEL_FAST",
|
|
2012
|
+
"PARALLAX_CODEX_MODEL_POWERFUL",
|
|
2013
|
+
"PARALLAX_CODEX_MODEL_FAST",
|
|
2014
|
+
"PARALLAX_AIDER_PROVIDER",
|
|
2015
|
+
"PARALLAX_AIDER_MODEL_POWERFUL",
|
|
2016
|
+
"PARALLAX_AIDER_MODEL_FAST",
|
|
2017
|
+
// Custom credential forwarding ā intentionally broad: users configure which env vars
|
|
2018
|
+
// to forward to coding agents via this comma-separated key list (e.g. MCP server tokens).
|
|
2019
|
+
"CUSTOM_CREDENTIAL_KEYS",
|
|
2020
|
+
]);
|
|
2021
|
+
const originalGetSetting = runtime.getSetting.bind(runtime);
|
|
2022
|
+
runtime.getSetting = (key) => {
|
|
2023
|
+
const result = originalGetSetting(key);
|
|
2024
|
+
if (result !== null && result !== undefined)
|
|
2025
|
+
return result;
|
|
2026
|
+
if (GETSETTING_ENV_ALLOWLIST.has(key)) {
|
|
2027
|
+
const envVal = process.env[key];
|
|
2028
|
+
if (envVal !== undefined && envVal.trim() !== "")
|
|
2029
|
+
return envVal;
|
|
2030
|
+
}
|
|
2031
|
+
return result;
|
|
2032
|
+
};
|
|
2033
|
+
// Add targeted diagnostics around component writes. Rolodex reflection and
|
|
2034
|
+
// relationship extraction rely heavily on components; when inserts fail,
|
|
2035
|
+
// upstream logs often hide the concrete DB cause/constraint.
|
|
2036
|
+
if (!runtimeWithBindings.__miladyComponentWriteDiagnosticsInstalled) {
|
|
2037
|
+
const runtimeWithComponentWrites = runtime;
|
|
2038
|
+
if (typeof runtimeWithComponentWrites.createComponent === "function") {
|
|
2039
|
+
const originalCreate = runtimeWithComponentWrites.createComponent.bind(runtime);
|
|
2040
|
+
runtimeWithComponentWrites.createComponent = async (input) => {
|
|
2041
|
+
try {
|
|
2042
|
+
return await originalCreate(input);
|
|
2043
|
+
}
|
|
2044
|
+
catch (error) {
|
|
2045
|
+
// Recovery path: some evaluators (e.g. relationship extraction)
|
|
2046
|
+
// compute a synthetic worldId that may not exist yet. If we hit the
|
|
2047
|
+
// components->worlds FK, retry once with the room's canonical worldId.
|
|
2048
|
+
if (isComponentsWorldFkViolation(error) &&
|
|
2049
|
+
input.roomId &&
|
|
2050
|
+
typeof runtime.getRoom === "function") {
|
|
2051
|
+
try {
|
|
2052
|
+
const room = await runtime.getRoom(input.roomId);
|
|
2053
|
+
if (room?.worldId && room.worldId !== input.worldId) {
|
|
2054
|
+
logger.warn(`[milady] createComponent retry with room worldId (${room.worldId}) after FK violation`);
|
|
2055
|
+
const recovered = {
|
|
2056
|
+
...input,
|
|
2057
|
+
worldId: room.worldId,
|
|
2058
|
+
};
|
|
2059
|
+
return await originalCreate(recovered);
|
|
2060
|
+
}
|
|
2061
|
+
}
|
|
2062
|
+
catch (retryLookupError) {
|
|
2063
|
+
logger.warn(`[milady] createComponent recovery lookup failed: ${formatError(retryLookupError)}`);
|
|
2064
|
+
}
|
|
2065
|
+
}
|
|
2066
|
+
const component = summarizeComponentWrite(input);
|
|
2067
|
+
logger.error(`[milady] createComponent failed: ${formatError(error)} | component=${JSON.stringify(component)}`);
|
|
2068
|
+
logger.error(`[milady] createComponent db details: ${JSON.stringify(toErrorDetails(error))}`);
|
|
2069
|
+
throw error;
|
|
2070
|
+
}
|
|
2071
|
+
};
|
|
2072
|
+
}
|
|
2073
|
+
if (typeof runtimeWithComponentWrites.updateComponent === "function") {
|
|
2074
|
+
const originalUpdate = runtimeWithComponentWrites.updateComponent.bind(runtime);
|
|
2075
|
+
runtimeWithComponentWrites.updateComponent = async (input) => {
|
|
2076
|
+
try {
|
|
2077
|
+
return await originalUpdate(input);
|
|
2078
|
+
}
|
|
2079
|
+
catch (error) {
|
|
2080
|
+
const component = summarizeComponentWrite(input);
|
|
2081
|
+
logger.error(`[milady] updateComponent failed: ${formatError(error)} | component=${JSON.stringify(component)}`);
|
|
2082
|
+
logger.error(`[milady] updateComponent db details: ${JSON.stringify(toErrorDetails(error))}`);
|
|
2083
|
+
throw error;
|
|
2084
|
+
}
|
|
2085
|
+
};
|
|
2086
|
+
}
|
|
2087
|
+
runtimeWithBindings.__miladyComponentWriteDiagnosticsInstalled = true;
|
|
2088
|
+
}
|
|
2089
|
+
// Proactive guard for plugin-sql entity creation. Some evaluators may attempt
|
|
2090
|
+
// to create the same entity in rapid succession; plugin-sql's batch insert is
|
|
2091
|
+
// non-idempotent and can fail entire writes on duplicate/conflicting rows.
|
|
2092
|
+
if (!runtimeWithBindings.__miladyEntityWriteDiagnosticsInstalled) {
|
|
2093
|
+
const runtimeWithEntityWrites = runtime;
|
|
2094
|
+
if (typeof runtimeWithEntityWrites.createEntities === "function") {
|
|
2095
|
+
const originalCreateEntities = runtimeWithEntityWrites.createEntities.bind(runtime);
|
|
2096
|
+
runtimeWithEntityWrites.createEntities = async (entities) => {
|
|
2097
|
+
return withEntityCreateMutex(runtimeWithBindings, async () => {
|
|
2098
|
+
const uniqueById = new Map();
|
|
2099
|
+
for (const entity of entities) {
|
|
2100
|
+
if (entity?.id)
|
|
2101
|
+
uniqueById.set(entity.id, entity);
|
|
2102
|
+
}
|
|
2103
|
+
const deduped = Array.from(uniqueById.values());
|
|
2104
|
+
if (deduped.length === 0)
|
|
2105
|
+
return true;
|
|
2106
|
+
let missing = deduped;
|
|
2107
|
+
if (typeof runtimeWithEntityWrites.getEntitiesByIds === "function") {
|
|
2108
|
+
try {
|
|
2109
|
+
const existing = (await runtimeWithEntityWrites.getEntitiesByIds(deduped.map((e) => e.id))) ?? [];
|
|
2110
|
+
const existingIds = new Set();
|
|
2111
|
+
for (const entity of existing) {
|
|
2112
|
+
if (entity?.id)
|
|
2113
|
+
existingIds.add(entity.id);
|
|
2114
|
+
}
|
|
2115
|
+
missing = deduped.filter((entity) => !existingIds.has(entity.id));
|
|
2116
|
+
}
|
|
2117
|
+
catch (err) {
|
|
2118
|
+
logger.warn(`[milady] createEntities precheck failed; proceeding with guarded insert: ${formatError(err)}`);
|
|
2119
|
+
}
|
|
2120
|
+
}
|
|
2121
|
+
if (missing.length === 0)
|
|
2122
|
+
return true;
|
|
2123
|
+
const ok = await originalCreateEntities(missing);
|
|
2124
|
+
if (ok)
|
|
2125
|
+
return true;
|
|
2126
|
+
if (typeof runtimeWithEntityWrites.ensureEntityExists === "function") {
|
|
2127
|
+
let allRecovered = true;
|
|
2128
|
+
for (const entity of missing) {
|
|
2129
|
+
try {
|
|
2130
|
+
const ensured = await runtimeWithEntityWrites.ensureEntityExists(entity);
|
|
2131
|
+
allRecovered = allRecovered && ensured;
|
|
2132
|
+
}
|
|
2133
|
+
catch (err) {
|
|
2134
|
+
allRecovered = false;
|
|
2135
|
+
logger.warn(`[milady] ensureEntityExists recovery failed for ${String(entity.id)}: ${formatError(err)}`);
|
|
2136
|
+
}
|
|
2137
|
+
}
|
|
2138
|
+
if (allRecovered)
|
|
2139
|
+
return true;
|
|
2140
|
+
}
|
|
2141
|
+
logger.warn(`[milady] createEntities unresolved after guarded retries (requested=${entities.length}, deduped=${deduped.length}, missing=${missing.length})`);
|
|
2142
|
+
return false;
|
|
2143
|
+
});
|
|
2144
|
+
};
|
|
2145
|
+
}
|
|
2146
|
+
runtimeWithBindings.__miladyEntityWriteDiagnosticsInstalled = true;
|
|
2147
|
+
}
|
|
2148
|
+
runtimeWithBindings.__miladyMethodBindingsInstalled = true;
|
|
2149
|
+
}
|
|
2150
|
+
function installActionAliases(runtime) {
|
|
2151
|
+
const runtimeWithAliases = runtime;
|
|
2152
|
+
if (runtimeWithAliases.__miladyActionAliasesInstalled) {
|
|
2153
|
+
return;
|
|
2154
|
+
}
|
|
2155
|
+
const actions = Array.isArray(runtimeWithAliases.actions)
|
|
2156
|
+
? runtimeWithAliases.actions
|
|
2157
|
+
: [];
|
|
2158
|
+
// Keep compaction automatic-only; do not allow manual COMPACT_SESSION invokes.
|
|
2159
|
+
const compactSessionIndex = actions.findIndex((action) => action?.name?.toUpperCase() === "COMPACT_SESSION");
|
|
2160
|
+
if (compactSessionIndex !== -1) {
|
|
2161
|
+
actions.splice(compactSessionIndex, 1);
|
|
2162
|
+
logger.info("[milady] Disabled manual COMPACT_SESSION action; auto-compaction remains enabled");
|
|
2163
|
+
}
|
|
2164
|
+
// Compatibility alias: older prompts/docs still reference CODE_TASK,
|
|
2165
|
+
// while plugin-agent-orchestrator exposes CREATE_TASK.
|
|
2166
|
+
const createTaskAction = actions.find((action) => action?.name?.toUpperCase() === "CREATE_TASK");
|
|
2167
|
+
if (createTaskAction) {
|
|
2168
|
+
const similes = Array.isArray(createTaskAction.similes)
|
|
2169
|
+
? createTaskAction.similes
|
|
2170
|
+
: [];
|
|
2171
|
+
const hasCodeTaskAlias = similes.some((simile) => simile.toUpperCase() === "CODE_TASK");
|
|
2172
|
+
if (!hasCodeTaskAlias) {
|
|
2173
|
+
createTaskAction.similes = [...similes, "CODE_TASK"];
|
|
2174
|
+
logger.info("[milady] Added action alias CODE_TASK -> CREATE_TASK for agent-orchestrator");
|
|
2175
|
+
}
|
|
2176
|
+
}
|
|
2177
|
+
runtimeWithAliases.__miladyActionAliasesInstalled = true;
|
|
2178
|
+
}
|
|
2179
|
+
async function registerSqlPluginWithRecovery(runtime, sqlPlugin, config) {
|
|
2180
|
+
let registerError = null;
|
|
2181
|
+
try {
|
|
2182
|
+
await runtime.registerPlugin(sqlPlugin.plugin);
|
|
2183
|
+
}
|
|
2184
|
+
catch (err) {
|
|
2185
|
+
registerError = err;
|
|
2186
|
+
}
|
|
2187
|
+
if (registerError) {
|
|
2188
|
+
const pgliteDataDir = resolveActivePgliteDataDir(config);
|
|
2189
|
+
if (!pgliteDataDir) {
|
|
2190
|
+
throw registerError;
|
|
2191
|
+
}
|
|
2192
|
+
const recoveryAction = getPgliteRecoveryAction(registerError, pgliteDataDir);
|
|
2193
|
+
if (recoveryAction === "none") {
|
|
2194
|
+
throw registerError;
|
|
2195
|
+
}
|
|
2196
|
+
if (recoveryAction === "fail-active-lock") {
|
|
2197
|
+
throw createActivePgliteLockError(pgliteDataDir, registerError);
|
|
2198
|
+
}
|
|
2199
|
+
if (recoveryAction === "retry-without-reset") {
|
|
2200
|
+
logger.warn(`[milady] SQL plugin registration failed (${formatError(registerError)}). Cleared a stale PGLite lock in ${pgliteDataDir} and retrying without resetting data.`);
|
|
2201
|
+
}
|
|
2202
|
+
else {
|
|
2203
|
+
logger.warn(`[milady] SQL plugin registration failed (${formatError(registerError)}). Resetting local PGLite DB at ${pgliteDataDir} and retrying once.`);
|
|
2204
|
+
await resetPgliteDataDir(pgliteDataDir);
|
|
2205
|
+
process.env.PGLITE_DATA_DIR = pgliteDataDir;
|
|
2206
|
+
}
|
|
2207
|
+
try {
|
|
2208
|
+
await runtime.registerPlugin(sqlPlugin.plugin);
|
|
2209
|
+
}
|
|
2210
|
+
catch (retryErr) {
|
|
2211
|
+
if (!isPluginAlreadyRegisteredError(retryErr)) {
|
|
2212
|
+
throw retryErr;
|
|
2213
|
+
}
|
|
2214
|
+
}
|
|
2215
|
+
}
|
|
2216
|
+
await initializeDatabaseAdapter(runtime, config);
|
|
2217
|
+
}
|
|
2218
|
+
/**
|
|
2219
|
+
* Build an elizaOS Character from the Milady config.
|
|
2220
|
+
*
|
|
2221
|
+
* Resolves the agent name from `config.agents.list` (first entry) or
|
|
2222
|
+
* `config.ui.assistant.name`, falling back to "Milady". Character
|
|
2223
|
+
* personality data (bio, system prompt, style, etc.) is stored in the
|
|
2224
|
+
* database ā not the config file ā so we only provide sensible defaults
|
|
2225
|
+
* here for the initial bootstrap.
|
|
2226
|
+
*/
|
|
2227
|
+
/** @internal Exported for testing. */
|
|
2228
|
+
export function buildCharacterFromConfig(config) {
|
|
2229
|
+
// Resolve name: agents list ā ui assistant ā "Milady"
|
|
2230
|
+
const agentEntry = config.agents?.list?.[0];
|
|
2231
|
+
const name = agentEntry?.name ?? config.ui?.assistant?.name ?? "Milady";
|
|
2232
|
+
const bundledPreset = (() => {
|
|
2233
|
+
const presetByName = {
|
|
2234
|
+
Reimu: "uwu~",
|
|
2235
|
+
Marisa: "hell yeah",
|
|
2236
|
+
Yukari: "lol k",
|
|
2237
|
+
Sakuya: "Noted.",
|
|
2238
|
+
Koishi: "hehe~",
|
|
2239
|
+
Remilia: "...",
|
|
2240
|
+
Reisen: "locked in",
|
|
2241
|
+
};
|
|
2242
|
+
const presetCatchphrase = presetByName[name.trim()];
|
|
2243
|
+
if (!presetCatchphrase)
|
|
2244
|
+
return undefined;
|
|
2245
|
+
return STYLE_PRESETS.find((preset) => preset.catchphrase === presetCatchphrase);
|
|
2246
|
+
})();
|
|
2247
|
+
// Read personality fields from the agent config entry (set during
|
|
2248
|
+
// onboarding from the chosen style preset). Fall back to generic
|
|
2249
|
+
// defaults when the preset data is not present (e.g. pre-onboarding
|
|
2250
|
+
// bootstrap or configs created before this change). For built-in default
|
|
2251
|
+
// characters, fall back to the bundled preset so legacy name-only configs
|
|
2252
|
+
// still retain their default posts/messages.
|
|
2253
|
+
const bio = agentEntry?.bio ??
|
|
2254
|
+
bundledPreset?.bio ?? [
|
|
2255
|
+
"{{name}} is an AI assistant powered by Milady and elizaOS.",
|
|
2256
|
+
];
|
|
2257
|
+
const systemPrompt = agentEntry?.system ??
|
|
2258
|
+
bundledPreset?.system ??
|
|
2259
|
+
"You are {{name}}, an autonomous AI agent powered by elizaOS.";
|
|
2260
|
+
const style = agentEntry?.style ?? bundledPreset?.style;
|
|
2261
|
+
const adjectives = agentEntry?.adjectives ?? bundledPreset?.adjectives;
|
|
2262
|
+
const postExamples = agentEntry?.postExamples ?? bundledPreset?.postExamples;
|
|
2263
|
+
const messageExamples = agentEntry?.messageExamples ?? bundledPreset?.messageExamples;
|
|
2264
|
+
// Collect secrets from process.env (API keys the plugins need)
|
|
2265
|
+
const secretKeys = [
|
|
2266
|
+
"ANTHROPIC_API_KEY",
|
|
2267
|
+
"OPENAI_API_KEY",
|
|
2268
|
+
"GEMINI_API_KEY",
|
|
2269
|
+
"GOOGLE_API_KEY",
|
|
2270
|
+
"GOOGLE_GENERATIVE_AI_API_KEY",
|
|
2271
|
+
"GROQ_API_KEY",
|
|
2272
|
+
"XAI_API_KEY",
|
|
2273
|
+
"OPENROUTER_API_KEY",
|
|
2274
|
+
"AI_GATEWAY_API_KEY",
|
|
2275
|
+
"AIGATEWAY_API_KEY",
|
|
2276
|
+
"AI_GATEWAY_BASE_URL",
|
|
2277
|
+
"AI_GATEWAY_SMALL_MODEL",
|
|
2278
|
+
"AI_GATEWAY_LARGE_MODEL",
|
|
2279
|
+
"AI_GATEWAY_EMBEDDING_MODEL",
|
|
2280
|
+
"AI_GATEWAY_EMBEDDING_DIMENSIONS",
|
|
2281
|
+
"AI_GATEWAY_IMAGE_MODEL",
|
|
2282
|
+
"AI_GATEWAY_TIMEOUT_MS",
|
|
2283
|
+
"OLLAMA_BASE_URL",
|
|
2284
|
+
"DISCORD_API_TOKEN",
|
|
2285
|
+
"DISCORD_APPLICATION_ID",
|
|
2286
|
+
"DISCORD_BOT_TOKEN",
|
|
2287
|
+
"TELEGRAM_BOT_TOKEN",
|
|
2288
|
+
"SLACK_BOT_TOKEN",
|
|
2289
|
+
"SLACK_APP_TOKEN",
|
|
2290
|
+
"SLACK_USER_TOKEN",
|
|
2291
|
+
"SIGNAL_ACCOUNT_NUMBER",
|
|
2292
|
+
"MSTEAMS_APP_ID",
|
|
2293
|
+
"MSTEAMS_APP_PASSWORD",
|
|
2294
|
+
"MATTERMOST_BOT_TOKEN",
|
|
2295
|
+
"MATTERMOST_BASE_URL",
|
|
2296
|
+
// ElizaCloud secrets
|
|
2297
|
+
"ELIZAOS_CLOUD_API_KEY",
|
|
2298
|
+
"ELIZAOS_CLOUD_BASE_URL",
|
|
2299
|
+
"ELIZAOS_CLOUD_ENABLED",
|
|
2300
|
+
// Wallet / blockchain secrets
|
|
2301
|
+
"EVM_PRIVATE_KEY",
|
|
2302
|
+
"SOLANA_PRIVATE_KEY",
|
|
2303
|
+
"ALCHEMY_API_KEY",
|
|
2304
|
+
"HELIUS_API_KEY",
|
|
2305
|
+
"BIRDEYE_API_KEY",
|
|
2306
|
+
"SOLANA_RPC_URL",
|
|
2307
|
+
"X402_PRIVATE_KEY",
|
|
2308
|
+
"X402_NETWORK",
|
|
2309
|
+
"X402_PAY_TO",
|
|
2310
|
+
"X402_FACILITATOR_URL",
|
|
2311
|
+
"X402_MAX_PAYMENT_USD",
|
|
2312
|
+
"X402_MAX_TOTAL_USD",
|
|
2313
|
+
"X402_ENABLED",
|
|
2314
|
+
"X402_DB_PATH",
|
|
2315
|
+
// GitHub access for coding agent plugin
|
|
2316
|
+
"GITHUB_TOKEN",
|
|
2317
|
+
"GITHUB_OAUTH_CLIENT_ID",
|
|
2318
|
+
];
|
|
2319
|
+
const secrets = {};
|
|
2320
|
+
for (const key of secretKeys) {
|
|
2321
|
+
const value = process.env[key];
|
|
2322
|
+
if (value?.trim()) {
|
|
2323
|
+
secrets[key] = value;
|
|
2324
|
+
}
|
|
2325
|
+
}
|
|
2326
|
+
// Normalise messageExamples to the {examples: [{name,content}]} shape
|
|
2327
|
+
// that @elizaos/core expects. Config may contain EITHER format:
|
|
2328
|
+
// OLD (preset/onboarding): [[{user, content}, ...], ...]
|
|
2329
|
+
// NEW (@elizaos/core): [{examples: [{name, content}, ...]}, ...]
|
|
2330
|
+
const mappedExamples = messageExamples?.map((item) => {
|
|
2331
|
+
// Already in new format ā pass through
|
|
2332
|
+
if (item &&
|
|
2333
|
+
typeof item === "object" &&
|
|
2334
|
+
"examples" in item) {
|
|
2335
|
+
return item;
|
|
2336
|
+
}
|
|
2337
|
+
// Old format ā array of {user, content} entries
|
|
2338
|
+
const arr = item;
|
|
2339
|
+
return {
|
|
2340
|
+
examples: arr.map((msg) => ({
|
|
2341
|
+
name: msg.name ?? msg.user ?? "",
|
|
2342
|
+
content: msg.content,
|
|
2343
|
+
})),
|
|
2344
|
+
};
|
|
2345
|
+
});
|
|
2346
|
+
return mergeCharacterDefaults({
|
|
2347
|
+
name,
|
|
2348
|
+
bio,
|
|
2349
|
+
system: systemPrompt,
|
|
2350
|
+
...(style ? { style } : {}),
|
|
2351
|
+
...(adjectives ? { adjectives } : {}),
|
|
2352
|
+
...(postExamples ? { postExamples } : {}),
|
|
2353
|
+
...(mappedExamples ? { messageExamples: mappedExamples } : {}),
|
|
2354
|
+
secrets,
|
|
2355
|
+
});
|
|
2356
|
+
}
|
|
2357
|
+
/**
|
|
2358
|
+
* Resolve the primary model identifier from Milady config.
|
|
2359
|
+
*
|
|
2360
|
+
* Milady stores the model under `agents.defaults.model.primary` as an
|
|
2361
|
+
* AgentModelListConfig object. Returns undefined when no model is
|
|
2362
|
+
* explicitly configured (elizaOS falls back to whichever model
|
|
2363
|
+
* plugin is loaded).
|
|
2364
|
+
*/
|
|
2365
|
+
/** @internal Exported for testing. */
|
|
2366
|
+
export function resolvePrimaryModel(config) {
|
|
2367
|
+
const modelConfig = config.agents?.defaults?.model;
|
|
2368
|
+
if (!modelConfig)
|
|
2369
|
+
return undefined;
|
|
2370
|
+
// AgentDefaultsConfig.model is AgentModelListConfig: { primary?, fallbacks? }
|
|
2371
|
+
return modelConfig.primary;
|
|
2372
|
+
}
|
|
2373
|
+
/**
|
|
2374
|
+
* Vision is a heavy optional plugin. When Milady enables it, keep the service
|
|
2375
|
+
* loaded but idle until the user explicitly selects CAMERA, SCREEN, or BOTH.
|
|
2376
|
+
* This avoids background capture loops during normal app startup.
|
|
2377
|
+
*/
|
|
2378
|
+
export function resolveVisionModeSetting(config, env = process.env) {
|
|
2379
|
+
const explicitMode = env.VISION_MODE?.trim();
|
|
2380
|
+
if (explicitMode)
|
|
2381
|
+
return explicitMode;
|
|
2382
|
+
if (config.features?.vision === true)
|
|
2383
|
+
return "OFF";
|
|
2384
|
+
return undefined;
|
|
2385
|
+
}
|
|
2386
|
+
// ---------------------------------------------------------------------------
|
|
2387
|
+
// First-run onboarding
|
|
2388
|
+
// ---------------------------------------------------------------------------
|
|
2389
|
+
// Name pool + random picker shared with the web UI API server.
|
|
2390
|
+
// See src/runtime/onboarding-names.ts for the canonical list.
|
|
2391
|
+
import { pickRandomNames } from "./onboarding-names";
|
|
2392
|
+
// ---------------------------------------------------------------------------
|
|
2393
|
+
// Style presets ā shared between CLI and GUI onboarding
|
|
2394
|
+
// ---------------------------------------------------------------------------
|
|
2395
|
+
import { STYLE_PRESETS } from "../onboarding-presets";
|
|
2396
|
+
/**
|
|
2397
|
+
* Detect whether this is the first run (no agent name configured)
|
|
2398
|
+
* and run the onboarding flow:
|
|
2399
|
+
*
|
|
2400
|
+
* 1. Welcome banner
|
|
2401
|
+
* 2. Name selector (4 random + Custom)
|
|
2402
|
+
* 3. Catchphrase / writing-style selector
|
|
2403
|
+
* 4. Persist agent name to `agents.list[0]` in config
|
|
2404
|
+
*
|
|
2405
|
+
* Character personality (bio, system prompt, style) is stored in the
|
|
2406
|
+
* database at runtime ā only the agent name lives in config.
|
|
2407
|
+
*
|
|
2408
|
+
* Subsequent runs skip this entirely.
|
|
2409
|
+
*/
|
|
2410
|
+
async function runFirstTimeSetup(config) {
|
|
2411
|
+
const agentEntry = config.agents?.list?.[0];
|
|
2412
|
+
const hasName = Boolean(agentEntry?.name || config.ui?.assistant?.name);
|
|
2413
|
+
if (hasName)
|
|
2414
|
+
return config;
|
|
2415
|
+
// Only prompt when stdin is a TTY (interactive terminal)
|
|
2416
|
+
if (!process.stdin.isTTY)
|
|
2417
|
+
return config;
|
|
2418
|
+
// Load @clack/prompts lazily ā only needed for interactive CLI onboarding.
|
|
2419
|
+
const clack = await loadClack();
|
|
2420
|
+
// āā Step 1: Welcome āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
|
|
2421
|
+
clack.intro("WELCOME TO MILADY!");
|
|
2422
|
+
// āā Step 2: Name āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
|
|
2423
|
+
const randomNames = pickRandomNames(4);
|
|
2424
|
+
const nameChoice = await clack.select({
|
|
2425
|
+
message: "ā”ā”miladyā”ā”: Hey there, I'm.... err, what was my name again?",
|
|
2426
|
+
options: [
|
|
2427
|
+
...randomNames.map((n) => ({ value: n, label: n })),
|
|
2428
|
+
{ value: "_custom_", label: "Custom...", hint: "type your own" },
|
|
2429
|
+
],
|
|
2430
|
+
});
|
|
2431
|
+
if (clack.isCancel(nameChoice))
|
|
2432
|
+
cancelOnboarding();
|
|
2433
|
+
let name;
|
|
2434
|
+
if (nameChoice === "_custom_") {
|
|
2435
|
+
const customName = await clack.text({
|
|
2436
|
+
message: "OK, what should I be called?",
|
|
2437
|
+
placeholder: "Milady",
|
|
2438
|
+
});
|
|
2439
|
+
if (clack.isCancel(customName))
|
|
2440
|
+
cancelOnboarding();
|
|
2441
|
+
name = customName.trim() || "Milady";
|
|
2442
|
+
}
|
|
2443
|
+
else {
|
|
2444
|
+
name = nameChoice;
|
|
2445
|
+
}
|
|
2446
|
+
clack.log.message(`ā”ā”${name}ā”ā”: Oh that's right, I'm ${name}!`);
|
|
2447
|
+
// āā Step 3: Catchphrase / writing style āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
|
|
2448
|
+
const styleChoice = await clack.select({
|
|
2449
|
+
message: `${name}: Now... how do I like to talk again?`,
|
|
2450
|
+
options: STYLE_PRESETS.map((preset) => ({
|
|
2451
|
+
value: preset.catchphrase,
|
|
2452
|
+
label: preset.catchphrase,
|
|
2453
|
+
hint: preset.hint,
|
|
2454
|
+
})),
|
|
2455
|
+
});
|
|
2456
|
+
if (clack.isCancel(styleChoice))
|
|
2457
|
+
cancelOnboarding();
|
|
2458
|
+
const chosenTemplate = STYLE_PRESETS.find((p) => p.catchphrase === styleChoice);
|
|
2459
|
+
// āā Step 4: Model provider āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
|
|
2460
|
+
// Skip provider selection in cloud mode ā Eliza Cloud handles inference.
|
|
2461
|
+
// Check whether an API key is already set in the environment (from .env or
|
|
2462
|
+
// shell). If none is found, ask the user to pick a provider and enter a key.
|
|
2463
|
+
const PROVIDER_OPTIONS = [
|
|
2464
|
+
{
|
|
2465
|
+
id: "anthropic",
|
|
2466
|
+
label: "Anthropic (Claude)",
|
|
2467
|
+
envKey: "ANTHROPIC_API_KEY",
|
|
2468
|
+
detectKeys: ["ANTHROPIC_API_KEY"],
|
|
2469
|
+
hint: "sk-ant-...",
|
|
2470
|
+
},
|
|
2471
|
+
{
|
|
2472
|
+
id: "openai",
|
|
2473
|
+
label: "OpenAI (GPT)",
|
|
2474
|
+
envKey: "OPENAI_API_KEY",
|
|
2475
|
+
detectKeys: ["OPENAI_API_KEY"],
|
|
2476
|
+
hint: "sk-...",
|
|
2477
|
+
},
|
|
2478
|
+
{
|
|
2479
|
+
id: "openrouter",
|
|
2480
|
+
label: "OpenRouter",
|
|
2481
|
+
envKey: "OPENROUTER_API_KEY",
|
|
2482
|
+
detectKeys: ["OPENROUTER_API_KEY"],
|
|
2483
|
+
hint: "sk-or-...",
|
|
2484
|
+
},
|
|
2485
|
+
{
|
|
2486
|
+
id: "vercel-ai-gateway",
|
|
2487
|
+
label: "Vercel AI Gateway",
|
|
2488
|
+
envKey: "AI_GATEWAY_API_KEY",
|
|
2489
|
+
detectKeys: ["AI_GATEWAY_API_KEY", "AIGATEWAY_API_KEY"],
|
|
2490
|
+
hint: "aigw_...",
|
|
2491
|
+
},
|
|
2492
|
+
{
|
|
2493
|
+
id: "gemini",
|
|
2494
|
+
label: "Google Gemini",
|
|
2495
|
+
envKey: "GOOGLE_GENERATIVE_AI_API_KEY",
|
|
2496
|
+
detectKeys: [
|
|
2497
|
+
"GOOGLE_GENERATIVE_AI_API_KEY",
|
|
2498
|
+
"GOOGLE_API_KEY",
|
|
2499
|
+
"GEMINI_API_KEY",
|
|
2500
|
+
],
|
|
2501
|
+
hint: "AI...",
|
|
2502
|
+
},
|
|
2503
|
+
{
|
|
2504
|
+
id: "grok",
|
|
2505
|
+
label: "xAI (Grok)",
|
|
2506
|
+
envKey: "XAI_API_KEY",
|
|
2507
|
+
detectKeys: ["XAI_API_KEY"],
|
|
2508
|
+
hint: "xai-...",
|
|
2509
|
+
},
|
|
2510
|
+
{
|
|
2511
|
+
id: "groq",
|
|
2512
|
+
label: "Groq",
|
|
2513
|
+
envKey: "GROQ_API_KEY",
|
|
2514
|
+
detectKeys: ["GROQ_API_KEY"],
|
|
2515
|
+
hint: "gsk_...",
|
|
2516
|
+
},
|
|
2517
|
+
{
|
|
2518
|
+
id: "deepseek",
|
|
2519
|
+
label: "DeepSeek",
|
|
2520
|
+
envKey: "DEEPSEEK_API_KEY",
|
|
2521
|
+
detectKeys: ["DEEPSEEK_API_KEY"],
|
|
2522
|
+
hint: "sk-...",
|
|
2523
|
+
},
|
|
2524
|
+
{
|
|
2525
|
+
id: "mistral",
|
|
2526
|
+
label: "Mistral",
|
|
2527
|
+
envKey: "MISTRAL_API_KEY",
|
|
2528
|
+
detectKeys: ["MISTRAL_API_KEY"],
|
|
2529
|
+
hint: "",
|
|
2530
|
+
},
|
|
2531
|
+
{
|
|
2532
|
+
id: "together",
|
|
2533
|
+
label: "Together AI",
|
|
2534
|
+
envKey: "TOGETHER_API_KEY",
|
|
2535
|
+
detectKeys: ["TOGETHER_API_KEY"],
|
|
2536
|
+
hint: "",
|
|
2537
|
+
},
|
|
2538
|
+
{
|
|
2539
|
+
id: "ollama",
|
|
2540
|
+
label: "Ollama (local, free)",
|
|
2541
|
+
envKey: "OLLAMA_BASE_URL",
|
|
2542
|
+
detectKeys: ["OLLAMA_BASE_URL"],
|
|
2543
|
+
hint: "http://localhost:11434",
|
|
2544
|
+
},
|
|
2545
|
+
];
|
|
2546
|
+
// Detect if any provider key is already configured
|
|
2547
|
+
const detectedProvider = PROVIDER_OPTIONS.find((p) => p.detectKeys.some((key) => process.env[key]?.trim()));
|
|
2548
|
+
let providerEnvKey;
|
|
2549
|
+
let providerApiKey;
|
|
2550
|
+
if (detectedProvider) {
|
|
2551
|
+
clack.log.success(`Found existing ${detectedProvider.label} key in environment (${detectedProvider.envKey})`);
|
|
2552
|
+
}
|
|
2553
|
+
else {
|
|
2554
|
+
const providerChoice = await clack.select({
|
|
2555
|
+
message: `${name}: One more thing ā which AI provider should I use?`,
|
|
2556
|
+
options: [
|
|
2557
|
+
...PROVIDER_OPTIONS.map((p) => ({
|
|
2558
|
+
value: p.id,
|
|
2559
|
+
label: p.label,
|
|
2560
|
+
hint: p.id === "ollama" ? "no API key needed" : undefined,
|
|
2561
|
+
})),
|
|
2562
|
+
{
|
|
2563
|
+
value: "_skip_",
|
|
2564
|
+
label: "Skip for now",
|
|
2565
|
+
hint: "set an API key later via env or config",
|
|
2566
|
+
},
|
|
2567
|
+
],
|
|
2568
|
+
});
|
|
2569
|
+
if (clack.isCancel(providerChoice))
|
|
2570
|
+
cancelOnboarding();
|
|
2571
|
+
if (providerChoice !== "_skip_") {
|
|
2572
|
+
const chosen = PROVIDER_OPTIONS.find((p) => p.id === providerChoice);
|
|
2573
|
+
if (chosen) {
|
|
2574
|
+
providerEnvKey = chosen.envKey;
|
|
2575
|
+
if (chosen.id === "ollama") {
|
|
2576
|
+
// Ollama just needs a base URL, default to localhost
|
|
2577
|
+
const ollamaUrl = await clack.text({
|
|
2578
|
+
message: "Ollama base URL:",
|
|
2579
|
+
placeholder: "http://localhost:11434",
|
|
2580
|
+
defaultValue: "http://localhost:11434",
|
|
2581
|
+
});
|
|
2582
|
+
if (clack.isCancel(ollamaUrl))
|
|
2583
|
+
cancelOnboarding();
|
|
2584
|
+
providerApiKey = ollamaUrl.trim() || "http://localhost:11434";
|
|
2585
|
+
}
|
|
2586
|
+
else {
|
|
2587
|
+
const apiKeyInput = await clack.password({
|
|
2588
|
+
message: `Paste your ${chosen.label} API key:`,
|
|
2589
|
+
});
|
|
2590
|
+
if (clack.isCancel(apiKeyInput))
|
|
2591
|
+
cancelOnboarding();
|
|
2592
|
+
providerApiKey = apiKeyInput.trim();
|
|
2593
|
+
}
|
|
2594
|
+
}
|
|
2595
|
+
}
|
|
2596
|
+
}
|
|
2597
|
+
// āā Step 4b: Embedding model preset āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
|
|
2598
|
+
// (Simplified: always use the standard/reliable model preset. No user choice.)
|
|
2599
|
+
// āā Step 5: Wallet setup āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
|
|
2600
|
+
// Offer to generate or import wallets for EVM and Solana. Keys are
|
|
2601
|
+
// stored in config.env and process.env, making them available to
|
|
2602
|
+
// plugins at runtime.
|
|
2603
|
+
const { generateWalletKeys, importWallet } = await import("../api/wallet");
|
|
2604
|
+
const hasEvmKey = Boolean(process.env.EVM_PRIVATE_KEY?.trim());
|
|
2605
|
+
const hasSolKey = Boolean(process.env.SOLANA_PRIVATE_KEY?.trim());
|
|
2606
|
+
if (!hasEvmKey || !hasSolKey) {
|
|
2607
|
+
const walletAction = await clack.select({
|
|
2608
|
+
message: `${name}: Do you want me to set up crypto wallets? (for trading, NFTs, DeFi)`,
|
|
2609
|
+
options: [
|
|
2610
|
+
{
|
|
2611
|
+
value: "generate",
|
|
2612
|
+
label: "Generate new wallets",
|
|
2613
|
+
hint: "creates fresh EVM + Solana keypairs",
|
|
2614
|
+
},
|
|
2615
|
+
{
|
|
2616
|
+
value: "import",
|
|
2617
|
+
label: "Import existing wallets",
|
|
2618
|
+
hint: "paste your private keys",
|
|
2619
|
+
},
|
|
2620
|
+
{
|
|
2621
|
+
value: "skip",
|
|
2622
|
+
label: "Skip for now",
|
|
2623
|
+
hint: "wallets can be added later",
|
|
2624
|
+
},
|
|
2625
|
+
],
|
|
2626
|
+
});
|
|
2627
|
+
if (clack.isCancel(walletAction))
|
|
2628
|
+
cancelOnboarding();
|
|
2629
|
+
if (walletAction === "generate") {
|
|
2630
|
+
const keys = generateWalletKeys();
|
|
2631
|
+
if (!hasEvmKey) {
|
|
2632
|
+
process.env.EVM_PRIVATE_KEY = keys.evmPrivateKey;
|
|
2633
|
+
clack.log.success(`Generated EVM wallet: ${keys.evmAddress}`);
|
|
2634
|
+
}
|
|
2635
|
+
if (!hasSolKey) {
|
|
2636
|
+
process.env.SOLANA_PRIVATE_KEY = keys.solanaPrivateKey;
|
|
2637
|
+
clack.log.success(`Generated Solana wallet: ${keys.solanaAddress}`);
|
|
2638
|
+
}
|
|
2639
|
+
}
|
|
2640
|
+
else if (walletAction === "import") {
|
|
2641
|
+
// EVM import
|
|
2642
|
+
if (!hasEvmKey) {
|
|
2643
|
+
const evmKeyInput = await clack.password({
|
|
2644
|
+
message: "Paste your EVM private key (0x... hex, or skip):",
|
|
2645
|
+
});
|
|
2646
|
+
if (!clack.isCancel(evmKeyInput) && evmKeyInput.trim()) {
|
|
2647
|
+
const result = importWallet("evm", evmKeyInput.trim());
|
|
2648
|
+
if (result.success) {
|
|
2649
|
+
clack.log.success(`Imported EVM wallet: ${result.address}`);
|
|
2650
|
+
}
|
|
2651
|
+
else {
|
|
2652
|
+
clack.log.warn(`EVM import failed: ${result.error}`);
|
|
2653
|
+
}
|
|
2654
|
+
}
|
|
2655
|
+
}
|
|
2656
|
+
// Solana import
|
|
2657
|
+
if (!hasSolKey) {
|
|
2658
|
+
const solKeyInput = await clack.password({
|
|
2659
|
+
message: "Paste your Solana private key (base58, or skip):",
|
|
2660
|
+
});
|
|
2661
|
+
if (!clack.isCancel(solKeyInput) && solKeyInput.trim()) {
|
|
2662
|
+
const result = importWallet("solana", solKeyInput.trim());
|
|
2663
|
+
if (result.success) {
|
|
2664
|
+
clack.log.success(`Imported Solana wallet: ${result.address}`);
|
|
2665
|
+
}
|
|
2666
|
+
else {
|
|
2667
|
+
clack.log.warn(`Solana import failed: ${result.error}`);
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
2670
|
+
}
|
|
2671
|
+
}
|
|
2672
|
+
// "skip" ā do nothing
|
|
2673
|
+
}
|
|
2674
|
+
// āā Step 6: Skills Registry (ClawHub default) āāāāāāāāāāāāāāāāāāāāāāāāāā
|
|
2675
|
+
const hasSkillsRegistry = Boolean(process.env.SKILLS_REGISTRY?.trim() || process.env.CLAWHUB_REGISTRY?.trim());
|
|
2676
|
+
const hasSkillsmpKey = Boolean(process.env.SKILLSMP_API_KEY?.trim());
|
|
2677
|
+
if (!hasSkillsRegistry) {
|
|
2678
|
+
process.env.SKILLS_REGISTRY = "https://clawhub.ai";
|
|
2679
|
+
}
|
|
2680
|
+
// āā Step 7: GitHub access (for coding agents, issue management) āāāāāāāāā
|
|
2681
|
+
const hasGithubToken = Boolean(process.env.GITHUB_TOKEN?.trim());
|
|
2682
|
+
const hasGithubOAuth = Boolean(process.env.GITHUB_OAUTH_CLIENT_ID?.trim());
|
|
2683
|
+
if (!hasGithubToken) {
|
|
2684
|
+
const options = [
|
|
2685
|
+
{ value: "skip", label: "Skip for now", hint: "you can add this later" },
|
|
2686
|
+
{
|
|
2687
|
+
value: "pat",
|
|
2688
|
+
label: "Paste a Personal Access Token",
|
|
2689
|
+
hint: "github.com/settings/tokens",
|
|
2690
|
+
},
|
|
2691
|
+
];
|
|
2692
|
+
if (hasGithubOAuth) {
|
|
2693
|
+
options.push({
|
|
2694
|
+
value: "oauth",
|
|
2695
|
+
label: "Use OAuth (authorize in browser)",
|
|
2696
|
+
hint: "recommended",
|
|
2697
|
+
});
|
|
2698
|
+
}
|
|
2699
|
+
const githubChoice = await clack.select({
|
|
2700
|
+
message: "Configure GitHub access? (needed for coding agents, issue management, PRs)",
|
|
2701
|
+
options,
|
|
2702
|
+
});
|
|
2703
|
+
if (!clack.isCancel(githubChoice) && githubChoice === "pat") {
|
|
2704
|
+
const tokenInput = await clack.password({
|
|
2705
|
+
message: "Paste your GitHub token (or skip):",
|
|
2706
|
+
});
|
|
2707
|
+
if (!clack.isCancel(tokenInput) && tokenInput.trim()) {
|
|
2708
|
+
process.env.GITHUB_TOKEN = tokenInput.trim();
|
|
2709
|
+
clack.log.success("GitHub token configured.");
|
|
2710
|
+
}
|
|
2711
|
+
}
|
|
2712
|
+
else if (!clack.isCancel(githubChoice) && githubChoice === "oauth") {
|
|
2713
|
+
clack.log.info("GitHub OAuth will activate when coding agents need access.");
|
|
2714
|
+
}
|
|
2715
|
+
}
|
|
2716
|
+
// āā Step 8: Persist agent + style + provider + embedding config āāāāāāāāā
|
|
2717
|
+
// Save the agent name and chosen personality template into config so that
|
|
2718
|
+
// the same character data is used regardless of whether the user onboarded
|
|
2719
|
+
// via CLI or GUI. This ensures full parity between onboarding surfaces.
|
|
2720
|
+
const existingList = config.agents?.list ?? [];
|
|
2721
|
+
const mainEntry = existingList[0] ?? {
|
|
2722
|
+
id: "main",
|
|
2723
|
+
default: true,
|
|
2724
|
+
};
|
|
2725
|
+
const agentConfigEntry = { ...mainEntry, name };
|
|
2726
|
+
// Apply the chosen style template to the agent config entry so the
|
|
2727
|
+
// personality is persisted ā not just the name.
|
|
2728
|
+
if (chosenTemplate) {
|
|
2729
|
+
agentConfigEntry.bio = chosenTemplate.bio;
|
|
2730
|
+
agentConfigEntry.system = chosenTemplate.system;
|
|
2731
|
+
agentConfigEntry.style = chosenTemplate.style;
|
|
2732
|
+
agentConfigEntry.adjectives = chosenTemplate.adjectives;
|
|
2733
|
+
agentConfigEntry.postExamples = chosenTemplate.postExamples;
|
|
2734
|
+
agentConfigEntry.messageExamples = chosenTemplate.messageExamples;
|
|
2735
|
+
}
|
|
2736
|
+
const updatedList = [
|
|
2737
|
+
agentConfigEntry,
|
|
2738
|
+
...existingList.slice(1),
|
|
2739
|
+
];
|
|
2740
|
+
const updated = {
|
|
2741
|
+
...config,
|
|
2742
|
+
agents: {
|
|
2743
|
+
...config.agents,
|
|
2744
|
+
list: updatedList,
|
|
2745
|
+
},
|
|
2746
|
+
};
|
|
2747
|
+
// Persist the provider API key and wallet keys in config.env so they
|
|
2748
|
+
// survive restarts. Initialise the env bucket once to avoid the
|
|
2749
|
+
// repeated `if (!updated.env)` pattern.
|
|
2750
|
+
if (!updated.env)
|
|
2751
|
+
updated.env = {};
|
|
2752
|
+
const envBucket = updated.env;
|
|
2753
|
+
if (providerEnvKey && providerApiKey) {
|
|
2754
|
+
envBucket[providerEnvKey] = providerApiKey;
|
|
2755
|
+
// Also set immediately in process.env for the current run
|
|
2756
|
+
process.env[providerEnvKey] = providerApiKey;
|
|
2757
|
+
}
|
|
2758
|
+
if (process.env.EVM_PRIVATE_KEY && !hasEvmKey) {
|
|
2759
|
+
envBucket.EVM_PRIVATE_KEY = process.env.EVM_PRIVATE_KEY;
|
|
2760
|
+
}
|
|
2761
|
+
if (process.env.SOLANA_PRIVATE_KEY && !hasSolKey) {
|
|
2762
|
+
envBucket.SOLANA_PRIVATE_KEY = process.env.SOLANA_PRIVATE_KEY;
|
|
2763
|
+
}
|
|
2764
|
+
if (process.env.SKILLS_REGISTRY && !hasSkillsRegistry) {
|
|
2765
|
+
envBucket.SKILLS_REGISTRY = process.env.SKILLS_REGISTRY;
|
|
2766
|
+
}
|
|
2767
|
+
if (process.env.SKILLSMP_API_KEY && !hasSkillsmpKey) {
|
|
2768
|
+
envBucket.SKILLSMP_API_KEY = process.env.SKILLSMP_API_KEY;
|
|
2769
|
+
}
|
|
2770
|
+
if (process.env.GITHUB_TOKEN && !hasGithubToken) {
|
|
2771
|
+
envBucket.GITHUB_TOKEN = process.env.GITHUB_TOKEN;
|
|
2772
|
+
}
|
|
2773
|
+
if (process.env.GITHUB_OAUTH_CLIENT_ID && !hasGithubOAuth) {
|
|
2774
|
+
envBucket.GITHUB_OAUTH_CLIENT_ID = process.env.GITHUB_OAUTH_CLIENT_ID;
|
|
2775
|
+
}
|
|
2776
|
+
try {
|
|
2777
|
+
saveMiladyConfig(updated);
|
|
2778
|
+
}
|
|
2779
|
+
catch (err) {
|
|
2780
|
+
// Non-fatal: the agent can still start, but choices won't persist.
|
|
2781
|
+
clack.log.warn(`Could not save config: ${formatError(err)}`);
|
|
2782
|
+
}
|
|
2783
|
+
clack.log.message(`${name}: ${styleChoice} Alright, that's me.`);
|
|
2784
|
+
clack.outro("Let's get started!");
|
|
2785
|
+
return updated;
|
|
2786
|
+
}
|
|
2787
|
+
/**
|
|
2788
|
+
* Boot the elizaOS runtime without starting the readline chat loop.
|
|
2789
|
+
*
|
|
2790
|
+
* This is a convenience wrapper around {@link startEliza} in headless mode,
|
|
2791
|
+
* with optional config guards.
|
|
2792
|
+
*/
|
|
2793
|
+
export async function bootElizaRuntime(opts = {}) {
|
|
2794
|
+
if (opts.requireConfig && !configFileExists()) {
|
|
2795
|
+
throw new Error("No config found. Run `milady start` once to complete setup.");
|
|
2796
|
+
}
|
|
2797
|
+
const runtime = await startEliza({ headless: true });
|
|
2798
|
+
if (!runtime) {
|
|
2799
|
+
throw new Error("Failed to boot runtime");
|
|
2800
|
+
}
|
|
2801
|
+
return runtime;
|
|
2802
|
+
}
|
|
2803
|
+
const LEVEL_TO_NAME = {
|
|
2804
|
+
10: "trace",
|
|
2805
|
+
20: "debug",
|
|
2806
|
+
27: "success",
|
|
2807
|
+
28: "progress",
|
|
2808
|
+
29: "log",
|
|
2809
|
+
30: "info",
|
|
2810
|
+
40: "warn",
|
|
2811
|
+
50: "error",
|
|
2812
|
+
60: "fatal",
|
|
2813
|
+
};
|
|
2814
|
+
export const logToChatListener = (entry) => {
|
|
2815
|
+
if (entry.roomId && entry.runtime) {
|
|
2816
|
+
const runtime = entry.runtime;
|
|
2817
|
+
// access dynamic property
|
|
2818
|
+
const overrides = runtime.logLevelOverrides;
|
|
2819
|
+
const overrideLevel = overrides?.get(String(entry.roomId));
|
|
2820
|
+
if (overrideLevel) {
|
|
2821
|
+
const levelKey = entry.level;
|
|
2822
|
+
const levelName = (levelKey && LEVEL_TO_NAME[levelKey] ? LEVEL_TO_NAME[levelKey] : "log").toUpperCase();
|
|
2823
|
+
const prefix = `[${levelName}]`;
|
|
2824
|
+
const content = `${prefix} ${entry.msg}`;
|
|
2825
|
+
// Prevent infinite loops by suppressing logs from this action
|
|
2826
|
+
runtime
|
|
2827
|
+
.sendMessageToTarget({ roomId: entry.roomId }, {
|
|
2828
|
+
text: `\`\`\`\n${content}\n\`\`\``,
|
|
2829
|
+
source: "system",
|
|
2830
|
+
isLog: "true",
|
|
2831
|
+
})
|
|
2832
|
+
.catch(() => { });
|
|
2833
|
+
}
|
|
2834
|
+
}
|
|
2835
|
+
};
|
|
2836
|
+
/**
|
|
2837
|
+
* Start the elizaOS runtime with Milady's configuration.
|
|
2838
|
+
*
|
|
2839
|
+
* In headless mode the runtime is returned instead of entering the
|
|
2840
|
+
* interactive readline loop.
|
|
2841
|
+
*/
|
|
2842
|
+
export async function startEliza(opts) {
|
|
2843
|
+
// Start buffering logs early so startup messages appear in the UI log viewer
|
|
2844
|
+
const { captureEarlyLogs } = await import("../api/early-logs");
|
|
2845
|
+
captureEarlyLogs();
|
|
2846
|
+
// Register log listener for chat mirroring
|
|
2847
|
+
addLogListener(logToChatListener);
|
|
2848
|
+
// 1. Load Milady config from ~/.milady/milady.json
|
|
2849
|
+
let config;
|
|
2850
|
+
try {
|
|
2851
|
+
config = loadMiladyConfig();
|
|
2852
|
+
}
|
|
2853
|
+
catch (err) {
|
|
2854
|
+
if (err.code === "ENOENT") {
|
|
2855
|
+
logger.warn("[milady] No config found, using defaults");
|
|
2856
|
+
// All MiladyConfig fields are optional, so an empty object is
|
|
2857
|
+
// structurally valid. The `as` cast is safe here.
|
|
2858
|
+
config = {};
|
|
2859
|
+
}
|
|
2860
|
+
else {
|
|
2861
|
+
throw err;
|
|
2862
|
+
}
|
|
2863
|
+
}
|
|
2864
|
+
// 1b. First-run onboarding ā ask for agent name if not configured.
|
|
2865
|
+
// In headless mode (GUI) the onboarding is handled by the web UI,
|
|
2866
|
+
// so we skip the interactive CLI prompt and let the runtime start
|
|
2867
|
+
// with defaults. The GUI will restart the agent after onboarding.
|
|
2868
|
+
if (!opts?.headless) {
|
|
2869
|
+
config = await runFirstTimeSetup(config);
|
|
2870
|
+
}
|
|
2871
|
+
// 1c. Apply logging level from config to process.env so the global
|
|
2872
|
+
// @elizaos/core logger (used by plugins) respects it.
|
|
2873
|
+
// config.logging.level is guaranteed to be set (defaults to "error").
|
|
2874
|
+
// Users can still opt into noisy logs via config.logging.level or
|
|
2875
|
+
// an explicit LOG_LEVEL environment variable.
|
|
2876
|
+
if (!process.env.LOG_LEVEL) {
|
|
2877
|
+
process.env.LOG_LEVEL = config.logging?.level ?? "error";
|
|
2878
|
+
}
|
|
2879
|
+
// 2. Push channel secrets into process.env for plugin discovery
|
|
2880
|
+
applyConnectorSecretsToEnv(config);
|
|
2881
|
+
await autoResolveDiscordAppId();
|
|
2882
|
+
// 2b. Propagate cloud config into process.env for ElizaCloud plugin
|
|
2883
|
+
applyCloudConfigToEnv(config);
|
|
2884
|
+
// 2c. Propagate x402 config into process.env
|
|
2885
|
+
applyX402ConfigToEnv(config);
|
|
2886
|
+
// 2d. Propagate database config into process.env for plugin-sql
|
|
2887
|
+
applyDatabaseConfigToEnv(config);
|
|
2888
|
+
// 2e. Propagate arbitrary env vars from config.env into process.env.
|
|
2889
|
+
// Milady stores user-defined env vars (plugin settings, API URLs, etc.)
|
|
2890
|
+
// in config.env; elizaOS plugins read them via process.env / getSetting.
|
|
2891
|
+
if (config.env &&
|
|
2892
|
+
typeof config.env === "object" &&
|
|
2893
|
+
!Array.isArray(config.env)) {
|
|
2894
|
+
for (const [key, value] of Object.entries(config.env)) {
|
|
2895
|
+
if (typeof value === "string" && !process.env[key]) {
|
|
2896
|
+
process.env[key] = value;
|
|
2897
|
+
}
|
|
2898
|
+
}
|
|
2899
|
+
}
|
|
2900
|
+
// Log active database configuration for debugging persistence issues
|
|
2901
|
+
{
|
|
2902
|
+
const dbProvider = config.database?.provider ?? "pglite";
|
|
2903
|
+
const pgliteDir = process.env.PGLITE_DATA_DIR;
|
|
2904
|
+
const postgresUrl = process.env.POSTGRES_URL;
|
|
2905
|
+
logger.info(`[milady] Database provider: ${dbProvider}` +
|
|
2906
|
+
(dbProvider === "pglite" && pgliteDir
|
|
2907
|
+
? ` | data dir: ${pgliteDir}`
|
|
2908
|
+
: "") +
|
|
2909
|
+
(dbProvider === "postgres" && postgresUrl
|
|
2910
|
+
? ` | connection: ${postgresUrl.replace(/:\/\/([^:]+):([^@]+)@/, "://$1:***@")}`
|
|
2911
|
+
: ""));
|
|
2912
|
+
}
|
|
2913
|
+
// 2d-iii. OG tracking code initialization
|
|
2914
|
+
try {
|
|
2915
|
+
const { initializeOGCode } = await import("../api/og-tracker");
|
|
2916
|
+
initializeOGCode();
|
|
2917
|
+
}
|
|
2918
|
+
catch {
|
|
2919
|
+
// Silent ā OG tracking is non-critical
|
|
2920
|
+
}
|
|
2921
|
+
// 2d-ii. Allow destructive migrations (e.g. dropping tables removed between
|
|
2922
|
+
// plugin versions) so the runtime doesn't silently stall. Without this
|
|
2923
|
+
// the migration system throws an error that gets swallowed, leaving the
|
|
2924
|
+
// app hanging indefinitely with no output.
|
|
2925
|
+
if (!process.env.ELIZA_ALLOW_DESTRUCTIVE_MIGRATIONS) {
|
|
2926
|
+
process.env.ELIZA_ALLOW_DESTRUCTIVE_MIGRATIONS = "true";
|
|
2927
|
+
}
|
|
2928
|
+
// 2e. Prevent @elizaos/core from auto-loading @elizaos/plugin-bootstrap.
|
|
2929
|
+
// Milady uses @elizaos/plugin-trust which provides the settings/roles
|
|
2930
|
+
// providers and actions. plugin-bootstrap (v1.x) is incompatible with
|
|
2931
|
+
// the 2.0.0-alpha.x runtime used here.
|
|
2932
|
+
if (!process.env.IGNORE_BOOTSTRAP) {
|
|
2933
|
+
process.env.IGNORE_BOOTSTRAP = "true";
|
|
2934
|
+
}
|
|
2935
|
+
// 2e-ii. Ensure SECRET_SALT is set to suppress the @elizaos/core default
|
|
2936
|
+
// warning and avoid using a predictable value in production.
|
|
2937
|
+
if (!process.env.SECRET_SALT) {
|
|
2938
|
+
process.env.SECRET_SALT = crypto.randomBytes(32).toString("hex");
|
|
2939
|
+
logger.info("[milady] Generated random SECRET_SALT for this session");
|
|
2940
|
+
}
|
|
2941
|
+
// 2e-iii. Pre-flight validation for Google AI API keys. If the key looks
|
|
2942
|
+
// obviously invalid (too short, placeholder, wrong prefix), clear it
|
|
2943
|
+
// to prevent plugin-google-genai from making a failing API call.
|
|
2944
|
+
for (const gkey of [
|
|
2945
|
+
"GEMINI_API_KEY",
|
|
2946
|
+
"GOOGLE_API_KEY",
|
|
2947
|
+
"GOOGLE_GENERATIVE_AI_API_KEY",
|
|
2948
|
+
]) {
|
|
2949
|
+
const val = process.env[gkey]?.trim();
|
|
2950
|
+
if (val &&
|
|
2951
|
+
(val.length < 20 || val === "your-key-here" || val.startsWith("sk-"))) {
|
|
2952
|
+
logger.warn(`[milady] ${gkey} appears invalid (length/format), clearing to skip Google AI plugin`);
|
|
2953
|
+
delete process.env[gkey];
|
|
2954
|
+
}
|
|
2955
|
+
}
|
|
2956
|
+
// 2f. Apply subscription-based credentials (Claude Max, Codex Max)
|
|
2957
|
+
try {
|
|
2958
|
+
const { applySubscriptionCredentials } = await import("../auth/index");
|
|
2959
|
+
await applySubscriptionCredentials(config);
|
|
2960
|
+
}
|
|
2961
|
+
catch (err) {
|
|
2962
|
+
logger.warn(`[milady] Failed to apply subscription credentials: ${err}`);
|
|
2963
|
+
}
|
|
2964
|
+
// 3. Build elizaOS Character from Milady config
|
|
2965
|
+
const character = buildCharacterFromConfig(config);
|
|
2966
|
+
const primaryModel = resolvePrimaryModel(config);
|
|
2967
|
+
// 4. Ensure workspace exists with bootstrap files
|
|
2968
|
+
const workspaceDir = config.agents?.defaults?.workspace ?? resolveDefaultAgentWorkspaceDir();
|
|
2969
|
+
await ensureAgentWorkspace({ dir: workspaceDir, ensureBootstrapFiles: true });
|
|
2970
|
+
// 4b. Ensure custom plugins directory exists for drop-in plugins
|
|
2971
|
+
await fs.mkdir(path.join(resolveStateDir(), CUSTOM_PLUGINS_DIRNAME), {
|
|
2972
|
+
recursive: true,
|
|
2973
|
+
});
|
|
2974
|
+
// 5. Create the Milady bridge plugin (workspace context + session keys + compaction)
|
|
2975
|
+
const agentId = character.name?.toLowerCase().replace(/\s+/g, "-") ?? "main";
|
|
2976
|
+
const miladyPlugin = createAutonomousPlugin({
|
|
2977
|
+
workspaceDir,
|
|
2978
|
+
bootstrapMaxChars: config.agents?.defaults?.bootstrapMaxChars,
|
|
2979
|
+
agentId,
|
|
2980
|
+
});
|
|
2981
|
+
// 6. Resolve and load plugins
|
|
2982
|
+
// In headless (GUI) mode before onboarding, the user hasn't configured a
|
|
2983
|
+
// provider yet. Downgrade diagnostics so the expected "no AI provider"
|
|
2984
|
+
// state doesn't appear as a scary Error in the terminal.
|
|
2985
|
+
const preOnboarding = opts?.headless && !config.agents;
|
|
2986
|
+
const resolvedPlugins = await resolvePlugins(config, {
|
|
2987
|
+
quiet: preOnboarding,
|
|
2988
|
+
});
|
|
2989
|
+
if (resolvedPlugins.length === 0) {
|
|
2990
|
+
if (preOnboarding) {
|
|
2991
|
+
logger.info("[milady] No plugins loaded yet ā the onboarding wizard will configure a model provider");
|
|
2992
|
+
}
|
|
2993
|
+
else {
|
|
2994
|
+
logger.error("[milady] No plugins loaded ā at least one model provider plugin is required");
|
|
2995
|
+
logger.error("[milady] Set an API key (e.g. ANTHROPIC_API_KEY, OPENAI_API_KEY) in your environment");
|
|
2996
|
+
throw new Error("No plugins loaded");
|
|
2997
|
+
}
|
|
2998
|
+
}
|
|
2999
|
+
// 6b. Debug logging ā print full context after provider + plugin resolution
|
|
3000
|
+
{
|
|
3001
|
+
const pluginNames = resolvedPlugins.map((p) => p.name);
|
|
3002
|
+
const providerNames = resolvedPlugins
|
|
3003
|
+
.flatMap((p) => p.plugin.providers ?? [])
|
|
3004
|
+
.map((prov) => prov.name);
|
|
3005
|
+
// Build a context summary for validation
|
|
3006
|
+
const contextSummary = {
|
|
3007
|
+
agentName: character.name,
|
|
3008
|
+
pluginCount: resolvedPlugins.length,
|
|
3009
|
+
providerCount: providerNames.length,
|
|
3010
|
+
primaryModel: primaryModel ?? "(auto-detect)",
|
|
3011
|
+
workspaceDir,
|
|
3012
|
+
};
|
|
3013
|
+
debugLogResolvedContext(pluginNames, providerNames, contextSummary, (msg) => logger.debug(msg));
|
|
3014
|
+
// Validate the context and surface issues early
|
|
3015
|
+
const contextValidation = validateRuntimeContext(contextSummary);
|
|
3016
|
+
if (!contextValidation.valid) {
|
|
3017
|
+
const issues = [];
|
|
3018
|
+
if (contextValidation.nullFields.length > 0) {
|
|
3019
|
+
issues.push(`null: ${contextValidation.nullFields.join(", ")}`);
|
|
3020
|
+
}
|
|
3021
|
+
if (contextValidation.undefinedFields.length > 0) {
|
|
3022
|
+
issues.push(`undefined: ${contextValidation.undefinedFields.join(", ")}`);
|
|
3023
|
+
}
|
|
3024
|
+
if (contextValidation.emptyFields.length > 0) {
|
|
3025
|
+
issues.push(`empty: ${contextValidation.emptyFields.join(", ")}`);
|
|
3026
|
+
}
|
|
3027
|
+
logger.warn(`[milady] Context validation issues detected: ${issues.join("; ")}`);
|
|
3028
|
+
}
|
|
3029
|
+
}
|
|
3030
|
+
// 7. Create the AgentRuntime with Milady plugin + resolved plugins
|
|
3031
|
+
// All CORE_PLUGINS are pre-registered sequentially (in CORE_PLUGINS
|
|
3032
|
+
// order) before runtime.initialize() so that cross-plugin getService()
|
|
3033
|
+
// calls always resolve. runtime.initialize() registers remaining
|
|
3034
|
+
// characterPlugins (connectors, providers, custom) in parallel ā those
|
|
3035
|
+
// are NOT core and don't have ordering dependencies.
|
|
3036
|
+
const PREREGISTER_PLUGINS = new Set(CORE_PLUGINS);
|
|
3037
|
+
const sqlPlugin = resolvedPlugins.find((p) => p.name === "@elizaos/plugin-sql");
|
|
3038
|
+
const localEmbeddingPlugin = resolvedPlugins.find((p) => p.name === "@elizaos/plugin-local-embedding");
|
|
3039
|
+
const otherPlugins = resolvedPlugins.filter((p) => !PREREGISTER_PLUGINS.has(p.name));
|
|
3040
|
+
// Resolve the runtime log level from config (AgentRuntime doesn't support
|
|
3041
|
+
// "silent", so we map it to "fatal" as the quietest supported level).
|
|
3042
|
+
const runtimeLogLevel = (() => {
|
|
3043
|
+
// process.env.LOG_LEVEL is already resolved (set explicitly or from
|
|
3044
|
+
// config.logging.level above), so prefer it to honour the dev-mode
|
|
3045
|
+
// LOG_LEVEL=error override set by scripts/dev-ui.mjs.
|
|
3046
|
+
const lvl = process.env.LOG_LEVEL ?? config.logging?.level ?? "error";
|
|
3047
|
+
if (lvl === "silent")
|
|
3048
|
+
return "fatal";
|
|
3049
|
+
return lvl;
|
|
3050
|
+
})();
|
|
3051
|
+
// 7a. Resolve bundled skills directory from @elizaos/skills so
|
|
3052
|
+
// plugin-agent-skills auto-loads them on startup.
|
|
3053
|
+
let bundledSkillsDir = null;
|
|
3054
|
+
try {
|
|
3055
|
+
const { getSkillsDir } = (await import("@elizaos/skills"));
|
|
3056
|
+
bundledSkillsDir = getSkillsDir();
|
|
3057
|
+
logger.info(`[milady] Bundled skills dir: ${bundledSkillsDir}`);
|
|
3058
|
+
}
|
|
3059
|
+
catch {
|
|
3060
|
+
logger.debug("[milady] @elizaos/skills not available ā bundled skills will not be loaded");
|
|
3061
|
+
}
|
|
3062
|
+
// Workspace skills directory (highest precedence for overrides)
|
|
3063
|
+
const workspaceSkillsDir = workspaceDir ? `${workspaceDir}/skills` : null;
|
|
3064
|
+
const managedSkillsDir = path.join(resolveStateDir(), "skills");
|
|
3065
|
+
// āā Sandbox mode setup āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
|
|
3066
|
+
const sandboxConfig = config.agents?.defaults?.sandbox;
|
|
3067
|
+
const sandboxModeStr = sandboxConfig
|
|
3068
|
+
?.mode;
|
|
3069
|
+
const sandboxMode = sandboxModeStr === "light" ||
|
|
3070
|
+
sandboxModeStr === "standard" ||
|
|
3071
|
+
sandboxModeStr === "max"
|
|
3072
|
+
? sandboxModeStr
|
|
3073
|
+
: "off";
|
|
3074
|
+
const isSandboxActive = sandboxMode !== "off";
|
|
3075
|
+
let sandboxManager = null;
|
|
3076
|
+
let sandboxAuditLog = null;
|
|
3077
|
+
if (isSandboxActive) {
|
|
3078
|
+
logger.info(`[milady] Sandbox mode: ${sandboxMode}`);
|
|
3079
|
+
sandboxAuditLog = new SandboxAuditLog({ console: true });
|
|
3080
|
+
// Standard/max modes also start the container sandbox manager
|
|
3081
|
+
if (sandboxMode === "standard" || sandboxMode === "max") {
|
|
3082
|
+
const dockerSettings = sandboxConfig?.docker;
|
|
3083
|
+
const browserSettings = sandboxConfig?.browser;
|
|
3084
|
+
sandboxManager = new SandboxManager({
|
|
3085
|
+
mode: sandboxMode,
|
|
3086
|
+
image: dockerSettings?.image ?? undefined,
|
|
3087
|
+
containerPrefix: dockerSettings?.containerPrefix ?? undefined,
|
|
3088
|
+
network: dockerSettings?.network ?? undefined,
|
|
3089
|
+
memory: dockerSettings?.memory ?? undefined,
|
|
3090
|
+
cpus: dockerSettings?.cpus ?? undefined,
|
|
3091
|
+
workspaceRoot: workspaceDir ?? undefined,
|
|
3092
|
+
browser: browserSettings
|
|
3093
|
+
? {
|
|
3094
|
+
enabled: browserSettings.enabled ?? false,
|
|
3095
|
+
image: browserSettings.image ?? undefined,
|
|
3096
|
+
cdpPort: browserSettings.cdpPort ?? undefined,
|
|
3097
|
+
vncPort: browserSettings.vncPort ?? undefined,
|
|
3098
|
+
noVncPort: browserSettings.noVncPort ?? undefined,
|
|
3099
|
+
headless: browserSettings.headless ?? undefined,
|
|
3100
|
+
enableNoVnc: browserSettings.enableNoVnc ?? undefined,
|
|
3101
|
+
autoStart: browserSettings.autoStart ?? true,
|
|
3102
|
+
autoStartTimeoutMs: browserSettings.autoStartTimeoutMs ?? undefined,
|
|
3103
|
+
}
|
|
3104
|
+
: undefined,
|
|
3105
|
+
});
|
|
3106
|
+
try {
|
|
3107
|
+
await sandboxManager.start();
|
|
3108
|
+
logger.info("[milady] Sandbox manager started");
|
|
3109
|
+
}
|
|
3110
|
+
catch (err) {
|
|
3111
|
+
logger.error(`[milady] Sandbox manager failed to start: ${err instanceof Error ? err.message : String(err)}`);
|
|
3112
|
+
// Non-fatal: light mode fallback
|
|
3113
|
+
}
|
|
3114
|
+
}
|
|
3115
|
+
sandboxAuditLog.record({
|
|
3116
|
+
type: "sandbox_lifecycle",
|
|
3117
|
+
summary: `Sandbox initialized: mode=${sandboxMode}`,
|
|
3118
|
+
severity: "info",
|
|
3119
|
+
});
|
|
3120
|
+
}
|
|
3121
|
+
// āā End sandbox setup āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
|
|
3122
|
+
// āā Boost preferred model plugin priority āāāāāāāāāāāāāāāāāāāāāāāāāāāāā
|
|
3123
|
+
// elizaOS selects the model handler with the highest `priority` for each
|
|
3124
|
+
// ModelType. All provider plugins default to priority 0, so whichever
|
|
3125
|
+
// registers first wins ā essentially random when using Promise.all.
|
|
3126
|
+
// When the user has explicitly chosen a primary model provider (via
|
|
3127
|
+
// `model.primary` in config), we bump that plugin's priority so its
|
|
3128
|
+
// handlers are always selected over other providers.
|
|
3129
|
+
const pluginsForRuntime = otherPlugins.map((p) => p.plugin);
|
|
3130
|
+
const visionModeSetting = resolveVisionModeSetting(config);
|
|
3131
|
+
if (primaryModel) {
|
|
3132
|
+
for (const plugin of pluginsForRuntime) {
|
|
3133
|
+
if (plugin.name === primaryModel) {
|
|
3134
|
+
plugin.priority = (plugin.priority ?? 0) + 10;
|
|
3135
|
+
logger.info(`[milady] Boosted plugin "${plugin.name}" priority to ${plugin.priority} (model.primary)`);
|
|
3136
|
+
break;
|
|
3137
|
+
}
|
|
3138
|
+
}
|
|
3139
|
+
}
|
|
3140
|
+
// Deduplicate actions across all plugins to avoid "Action already registered"
|
|
3141
|
+
// warnings from elizaOS core. First plugin wins (miladyPlugin is first).
|
|
3142
|
+
deduplicatePluginActions([miladyPlugin, ...pluginsForRuntime]);
|
|
3143
|
+
let runtime = new AgentRuntime({
|
|
3144
|
+
character,
|
|
3145
|
+
// advancedCapabilities: true,
|
|
3146
|
+
actionPlanning: true,
|
|
3147
|
+
// advancedMemory: true, // Not supported in this version of AgentRuntime
|
|
3148
|
+
plugins: [miladyPlugin, ...pluginsForRuntime],
|
|
3149
|
+
...(runtimeLogLevel ? { logLevel: runtimeLogLevel } : {}),
|
|
3150
|
+
// Sandbox options ā only active when mode != "off"
|
|
3151
|
+
...(isSandboxActive
|
|
3152
|
+
? {
|
|
3153
|
+
sandboxMode: true,
|
|
3154
|
+
sandboxAuditHandler: sandboxAuditLog
|
|
3155
|
+
? (event) => {
|
|
3156
|
+
sandboxAuditLog.recordTokenReplacement(event.direction, event.url, event.tokenIds);
|
|
3157
|
+
}
|
|
3158
|
+
: undefined,
|
|
3159
|
+
}
|
|
3160
|
+
: {}),
|
|
3161
|
+
settings: {
|
|
3162
|
+
VALIDATION_LEVEL: "fast",
|
|
3163
|
+
// Forward non-sensitive Milady config.env vars as runtime settings so
|
|
3164
|
+
// plugins can access them via runtime.getSetting(). This fixes a bug where
|
|
3165
|
+
// plugins (e.g. @elizaos/plugin-google-genai) call runtime.getSetting()
|
|
3166
|
+
// which returns null for keys not in settings, but the plugin checks
|
|
3167
|
+
// !== undefined causing it to use "null" as the model name.
|
|
3168
|
+
//
|
|
3169
|
+
// Security: Filter out blockchain private keys and secrets. API keys are
|
|
3170
|
+
// allowed since plugins need them via runtime.getSetting(). Private keys
|
|
3171
|
+
// should only be accessed via process.env by signing services.
|
|
3172
|
+
...Object.fromEntries(Object.entries(collectConfigEnvVars(config)).filter(([key]) => isEnvKeyAllowedForForwarding(key))),
|
|
3173
|
+
// Forward Milady config env vars as runtime settings
|
|
3174
|
+
...(primaryModel ? { MODEL_PROVIDER: primaryModel } : {}),
|
|
3175
|
+
...(visionModeSetting ? { VISION_MODE: visionModeSetting } : {}),
|
|
3176
|
+
// Forward skills config so plugin-agent-skills can apply allow/deny filtering
|
|
3177
|
+
...(config.skills?.allowBundled
|
|
3178
|
+
? { SKILLS_ALLOWLIST: config.skills.allowBundled.join(",") }
|
|
3179
|
+
: {}),
|
|
3180
|
+
...(config.skills?.denyBundled
|
|
3181
|
+
? { SKILLS_DENYLIST: config.skills.denyBundled.join(",") }
|
|
3182
|
+
: {}),
|
|
3183
|
+
// Managed skills are stored in the Milady state dir (~/.milady/skills).
|
|
3184
|
+
SKILLS_DIR: managedSkillsDir,
|
|
3185
|
+
// Tell plugin-agent-skills where to find bundled + workspace skills
|
|
3186
|
+
...(bundledSkillsDir ? { BUNDLED_SKILLS_DIRS: bundledSkillsDir } : {}),
|
|
3187
|
+
...(workspaceSkillsDir
|
|
3188
|
+
? { WORKSPACE_SKILLS_DIR: workspaceSkillsDir }
|
|
3189
|
+
: {}),
|
|
3190
|
+
// Also forward extra dirs from config
|
|
3191
|
+
...(config.skills?.load?.extraDirs?.length
|
|
3192
|
+
? { EXTRA_SKILLS_DIRS: config.skills.load.extraDirs.join(",") }
|
|
3193
|
+
: {}),
|
|
3194
|
+
// Disable image description when vision is explicitly toggled off.
|
|
3195
|
+
// The cloud plugin always registers IMAGE_DESCRIPTION, so we need a
|
|
3196
|
+
// runtime setting to prevent the message service from calling it.
|
|
3197
|
+
...(config.features?.vision === false
|
|
3198
|
+
? { DISABLE_IMAGE_DESCRIPTION: "true" }
|
|
3199
|
+
: {}),
|
|
3200
|
+
},
|
|
3201
|
+
});
|
|
3202
|
+
installRuntimeMethodBindings(runtime);
|
|
3203
|
+
// 7b. Pre-register plugin-sql so the adapter is ready before other plugins init.
|
|
3204
|
+
// This is OPTIONAL ā without it, some features (memory, todos) won't work.
|
|
3205
|
+
// runtime.db is a getter that returns this.adapter.db and throws when
|
|
3206
|
+
// this.adapter is undefined, so plugins that use runtime.db will fail.
|
|
3207
|
+
if (sqlPlugin) {
|
|
3208
|
+
// 7c. Eagerly initialize the database adapter so it's fully ready
|
|
3209
|
+
// BEFORE other plugins run their init(). When legacy/corrupt PGLite
|
|
3210
|
+
// state causes startup aborts, reset the local DB dir and retry once.
|
|
3211
|
+
await registerSqlPluginWithRecovery(runtime, sqlPlugin, config);
|
|
3212
|
+
}
|
|
3213
|
+
else {
|
|
3214
|
+
const loadedNames = resolvedPlugins.map((p) => p.name).join(", ");
|
|
3215
|
+
logger.error(`[milady] @elizaos/plugin-sql was NOT found among resolved plugins. ` +
|
|
3216
|
+
`Loaded: [${loadedNames}]`);
|
|
3217
|
+
throw new Error("@elizaos/plugin-sql is required but was not loaded. " +
|
|
3218
|
+
"Ensure the package is installed and built (check for import errors above).");
|
|
3219
|
+
}
|
|
3220
|
+
// 7d. Pre-register plugin-local-embedding so its TEXT_EMBEDDING handler
|
|
3221
|
+
// (priority 10) is available before runtime.initialize() starts all
|
|
3222
|
+
// plugins in parallel. Without this, the bootstrap plugin's services
|
|
3223
|
+
// (ActionFilterService, EmbeddingGenerationService) race ahead and use
|
|
3224
|
+
// the cloud plugin's TEXT_EMBEDDING handler ā which hits a paid API ā
|
|
3225
|
+
// because local-embedding's heavier init hasn't completed yet.
|
|
3226
|
+
if (localEmbeddingPlugin) {
|
|
3227
|
+
configureLocalEmbeddingPlugin(localEmbeddingPlugin.plugin, config);
|
|
3228
|
+
await runtime.registerPlugin(localEmbeddingPlugin.plugin);
|
|
3229
|
+
logger.info("[milady] plugin-local-embedding pre-registered (TEXT_EMBEDDING ready)");
|
|
3230
|
+
}
|
|
3231
|
+
else {
|
|
3232
|
+
logger.warn("[milady] @elizaos/plugin-local-embedding not found ā embeddings " +
|
|
3233
|
+
"will fall back to whatever TEXT_EMBEDDING handler is registered by " +
|
|
3234
|
+
"other plugins (may incur cloud API costs)");
|
|
3235
|
+
}
|
|
3236
|
+
// 7e. Pre-register remaining core plugins sequentially in CORE_PLUGINS order.
|
|
3237
|
+
// Each registerPlugin() call runs the plugin's init() before proceeding
|
|
3238
|
+
// to the next, guaranteeing that cross-plugin getService() calls resolve.
|
|
3239
|
+
{
|
|
3240
|
+
const alreadyPreRegistered = new Set([
|
|
3241
|
+
"@elizaos/plugin-sql",
|
|
3242
|
+
"@elizaos/plugin-local-embedding",
|
|
3243
|
+
]);
|
|
3244
|
+
for (const name of CORE_PLUGINS) {
|
|
3245
|
+
if (alreadyPreRegistered.has(name))
|
|
3246
|
+
continue;
|
|
3247
|
+
const resolved = resolvedPlugins.find((p) => p.name === name);
|
|
3248
|
+
if (!resolved) {
|
|
3249
|
+
logger.debug(`[milady] Core plugin ${name} not resolved ā skipping pre-registration`);
|
|
3250
|
+
continue;
|
|
3251
|
+
}
|
|
3252
|
+
try {
|
|
3253
|
+
await runtime.registerPlugin(resolved.plugin);
|
|
3254
|
+
}
|
|
3255
|
+
catch (err) {
|
|
3256
|
+
logger.warn(`[milady] Core plugin ${name} pre-registration failed: ${formatError(err)}`);
|
|
3257
|
+
}
|
|
3258
|
+
}
|
|
3259
|
+
}
|
|
3260
|
+
const warmAgentSkillsService = async () => {
|
|
3261
|
+
// Let runtime startup complete first; this warm-up runs asynchronously
|
|
3262
|
+
// so API + agent come online immediately.
|
|
3263
|
+
try {
|
|
3264
|
+
const skillServicePromise = runtime.getServiceLoadPromise("AGENT_SKILLS_SERVICE");
|
|
3265
|
+
const timeout = new Promise((_resolve, reject) => {
|
|
3266
|
+
setTimeout(() => {
|
|
3267
|
+
reject(new Error("AgentSkillsService warm-up timed out (10s) ā non-blocking, agent will function without skills"));
|
|
3268
|
+
}, 10_000);
|
|
3269
|
+
});
|
|
3270
|
+
await Promise.race([skillServicePromise, timeout]);
|
|
3271
|
+
const svc = runtime.getService("AGENT_SKILLS_SERVICE");
|
|
3272
|
+
if (svc?.getCatalogStats) {
|
|
3273
|
+
const stats = svc.getCatalogStats();
|
|
3274
|
+
logger.info(`[milady] AgentSkills ready ā ${stats.loaded} skills loaded, ` +
|
|
3275
|
+
`${stats.total} in catalog (storage: ${stats.storageType})`);
|
|
3276
|
+
}
|
|
3277
|
+
// Guard against non-string skill.description values.
|
|
3278
|
+
// The bundled YAML parser produces {} for multi-line descriptions, which
|
|
3279
|
+
// crashes findBestLocalMatch / scoreSkillMatch (call .toLowerCase() on it).
|
|
3280
|
+
// Instead of a one-shot sanitize (which misses skills loaded later by
|
|
3281
|
+
// syncCatalog / autoRefresh), we monkey-patch getLoadedSkills to always
|
|
3282
|
+
// return sanitized values.
|
|
3283
|
+
const svcAny = svc;
|
|
3284
|
+
const origGetLoaded = svcAny?.getLoadedSkills;
|
|
3285
|
+
if (origGetLoaded && svcAny) {
|
|
3286
|
+
svcAny.getLoadedSkills = function (...args) {
|
|
3287
|
+
const skills = origGetLoaded.apply(this, args);
|
|
3288
|
+
for (const skill of skills) {
|
|
3289
|
+
if (typeof skill.description !== "string") {
|
|
3290
|
+
skill.description =
|
|
3291
|
+
skill.description == null
|
|
3292
|
+
? ""
|
|
3293
|
+
: JSON.stringify(skill.description);
|
|
3294
|
+
}
|
|
3295
|
+
}
|
|
3296
|
+
return skills;
|
|
3297
|
+
};
|
|
3298
|
+
logger.debug("[milady] Patched getLoadedSkills to guard descriptions");
|
|
3299
|
+
}
|
|
3300
|
+
}
|
|
3301
|
+
catch (err) {
|
|
3302
|
+
// Non-fatal ā the agent can operate without skills. This warm-up runs
|
|
3303
|
+
// async so it doesn't block startup.
|
|
3304
|
+
logger.debug(`[milady] AgentSkillsService warm-up: ${formatError(err)}`);
|
|
3305
|
+
}
|
|
3306
|
+
};
|
|
3307
|
+
const initializeRuntimeServices = async () => {
|
|
3308
|
+
// 8. Initialize the runtime (registers remaining plugins, starts services)
|
|
3309
|
+
await runtime.initialize();
|
|
3310
|
+
await waitForTrajectoryLoggerService(runtime, "runtime.initialize()");
|
|
3311
|
+
ensureTrajectoryLoggerEnabled(runtime, "runtime.initialize()");
|
|
3312
|
+
installDatabaseTrajectoryLogger(runtime);
|
|
3313
|
+
patchTrajectoryLoggerAliasCompatibility(runtime);
|
|
3314
|
+
// 8b. Ensure AutonomyService is available for trigger dispatch.
|
|
3315
|
+
// IGNORE_BOOTSTRAP=true prevents the bootstrap plugin (which normally
|
|
3316
|
+
// registers this service) from loading, so we start it explicitly.
|
|
3317
|
+
if (!runtime.getService("AUTONOMY")) {
|
|
3318
|
+
try {
|
|
3319
|
+
await AutonomyService.start(runtime);
|
|
3320
|
+
logger.info("[milady] AutonomyService started for trigger dispatch");
|
|
3321
|
+
}
|
|
3322
|
+
catch (err) {
|
|
3323
|
+
logger.warn(`[milady] AutonomyService failed to start: ${formatError(err)}`);
|
|
3324
|
+
}
|
|
3325
|
+
}
|
|
3326
|
+
// Do not block runtime startup on skills warm-up.
|
|
3327
|
+
void warmAgentSkillsService();
|
|
3328
|
+
};
|
|
3329
|
+
try {
|
|
3330
|
+
await initializeRuntimeServices();
|
|
3331
|
+
}
|
|
3332
|
+
catch (err) {
|
|
3333
|
+
const pgliteDataDir = resolveActivePgliteDataDir(config);
|
|
3334
|
+
const recoveryAction = !opts?.pgliteRecoveryAttempted && pgliteDataDir
|
|
3335
|
+
? getPgliteRecoveryAction(err, pgliteDataDir)
|
|
3336
|
+
: "none";
|
|
3337
|
+
if (!pgliteDataDir || recoveryAction === "none") {
|
|
3338
|
+
throw err;
|
|
3339
|
+
}
|
|
3340
|
+
if (recoveryAction === "fail-active-lock") {
|
|
3341
|
+
throw createActivePgliteLockError(pgliteDataDir, err);
|
|
3342
|
+
}
|
|
3343
|
+
logger.warn(recoveryAction === "retry-without-reset"
|
|
3344
|
+
? `[milady] Runtime migrations failed (${formatError(err)}). Cleared a stale PGLite lock in ${pgliteDataDir} and retrying startup once without resetting data.`
|
|
3345
|
+
: `[milady] Runtime migrations failed (${formatError(err)}). Resetting local PGLite DB at ${pgliteDataDir} and retrying startup once.`);
|
|
3346
|
+
try {
|
|
3347
|
+
await shutdownRuntime(runtime, "PGLite recovery");
|
|
3348
|
+
}
|
|
3349
|
+
catch {
|
|
3350
|
+
// Ignore cleanup errors ā retry creates a fresh runtime anyway.
|
|
3351
|
+
}
|
|
3352
|
+
if (recoveryAction === "reset-data-dir") {
|
|
3353
|
+
await resetPgliteDataDir(pgliteDataDir);
|
|
3354
|
+
process.env.PGLITE_DATA_DIR = pgliteDataDir;
|
|
3355
|
+
}
|
|
3356
|
+
return await startEliza({
|
|
3357
|
+
...opts,
|
|
3358
|
+
pgliteRecoveryAttempted: true,
|
|
3359
|
+
});
|
|
3360
|
+
}
|
|
3361
|
+
installActionAliases(runtime);
|
|
3362
|
+
// 9. Graceful shutdown handler
|
|
3363
|
+
//
|
|
3364
|
+
// In headless mode the caller (dev-server / Electron) owns the process
|
|
3365
|
+
// lifecycle, so we must NOT register signal handlers here ā they would
|
|
3366
|
+
// stack on every hot-restart, close over stale runtime references, and
|
|
3367
|
+
// race with bun --watch's own process teardown.
|
|
3368
|
+
if (!opts?.headless) {
|
|
3369
|
+
let isShuttingDown = false;
|
|
3370
|
+
const shutdown = async () => {
|
|
3371
|
+
if (isShuttingDown)
|
|
3372
|
+
return;
|
|
3373
|
+
isShuttingDown = true;
|
|
3374
|
+
try {
|
|
3375
|
+
// Stop sandbox manager before runtime
|
|
3376
|
+
if (sandboxManager) {
|
|
3377
|
+
try {
|
|
3378
|
+
await sandboxManager.stop();
|
|
3379
|
+
logger.info("[milady] Sandbox manager stopped");
|
|
3380
|
+
}
|
|
3381
|
+
catch (err) {
|
|
3382
|
+
logger.warn(`[milady] Sandbox stop error: ${err instanceof Error ? err.message : String(err)}`);
|
|
3383
|
+
}
|
|
3384
|
+
}
|
|
3385
|
+
}
|
|
3386
|
+
catch (err) {
|
|
3387
|
+
logger.warn(`[milady] Sandbox shutdown error: ${formatError(err)}`);
|
|
3388
|
+
}
|
|
3389
|
+
try {
|
|
3390
|
+
await shutdownRuntime(runtime, "signal shutdown");
|
|
3391
|
+
}
|
|
3392
|
+
catch (err) {
|
|
3393
|
+
logger.warn(`[milady] Error during shutdown: ${formatError(err)}`);
|
|
3394
|
+
}
|
|
3395
|
+
process.exit(0);
|
|
3396
|
+
};
|
|
3397
|
+
process.on("SIGINT", () => void shutdown());
|
|
3398
|
+
process.on("SIGTERM", () => void shutdown());
|
|
3399
|
+
}
|
|
3400
|
+
const loadHooksSystem = async () => {
|
|
3401
|
+
try {
|
|
3402
|
+
const internalHooksConfig = config.hooks
|
|
3403
|
+
?.internal;
|
|
3404
|
+
await loadHooks({
|
|
3405
|
+
workspacePath: workspaceDir,
|
|
3406
|
+
internalConfig: internalHooksConfig,
|
|
3407
|
+
miladyConfig: config,
|
|
3408
|
+
});
|
|
3409
|
+
const startupEvent = createHookEvent("gateway", "startup", "system", {
|
|
3410
|
+
cfg: config,
|
|
3411
|
+
});
|
|
3412
|
+
await triggerHook(startupEvent);
|
|
3413
|
+
}
|
|
3414
|
+
catch (err) {
|
|
3415
|
+
logger.warn(`[milady] Hooks system could not load: ${formatError(err)}`);
|
|
3416
|
+
}
|
|
3417
|
+
};
|
|
3418
|
+
// āā Headless mode ā return runtime for API server wiring āāāāāāāāāāāāāā
|
|
3419
|
+
if (opts?.headless) {
|
|
3420
|
+
void loadHooksSystem();
|
|
3421
|
+
logger.info("[milady] Runtime initialised in headless mode (autonomy enabled)");
|
|
3422
|
+
return runtime;
|
|
3423
|
+
}
|
|
3424
|
+
// 10. Load hooks system
|
|
3425
|
+
await loadHooksSystem();
|
|
3426
|
+
// āā Start API server for GUI access āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
|
|
3427
|
+
// In CLI mode (non-headless), start the API server in the background so
|
|
3428
|
+
// the GUI can connect to the running agent. This ensures full feature
|
|
3429
|
+
// parity: whether started via `npx miladyai`, `bun run dev`, or the
|
|
3430
|
+
// desktop app, the API server is always available for the GUI admin
|
|
3431
|
+
// surface.
|
|
3432
|
+
try {
|
|
3433
|
+
const { startApiServer } = await import("../api/server");
|
|
3434
|
+
const apiPort = Number(process.env.MILADY_PORT) || 2138;
|
|
3435
|
+
const { port: actualApiPort } = await startApiServer({
|
|
3436
|
+
port: apiPort,
|
|
3437
|
+
runtime,
|
|
3438
|
+
onRestart: async () => {
|
|
3439
|
+
logger.info("[milady] Hot-reload: Restarting runtime...");
|
|
3440
|
+
try {
|
|
3441
|
+
// Stop the old runtime to release resources (DB connections, timers, etc.)
|
|
3442
|
+
try {
|
|
3443
|
+
await shutdownRuntime(runtime, "hot-reload cleanup");
|
|
3444
|
+
}
|
|
3445
|
+
catch (stopErr) {
|
|
3446
|
+
logger.warn(`[milady] Hot-reload: old runtime stop failed: ${formatError(stopErr)}`);
|
|
3447
|
+
}
|
|
3448
|
+
// Reload config from disk (updated by API)
|
|
3449
|
+
const freshConfig = loadMiladyConfig();
|
|
3450
|
+
// Propagate secrets & cloud config into process.env so plugins
|
|
3451
|
+
// (especially plugin-elizacloud) can discover them. The initial
|
|
3452
|
+
// startup does this in startEliza(); the hot-reload must repeat it
|
|
3453
|
+
// because the config may have changed (e.g. cloud enabled during
|
|
3454
|
+
// onboarding).
|
|
3455
|
+
applyConnectorSecretsToEnv(freshConfig);
|
|
3456
|
+
await autoResolveDiscordAppId();
|
|
3457
|
+
applyCloudConfigToEnv(freshConfig);
|
|
3458
|
+
applyX402ConfigToEnv(freshConfig);
|
|
3459
|
+
applyDatabaseConfigToEnv(freshConfig);
|
|
3460
|
+
// Apply subscription-based credentials (Claude Max, Codex Max)
|
|
3461
|
+
// that may have been set up during onboarding.
|
|
3462
|
+
try {
|
|
3463
|
+
const { applySubscriptionCredentials } = await import("../auth/index");
|
|
3464
|
+
await applySubscriptionCredentials(freshConfig);
|
|
3465
|
+
}
|
|
3466
|
+
catch (subErr) {
|
|
3467
|
+
logger.warn(`[milady] Hot-reload: subscription credentials: ${formatError(subErr)}`);
|
|
3468
|
+
}
|
|
3469
|
+
// Resolve plugins using same function as startup
|
|
3470
|
+
const resolvedPlugins = await resolvePlugins(freshConfig);
|
|
3471
|
+
// Rebuild character from the fresh config so onboarding changes
|
|
3472
|
+
// (name, bio, style, etc.) are picked up on restart.
|
|
3473
|
+
const freshCharacter = buildCharacterFromConfig(freshConfig);
|
|
3474
|
+
// Recreate Milady plugin with fresh workspace
|
|
3475
|
+
const freshMiladyPlugin = createAutonomousPlugin({
|
|
3476
|
+
workspaceDir: freshConfig.agents?.defaults?.workspace ?? workspaceDir,
|
|
3477
|
+
bootstrapMaxChars: freshConfig.agents?.defaults?.bootstrapMaxChars,
|
|
3478
|
+
agentId: freshCharacter.name?.toLowerCase().replace(/\s+/g, "-") ?? "main",
|
|
3479
|
+
});
|
|
3480
|
+
// Create new runtime with updated plugins.
|
|
3481
|
+
// Filter out pre-registered plugins so they aren't double-loaded
|
|
3482
|
+
// inside initialize()'s Promise.all ā same pattern as the initial
|
|
3483
|
+
// startup to avoid the TEXT_EMBEDDING race condition.
|
|
3484
|
+
const freshPrimaryModel = resolvePrimaryModel(freshConfig);
|
|
3485
|
+
const freshOtherPlugins = resolvedPlugins.filter((p) => !PREREGISTER_PLUGINS.has(p.name));
|
|
3486
|
+
// Boost preferred model plugin priority (same as initial startup)
|
|
3487
|
+
const freshPluginsForRuntime = freshOtherPlugins.map((p) => p.plugin);
|
|
3488
|
+
const freshVisionModeSetting = resolveVisionModeSetting(freshConfig);
|
|
3489
|
+
if (freshPrimaryModel) {
|
|
3490
|
+
for (const plugin of freshPluginsForRuntime) {
|
|
3491
|
+
if (plugin.name === freshPrimaryModel) {
|
|
3492
|
+
plugin.priority = (plugin.priority ?? 0) + 10;
|
|
3493
|
+
break;
|
|
3494
|
+
}
|
|
3495
|
+
}
|
|
3496
|
+
}
|
|
3497
|
+
const newRuntime = new AgentRuntime({
|
|
3498
|
+
character: freshCharacter,
|
|
3499
|
+
plugins: [freshMiladyPlugin, ...freshPluginsForRuntime],
|
|
3500
|
+
...(runtimeLogLevel ? { logLevel: runtimeLogLevel } : {}),
|
|
3501
|
+
settings: {
|
|
3502
|
+
...(freshPrimaryModel
|
|
3503
|
+
? { MODEL_PROVIDER: freshPrimaryModel }
|
|
3504
|
+
: {}),
|
|
3505
|
+
...(freshVisionModeSetting
|
|
3506
|
+
? { VISION_MODE: freshVisionModeSetting }
|
|
3507
|
+
: {}),
|
|
3508
|
+
// Disable image description when vision is explicitly toggled off.
|
|
3509
|
+
...(freshConfig.features?.vision === false
|
|
3510
|
+
? { DISABLE_IMAGE_DESCRIPTION: "true" }
|
|
3511
|
+
: {}),
|
|
3512
|
+
},
|
|
3513
|
+
});
|
|
3514
|
+
installRuntimeMethodBindings(newRuntime);
|
|
3515
|
+
// Pre-register plugin-sql + local-embedding before initialize()
|
|
3516
|
+
// to avoid the same race condition as the initial startup.
|
|
3517
|
+
// Re-derive from freshly resolved plugins (not outer closure) so
|
|
3518
|
+
// hot-reload picks up any plugin updates.
|
|
3519
|
+
const freshSqlPlugin = resolvedPlugins.find((p) => p.name === "@elizaos/plugin-sql");
|
|
3520
|
+
const freshLocalEmbeddingPlugin = resolvedPlugins.find((p) => p.name === "@elizaos/plugin-local-embedding");
|
|
3521
|
+
if (freshSqlPlugin) {
|
|
3522
|
+
await registerSqlPluginWithRecovery(newRuntime, freshSqlPlugin, freshConfig);
|
|
3523
|
+
}
|
|
3524
|
+
if (freshLocalEmbeddingPlugin) {
|
|
3525
|
+
configureLocalEmbeddingPlugin(freshLocalEmbeddingPlugin.plugin, freshConfig);
|
|
3526
|
+
await newRuntime.registerPlugin(freshLocalEmbeddingPlugin.plugin);
|
|
3527
|
+
}
|
|
3528
|
+
// Pre-register remaining core plugins sequentially (same as startup)
|
|
3529
|
+
{
|
|
3530
|
+
const alreadyPreRegistered = new Set([
|
|
3531
|
+
"@elizaos/plugin-sql",
|
|
3532
|
+
"@elizaos/plugin-local-embedding",
|
|
3533
|
+
]);
|
|
3534
|
+
for (const name of CORE_PLUGINS) {
|
|
3535
|
+
if (alreadyPreRegistered.has(name))
|
|
3536
|
+
continue;
|
|
3537
|
+
const resolved = resolvedPlugins.find((p) => p.name === name);
|
|
3538
|
+
if (!resolved)
|
|
3539
|
+
continue;
|
|
3540
|
+
try {
|
|
3541
|
+
await newRuntime.registerPlugin(resolved.plugin);
|
|
3542
|
+
}
|
|
3543
|
+
catch (err) {
|
|
3544
|
+
logger.warn(`[milady] Hot-reload: core plugin ${name} pre-registration failed: ${formatError(err)}`);
|
|
3545
|
+
}
|
|
3546
|
+
}
|
|
3547
|
+
}
|
|
3548
|
+
await newRuntime.initialize();
|
|
3549
|
+
await waitForTrajectoryLoggerService(newRuntime, "hot-reload runtime.initialize()");
|
|
3550
|
+
ensureTrajectoryLoggerEnabled(newRuntime, "hot-reload runtime.initialize()");
|
|
3551
|
+
// Ensure AutonomyService survives hot-reload
|
|
3552
|
+
if (!newRuntime.getService("AUTONOMY")) {
|
|
3553
|
+
try {
|
|
3554
|
+
await AutonomyService.start(newRuntime);
|
|
3555
|
+
}
|
|
3556
|
+
catch (err) {
|
|
3557
|
+
logger.warn(`[milady] AutonomyService failed to start after hot-reload: ${formatError(err)}`);
|
|
3558
|
+
}
|
|
3559
|
+
}
|
|
3560
|
+
installActionAliases(newRuntime);
|
|
3561
|
+
runtime = newRuntime;
|
|
3562
|
+
logger.info("[milady] Hot-reload: Runtime restarted successfully");
|
|
3563
|
+
return newRuntime;
|
|
3564
|
+
}
|
|
3565
|
+
catch (err) {
|
|
3566
|
+
logger.error(`[milady] Hot-reload failed: ${formatError(err)}`);
|
|
3567
|
+
return null;
|
|
3568
|
+
}
|
|
3569
|
+
},
|
|
3570
|
+
});
|
|
3571
|
+
const dashboardUrl = `http://localhost:${actualApiPort}`;
|
|
3572
|
+
console.log(`[milady] Control UI: ${dashboardUrl}`);
|
|
3573
|
+
logger.info(`[milady] API server listening on ${dashboardUrl}`);
|
|
3574
|
+
}
|
|
3575
|
+
catch (apiErr) {
|
|
3576
|
+
logger.warn(`[milady] Could not start API server: ${formatError(apiErr)}`);
|
|
3577
|
+
// Non-fatal ā CLI chat loop still works without the API server.
|
|
3578
|
+
}
|
|
3579
|
+
// āā Server-only mode ā keep running without chat loop āāāāāāāāāāāāāāāāāāāā
|
|
3580
|
+
if (opts?.serverOnly) {
|
|
3581
|
+
logger.info("[milady] Running in server-only mode (no interactive chat)");
|
|
3582
|
+
console.log("[milady] Server running. Press Ctrl+C to stop.");
|
|
3583
|
+
// Keep process alive ā the API server handles all interaction
|
|
3584
|
+
const keepAlive = setInterval(() => { }, 1 << 30); // ~12 days
|
|
3585
|
+
// Cleanup on exit
|
|
3586
|
+
const cleanup = async () => {
|
|
3587
|
+
clearInterval(keepAlive);
|
|
3588
|
+
try {
|
|
3589
|
+
await shutdownRuntime(runtime, "server-only shutdown");
|
|
3590
|
+
}
|
|
3591
|
+
catch (err) {
|
|
3592
|
+
logger.warn(`[milady] Error stopping runtime: ${formatError(err)}`);
|
|
3593
|
+
}
|
|
3594
|
+
process.exit(0);
|
|
3595
|
+
};
|
|
3596
|
+
process.on("SIGINT", () => void cleanup());
|
|
3597
|
+
process.on("SIGTERM", () => void cleanup());
|
|
3598
|
+
return runtime;
|
|
3599
|
+
}
|
|
3600
|
+
// āā Interactive chat loop āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
|
|
3601
|
+
const agentName = character.name ?? "Milady";
|
|
3602
|
+
const userId = crypto.randomUUID();
|
|
3603
|
+
// Use `let` so the fallback path can reassign to fresh IDs.
|
|
3604
|
+
let roomId = stringToUuid(`${agentName}-chat-room`);
|
|
3605
|
+
try {
|
|
3606
|
+
const worldId = stringToUuid(`${agentName}-chat-world`);
|
|
3607
|
+
// Use a deterministic messageServerId so the settings provider
|
|
3608
|
+
// can reference the world by serverId after it is found.
|
|
3609
|
+
const messageServerId = stringToUuid(`${agentName}-cli-server`);
|
|
3610
|
+
await runtime.ensureConnection({
|
|
3611
|
+
entityId: userId,
|
|
3612
|
+
roomId,
|
|
3613
|
+
worldId,
|
|
3614
|
+
userName: "User",
|
|
3615
|
+
source: "cli",
|
|
3616
|
+
channelId: `${agentName}-chat`,
|
|
3617
|
+
type: ChannelType.DM,
|
|
3618
|
+
messageServerId,
|
|
3619
|
+
metadata: { ownership: { ownerId: userId } },
|
|
3620
|
+
});
|
|
3621
|
+
// Ensure the world has ownership metadata so the settings
|
|
3622
|
+
// provider can locate it via findWorldsForOwner during onboarding.
|
|
3623
|
+
// This also handles worlds that already exist from a prior session
|
|
3624
|
+
// but were created without ownership metadata.
|
|
3625
|
+
const world = await runtime.getWorld(worldId);
|
|
3626
|
+
if (world) {
|
|
3627
|
+
let needsUpdate = false;
|
|
3628
|
+
if (!world.metadata) {
|
|
3629
|
+
world.metadata = {};
|
|
3630
|
+
needsUpdate = true;
|
|
3631
|
+
}
|
|
3632
|
+
if (!world.metadata.ownership ||
|
|
3633
|
+
typeof world.metadata.ownership !== "object" ||
|
|
3634
|
+
world.metadata.ownership.ownerId !== userId) {
|
|
3635
|
+
world.metadata.ownership = { ownerId: userId };
|
|
3636
|
+
needsUpdate = true;
|
|
3637
|
+
}
|
|
3638
|
+
if (needsUpdate) {
|
|
3639
|
+
await runtime.updateWorld(world);
|
|
3640
|
+
}
|
|
3641
|
+
}
|
|
3642
|
+
}
|
|
3643
|
+
catch (err) {
|
|
3644
|
+
logger.warn(`[milady] Could not establish chat room, retrying with fresh IDs: ${formatError(err)}`);
|
|
3645
|
+
// Fall back to unique IDs if deterministic ones conflict with stale data.
|
|
3646
|
+
// IMPORTANT: reassign roomId so the message loop below uses the same room.
|
|
3647
|
+
roomId = crypto.randomUUID();
|
|
3648
|
+
const freshWorldId = crypto.randomUUID();
|
|
3649
|
+
const freshServerId = crypto.randomUUID();
|
|
3650
|
+
try {
|
|
3651
|
+
await runtime.ensureConnection({
|
|
3652
|
+
entityId: userId,
|
|
3653
|
+
roomId,
|
|
3654
|
+
worldId: freshWorldId,
|
|
3655
|
+
userName: "User",
|
|
3656
|
+
source: "cli",
|
|
3657
|
+
channelId: `${agentName}-chat`,
|
|
3658
|
+
type: ChannelType.DM,
|
|
3659
|
+
messageServerId: freshServerId,
|
|
3660
|
+
metadata: { ownership: { ownerId: userId } },
|
|
3661
|
+
});
|
|
3662
|
+
// Same ownership metadata fix for the fallback world.
|
|
3663
|
+
const fallbackWorld = await runtime.getWorld(freshWorldId);
|
|
3664
|
+
if (fallbackWorld) {
|
|
3665
|
+
let needsUpdate = false;
|
|
3666
|
+
if (!fallbackWorld.metadata) {
|
|
3667
|
+
fallbackWorld.metadata = {};
|
|
3668
|
+
needsUpdate = true;
|
|
3669
|
+
}
|
|
3670
|
+
if (!fallbackWorld.metadata.ownership ||
|
|
3671
|
+
typeof fallbackWorld.metadata.ownership !== "object" ||
|
|
3672
|
+
fallbackWorld.metadata.ownership.ownerId !==
|
|
3673
|
+
userId) {
|
|
3674
|
+
fallbackWorld.metadata.ownership = { ownerId: userId };
|
|
3675
|
+
needsUpdate = true;
|
|
3676
|
+
}
|
|
3677
|
+
if (needsUpdate) {
|
|
3678
|
+
await runtime.updateWorld(fallbackWorld);
|
|
3679
|
+
}
|
|
3680
|
+
}
|
|
3681
|
+
}
|
|
3682
|
+
catch (retryErr) {
|
|
3683
|
+
logger.error(`[milady] Chat room setup failed after retry: ${formatError(retryErr)}`);
|
|
3684
|
+
throw retryErr;
|
|
3685
|
+
}
|
|
3686
|
+
}
|
|
3687
|
+
const rl = readline.createInterface({
|
|
3688
|
+
input: process.stdin,
|
|
3689
|
+
output: process.stdout,
|
|
3690
|
+
});
|
|
3691
|
+
console.log(`\nš¬ Chat with ${agentName} (type 'exit' to quit)\n`);
|
|
3692
|
+
const prompt = () => {
|
|
3693
|
+
rl.question("You: ", async (input) => {
|
|
3694
|
+
const text = input.trim();
|
|
3695
|
+
if (text.toLowerCase() === "exit" || text.toLowerCase() === "quit") {
|
|
3696
|
+
console.log("\nGoodbye!");
|
|
3697
|
+
rl.close();
|
|
3698
|
+
try {
|
|
3699
|
+
await shutdownRuntime(runtime, "cli shutdown");
|
|
3700
|
+
}
|
|
3701
|
+
catch (err) {
|
|
3702
|
+
logger.warn(`[milady] Error stopping runtime: ${formatError(err)}`);
|
|
3703
|
+
}
|
|
3704
|
+
process.exit(0);
|
|
3705
|
+
}
|
|
3706
|
+
if (!text) {
|
|
3707
|
+
prompt();
|
|
3708
|
+
return;
|
|
3709
|
+
}
|
|
3710
|
+
try {
|
|
3711
|
+
const message = createMessageMemory({
|
|
3712
|
+
id: crypto.randomUUID(),
|
|
3713
|
+
entityId: userId,
|
|
3714
|
+
roomId,
|
|
3715
|
+
content: {
|
|
3716
|
+
text,
|
|
3717
|
+
source: "client_chat",
|
|
3718
|
+
channelType: ChannelType.DM,
|
|
3719
|
+
},
|
|
3720
|
+
});
|
|
3721
|
+
process.stdout.write(`${agentName}: `);
|
|
3722
|
+
if (!runtime.messageService) {
|
|
3723
|
+
logger.error("[milady] runtime.messageService is not available ā cannot process messages");
|
|
3724
|
+
console.log("[Error: message service unavailable]\n");
|
|
3725
|
+
prompt();
|
|
3726
|
+
return;
|
|
3727
|
+
}
|
|
3728
|
+
await runtime.messageService.handleMessage(runtime, message, async (content) => {
|
|
3729
|
+
if (content?.text) {
|
|
3730
|
+
process.stdout.write(content.text);
|
|
3731
|
+
}
|
|
3732
|
+
return [];
|
|
3733
|
+
});
|
|
3734
|
+
console.log("\n");
|
|
3735
|
+
}
|
|
3736
|
+
catch (err) {
|
|
3737
|
+
// Log the error and continue the prompt loop ā don't let a single
|
|
3738
|
+
// failed message kill the interactive session.
|
|
3739
|
+
console.log(`\n[Error: ${formatError(err)}]\n`);
|
|
3740
|
+
logger.error(`[milady] Chat message handling failed: ${formatError(err)}`);
|
|
3741
|
+
}
|
|
3742
|
+
prompt();
|
|
3743
|
+
});
|
|
3744
|
+
};
|
|
3745
|
+
prompt();
|
|
3746
|
+
}
|
|
3747
|
+
// When run directly (not imported), start immediately.
|
|
3748
|
+
// Use path.resolve to normalise both sides before comparing so that
|
|
3749
|
+
// symlinks, trailing slashes, and relative paths don't cause false negatives.
|
|
3750
|
+
const isDirectRun = (() => {
|
|
3751
|
+
const scriptArg = process.argv[1];
|
|
3752
|
+
if (!scriptArg)
|
|
3753
|
+
return false;
|
|
3754
|
+
const normalised = path.resolve(scriptArg);
|
|
3755
|
+
// Exact match against this module's file URL
|
|
3756
|
+
if (import.meta.url === pathToFileURL(normalised).href)
|
|
3757
|
+
return true;
|
|
3758
|
+
// Fallback: match the specific filename (handles tsx rewriting)
|
|
3759
|
+
const base = path.basename(normalised);
|
|
3760
|
+
return base === "eliza.ts" || base === "eliza";
|
|
3761
|
+
})();
|
|
3762
|
+
if (isDirectRun) {
|
|
3763
|
+
startEliza().catch((err) => {
|
|
3764
|
+
console.error("[milady] Fatal error:", err instanceof Error ? (err.stack ?? err.message) : err);
|
|
3765
|
+
process.exit(1);
|
|
3766
|
+
});
|
|
3767
|
+
}
|