@elizaos/agent 0.25.8 → 2.0.0-alpha.83

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