@elizaos/autonomous 2.0.0-alpha.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (795) hide show
  1. package/.turbo/turbo-build.log +2 -0
  2. package/LICENSE +21 -0
  3. package/dist/package.json +914 -0
  4. package/dist/packages/autonomous/src/actions/emote.d.ts +14 -0
  5. package/dist/packages/autonomous/src/actions/emote.d.ts.map +1 -0
  6. package/dist/packages/autonomous/src/actions/emote.js +85 -0
  7. package/dist/packages/autonomous/src/actions/restart.d.ts +19 -0
  8. package/dist/packages/autonomous/src/actions/restart.d.ts.map +1 -0
  9. package/dist/packages/autonomous/src/actions/restart.js +86 -0
  10. package/dist/packages/autonomous/src/actions/send-message.d.ts +3 -0
  11. package/dist/packages/autonomous/src/actions/send-message.d.ts.map +1 -0
  12. package/dist/packages/autonomous/src/actions/send-message.js +144 -0
  13. package/dist/packages/autonomous/src/actions/stream-control.d.ts +15 -0
  14. package/dist/packages/autonomous/src/actions/stream-control.d.ts.map +1 -0
  15. package/dist/packages/autonomous/src/actions/stream-control.js +357 -0
  16. package/dist/packages/autonomous/src/actions/switch-stream-source.d.ts +16 -0
  17. package/dist/packages/autonomous/src/actions/switch-stream-source.d.ts.map +1 -0
  18. package/dist/packages/autonomous/src/actions/switch-stream-source.js +94 -0
  19. package/dist/packages/autonomous/src/actions/terminal.d.ts +14 -0
  20. package/dist/packages/autonomous/src/actions/terminal.d.ts.map +1 -0
  21. package/dist/packages/autonomous/src/actions/terminal.js +154 -0
  22. package/dist/packages/autonomous/src/api/agent-admin-routes.d.ts +38 -0
  23. package/dist/packages/autonomous/src/api/agent-admin-routes.d.ts.map +1 -0
  24. package/dist/packages/autonomous/src/api/agent-admin-routes.js +93 -0
  25. package/dist/packages/autonomous/src/api/agent-lifecycle-routes.d.ts +16 -0
  26. package/dist/packages/autonomous/src/api/agent-lifecycle-routes.d.ts.map +1 -0
  27. package/dist/packages/autonomous/src/api/agent-lifecycle-routes.js +80 -0
  28. package/dist/packages/autonomous/src/api/agent-model.d.ts +12 -0
  29. package/dist/packages/autonomous/src/api/agent-model.d.ts.map +1 -0
  30. package/dist/packages/autonomous/src/api/agent-model.js +123 -0
  31. package/dist/packages/autonomous/src/api/agent-transfer-routes.d.ts +16 -0
  32. package/dist/packages/autonomous/src/api/agent-transfer-routes.d.ts.map +1 -0
  33. package/dist/packages/autonomous/src/api/agent-transfer-routes.js +124 -0
  34. package/dist/packages/autonomous/src/api/apps-routes.d.ts +19 -0
  35. package/dist/packages/autonomous/src/api/apps-routes.d.ts.map +1 -0
  36. package/dist/packages/autonomous/src/api/apps-routes.js +128 -0
  37. package/dist/packages/autonomous/src/api/auth-routes.d.ts +11 -0
  38. package/dist/packages/autonomous/src/api/auth-routes.d.ts.map +1 -0
  39. package/dist/packages/autonomous/src/api/auth-routes.js +54 -0
  40. package/dist/packages/autonomous/src/api/bsc-trade.d.ts +34 -0
  41. package/dist/packages/autonomous/src/api/bsc-trade.d.ts.map +1 -0
  42. package/dist/packages/autonomous/src/api/bsc-trade.js +567 -0
  43. package/dist/packages/autonomous/src/api/bug-report-routes.d.ts +7 -0
  44. package/dist/packages/autonomous/src/api/bug-report-routes.d.ts.map +1 -0
  45. package/dist/packages/autonomous/src/api/bug-report-routes.js +124 -0
  46. package/dist/packages/autonomous/src/api/character-routes.d.ts +50 -0
  47. package/dist/packages/autonomous/src/api/character-routes.d.ts.map +1 -0
  48. package/dist/packages/autonomous/src/api/character-routes.js +302 -0
  49. package/dist/packages/autonomous/src/api/cloud-billing-routes.d.ts +14 -0
  50. package/dist/packages/autonomous/src/api/cloud-billing-routes.d.ts.map +1 -0
  51. package/dist/packages/autonomous/src/api/cloud-billing-routes.js +400 -0
  52. package/dist/packages/autonomous/src/api/cloud-compat-routes.d.ts +15 -0
  53. package/dist/packages/autonomous/src/api/cloud-compat-routes.d.ts.map +1 -0
  54. package/dist/packages/autonomous/src/api/cloud-compat-routes.js +131 -0
  55. package/dist/packages/autonomous/src/api/cloud-routes.d.ts +62 -0
  56. package/dist/packages/autonomous/src/api/cloud-routes.d.ts.map +1 -0
  57. package/dist/packages/autonomous/src/api/cloud-routes.js +339 -0
  58. package/dist/packages/autonomous/src/api/cloud-status-routes.d.ts +15 -0
  59. package/dist/packages/autonomous/src/api/cloud-status-routes.d.ts.map +1 -0
  60. package/dist/packages/autonomous/src/api/cloud-status-routes.js +165 -0
  61. package/dist/packages/autonomous/src/api/compat-utils.d.ts +49 -0
  62. package/dist/packages/autonomous/src/api/compat-utils.d.ts.map +1 -0
  63. package/dist/packages/autonomous/src/api/compat-utils.js +126 -0
  64. package/dist/packages/autonomous/src/api/connector-health.d.ts +34 -0
  65. package/dist/packages/autonomous/src/api/connector-health.d.ts.map +1 -0
  66. package/dist/packages/autonomous/src/api/connector-health.js +109 -0
  67. package/dist/packages/autonomous/src/api/coordinator-wiring.d.ts +46 -0
  68. package/dist/packages/autonomous/src/api/coordinator-wiring.d.ts.map +1 -0
  69. package/dist/packages/autonomous/src/api/coordinator-wiring.js +99 -0
  70. package/dist/packages/autonomous/src/api/credit-detection.d.ts +9 -0
  71. package/dist/packages/autonomous/src/api/credit-detection.d.ts.map +1 -0
  72. package/dist/packages/autonomous/src/api/credit-detection.js +41 -0
  73. package/dist/packages/autonomous/src/api/database.d.ts +33 -0
  74. package/dist/packages/autonomous/src/api/database.d.ts.map +1 -0
  75. package/dist/packages/autonomous/src/api/database.js +1019 -0
  76. package/dist/packages/autonomous/src/api/diagnostics-routes.d.ts +46 -0
  77. package/dist/packages/autonomous/src/api/diagnostics-routes.d.ts.map +1 -0
  78. package/dist/packages/autonomous/src/api/diagnostics-routes.js +241 -0
  79. package/dist/packages/autonomous/src/api/drop-service.d.ts +26 -0
  80. package/dist/packages/autonomous/src/api/drop-service.d.ts.map +1 -0
  81. package/dist/packages/autonomous/src/api/drop-service.js +134 -0
  82. package/dist/packages/autonomous/src/api/early-logs.d.ts +29 -0
  83. package/dist/packages/autonomous/src/api/early-logs.d.ts.map +1 -0
  84. package/dist/packages/autonomous/src/api/early-logs.js +95 -0
  85. package/dist/packages/autonomous/src/api/http-helpers.d.ts +50 -0
  86. package/dist/packages/autonomous/src/api/http-helpers.d.ts.map +1 -0
  87. package/dist/packages/autonomous/src/api/http-helpers.js +145 -0
  88. package/dist/packages/autonomous/src/api/hyperscape-routes-loader.d.ts +12 -0
  89. package/dist/packages/autonomous/src/api/hyperscape-routes-loader.d.ts.map +1 -0
  90. package/dist/packages/autonomous/src/api/hyperscape-routes-loader.js +21 -0
  91. package/dist/packages/autonomous/src/api/index.d.ts +62 -0
  92. package/dist/packages/autonomous/src/api/index.d.ts.map +1 -0
  93. package/dist/packages/autonomous/src/api/index.js +60 -0
  94. package/dist/packages/autonomous/src/api/knowledge-routes.d.ts +23 -0
  95. package/dist/packages/autonomous/src/api/knowledge-routes.d.ts.map +1 -0
  96. package/dist/packages/autonomous/src/api/knowledge-routes.js +887 -0
  97. package/dist/packages/autonomous/src/api/knowledge-service-loader.d.ts +51 -0
  98. package/dist/packages/autonomous/src/api/knowledge-service-loader.d.ts.map +1 -0
  99. package/dist/packages/autonomous/src/api/knowledge-service-loader.js +34 -0
  100. package/dist/packages/autonomous/src/api/memory-bounds.d.ts +51 -0
  101. package/dist/packages/autonomous/src/api/memory-bounds.d.ts.map +1 -0
  102. package/dist/packages/autonomous/src/api/memory-bounds.js +81 -0
  103. package/dist/packages/autonomous/src/api/memory-routes.d.ts +9 -0
  104. package/dist/packages/autonomous/src/api/memory-routes.d.ts.map +1 -0
  105. package/dist/packages/autonomous/src/api/memory-routes.js +241 -0
  106. package/dist/packages/autonomous/src/api/merkle-tree.d.ts +90 -0
  107. package/dist/packages/autonomous/src/api/merkle-tree.d.ts.map +1 -0
  108. package/dist/packages/autonomous/src/api/merkle-tree.js +174 -0
  109. package/dist/packages/autonomous/src/api/models-routes.d.ts +14 -0
  110. package/dist/packages/autonomous/src/api/models-routes.d.ts.map +1 -0
  111. package/dist/packages/autonomous/src/api/models-routes.js +37 -0
  112. package/dist/packages/autonomous/src/api/nfa-routes.d.ts +5 -0
  113. package/dist/packages/autonomous/src/api/nfa-routes.d.ts.map +1 -0
  114. package/dist/packages/autonomous/src/api/nfa-routes.js +125 -0
  115. package/dist/packages/autonomous/src/api/nft-verify.d.ts +35 -0
  116. package/dist/packages/autonomous/src/api/nft-verify.d.ts.map +1 -0
  117. package/dist/packages/autonomous/src/api/nft-verify.js +130 -0
  118. package/dist/packages/autonomous/src/api/og-tracker.d.ts +28 -0
  119. package/dist/packages/autonomous/src/api/og-tracker.d.ts.map +1 -0
  120. package/dist/packages/autonomous/src/api/og-tracker.js +60 -0
  121. package/dist/packages/autonomous/src/api/parse-action-block.d.ts +36 -0
  122. package/dist/packages/autonomous/src/api/parse-action-block.d.ts.map +1 -0
  123. package/dist/packages/autonomous/src/api/parse-action-block.js +110 -0
  124. package/dist/packages/autonomous/src/api/permissions-routes.d.ts +32 -0
  125. package/dist/packages/autonomous/src/api/permissions-routes.d.ts.map +1 -0
  126. package/dist/packages/autonomous/src/api/permissions-routes.js +149 -0
  127. package/dist/packages/autonomous/src/api/plugin-validation.d.ts +86 -0
  128. package/dist/packages/autonomous/src/api/plugin-validation.d.ts.map +1 -0
  129. package/dist/packages/autonomous/src/api/plugin-validation.js +259 -0
  130. package/dist/packages/autonomous/src/api/provider-switch-config.d.ts +20 -0
  131. package/dist/packages/autonomous/src/api/provider-switch-config.d.ts.map +1 -0
  132. package/dist/packages/autonomous/src/api/provider-switch-config.js +33 -0
  133. package/dist/packages/autonomous/src/api/registry-routes.d.ts +30 -0
  134. package/dist/packages/autonomous/src/api/registry-routes.d.ts.map +1 -0
  135. package/dist/packages/autonomous/src/api/registry-routes.js +90 -0
  136. package/dist/packages/autonomous/src/api/registry-service.d.ts +77 -0
  137. package/dist/packages/autonomous/src/api/registry-service.d.ts.map +1 -0
  138. package/dist/packages/autonomous/src/api/registry-service.js +190 -0
  139. package/dist/packages/autonomous/src/api/route-helpers.d.ts +16 -0
  140. package/dist/packages/autonomous/src/api/route-helpers.d.ts.map +1 -0
  141. package/dist/packages/autonomous/src/api/route-helpers.js +1 -0
  142. package/dist/packages/autonomous/src/api/sandbox-routes.d.ts +12 -0
  143. package/dist/packages/autonomous/src/api/sandbox-routes.d.ts.map +1 -0
  144. package/dist/packages/autonomous/src/api/sandbox-routes.js +1334 -0
  145. package/dist/packages/autonomous/src/api/server.d.ts +416 -0
  146. package/dist/packages/autonomous/src/api/server.d.ts.map +1 -0
  147. package/dist/packages/autonomous/src/api/server.js +13467 -0
  148. package/dist/packages/autonomous/src/api/signal-routes.d.ts +41 -0
  149. package/dist/packages/autonomous/src/api/signal-routes.d.ts.map +1 -0
  150. package/dist/packages/autonomous/src/api/signal-routes.js +168 -0
  151. package/dist/packages/autonomous/src/api/stream-persistence.d.ts +64 -0
  152. package/dist/packages/autonomous/src/api/stream-persistence.d.ts.map +1 -0
  153. package/dist/packages/autonomous/src/api/stream-persistence.js +231 -0
  154. package/dist/packages/autonomous/src/api/stream-route-state.d.ts +50 -0
  155. package/dist/packages/autonomous/src/api/stream-route-state.d.ts.map +1 -0
  156. package/dist/packages/autonomous/src/api/stream-route-state.js +1 -0
  157. package/dist/packages/autonomous/src/api/stream-routes.d.ts +45 -0
  158. package/dist/packages/autonomous/src/api/stream-routes.d.ts.map +1 -0
  159. package/dist/packages/autonomous/src/api/stream-routes.js +808 -0
  160. package/dist/packages/autonomous/src/api/stream-voice-routes.d.ts +36 -0
  161. package/dist/packages/autonomous/src/api/stream-voice-routes.d.ts.map +1 -0
  162. package/dist/packages/autonomous/src/api/stream-voice-routes.js +119 -0
  163. package/dist/packages/autonomous/src/api/streaming-text.d.ts +9 -0
  164. package/dist/packages/autonomous/src/api/streaming-text.d.ts.map +1 -0
  165. package/dist/packages/autonomous/src/api/streaming-text.js +85 -0
  166. package/dist/packages/autonomous/src/api/streaming-types.d.ts +30 -0
  167. package/dist/packages/autonomous/src/api/streaming-types.d.ts.map +1 -0
  168. package/dist/packages/autonomous/src/api/streaming-types.js +1 -0
  169. package/dist/packages/autonomous/src/api/subscription-routes.d.ts +41 -0
  170. package/dist/packages/autonomous/src/api/subscription-routes.d.ts.map +1 -0
  171. package/dist/packages/autonomous/src/api/subscription-routes.js +191 -0
  172. package/dist/packages/autonomous/src/api/terminal-run-limits.d.ts +5 -0
  173. package/dist/packages/autonomous/src/api/terminal-run-limits.d.ts.map +1 -0
  174. package/dist/packages/autonomous/src/api/terminal-run-limits.js +22 -0
  175. package/dist/packages/autonomous/src/api/training-backend-check.d.ts +8 -0
  176. package/dist/packages/autonomous/src/api/training-backend-check.d.ts.map +1 -0
  177. package/dist/packages/autonomous/src/api/training-backend-check.js +28 -0
  178. package/dist/packages/autonomous/src/api/training-routes.d.ts +44 -0
  179. package/dist/packages/autonomous/src/api/training-routes.d.ts.map +1 -0
  180. package/dist/packages/autonomous/src/api/training-routes.js +195 -0
  181. package/dist/packages/autonomous/src/api/training-service-like.d.ts +38 -0
  182. package/dist/packages/autonomous/src/api/training-service-like.d.ts.map +1 -0
  183. package/dist/packages/autonomous/src/api/training-service-like.js +1 -0
  184. package/dist/packages/autonomous/src/api/trajectory-routes.d.ts +17 -0
  185. package/dist/packages/autonomous/src/api/trajectory-routes.d.ts.map +1 -0
  186. package/dist/packages/autonomous/src/api/trajectory-routes.js +377 -0
  187. package/dist/packages/autonomous/src/api/trigger-routes.d.ts +75 -0
  188. package/dist/packages/autonomous/src/api/trigger-routes.d.ts.map +1 -0
  189. package/dist/packages/autonomous/src/api/trigger-routes.js +268 -0
  190. package/dist/packages/autonomous/src/api/twitter-verify.d.ts +25 -0
  191. package/dist/packages/autonomous/src/api/twitter-verify.d.ts.map +1 -0
  192. package/dist/packages/autonomous/src/api/twitter-verify.js +168 -0
  193. package/dist/packages/autonomous/src/api/tx-service.d.ts +47 -0
  194. package/dist/packages/autonomous/src/api/tx-service.d.ts.map +1 -0
  195. package/dist/packages/autonomous/src/api/tx-service.js +156 -0
  196. package/dist/packages/autonomous/src/api/wallet-dex-prices.d.ts +43 -0
  197. package/dist/packages/autonomous/src/api/wallet-dex-prices.d.ts.map +1 -0
  198. package/dist/packages/autonomous/src/api/wallet-dex-prices.js +149 -0
  199. package/dist/packages/autonomous/src/api/wallet-evm-balance.d.ts +65 -0
  200. package/dist/packages/autonomous/src/api/wallet-evm-balance.d.ts.map +1 -0
  201. package/dist/packages/autonomous/src/api/wallet-evm-balance.js +662 -0
  202. package/dist/packages/autonomous/src/api/wallet-routes.d.ts +35 -0
  203. package/dist/packages/autonomous/src/api/wallet-routes.d.ts.map +1 -0
  204. package/dist/packages/autonomous/src/api/wallet-routes.js +328 -0
  205. package/dist/packages/autonomous/src/api/wallet-rpc.d.ts +38 -0
  206. package/dist/packages/autonomous/src/api/wallet-rpc.d.ts.map +1 -0
  207. package/dist/packages/autonomous/src/api/wallet-rpc.js +143 -0
  208. package/dist/packages/autonomous/src/api/wallet-trading-profile.d.ts +51 -0
  209. package/dist/packages/autonomous/src/api/wallet-trading-profile.d.ts.map +1 -0
  210. package/dist/packages/autonomous/src/api/wallet-trading-profile.js +547 -0
  211. package/dist/packages/autonomous/src/api/wallet.d.ts +32 -0
  212. package/dist/packages/autonomous/src/api/wallet.d.ts.map +1 -0
  213. package/dist/packages/autonomous/src/api/wallet.js +553 -0
  214. package/dist/packages/autonomous/src/api/whatsapp-routes.d.ts +41 -0
  215. package/dist/packages/autonomous/src/api/whatsapp-routes.d.ts.map +1 -0
  216. package/dist/packages/autonomous/src/api/whatsapp-routes.js +182 -0
  217. package/dist/packages/autonomous/src/api/zip-utils.d.ts +8 -0
  218. package/dist/packages/autonomous/src/api/zip-utils.d.ts.map +1 -0
  219. package/dist/packages/autonomous/src/api/zip-utils.js +115 -0
  220. package/dist/packages/autonomous/src/auth/anthropic.d.ts +25 -0
  221. package/dist/packages/autonomous/src/auth/anthropic.d.ts.map +1 -0
  222. package/dist/packages/autonomous/src/auth/anthropic.js +40 -0
  223. package/dist/packages/autonomous/src/auth/apply-stealth.d.ts +8 -0
  224. package/dist/packages/autonomous/src/auth/apply-stealth.d.ts.map +1 -0
  225. package/dist/packages/autonomous/src/auth/apply-stealth.js +34 -0
  226. package/dist/packages/autonomous/src/auth/claude-code-stealth.d.ts +2 -0
  227. package/dist/packages/autonomous/src/auth/claude-code-stealth.d.ts.map +1 -0
  228. package/dist/packages/autonomous/src/auth/claude-code-stealth.js +104 -0
  229. package/dist/packages/autonomous/src/auth/credentials.d.ts +55 -0
  230. package/dist/packages/autonomous/src/auth/credentials.d.ts.map +1 -0
  231. package/dist/packages/autonomous/src/auth/credentials.js +182 -0
  232. package/dist/packages/autonomous/src/auth/index.d.ts +7 -0
  233. package/dist/packages/autonomous/src/auth/index.d.ts.map +1 -0
  234. package/dist/packages/autonomous/src/auth/index.js +3 -0
  235. package/dist/packages/autonomous/src/auth/openai-codex.d.ts +27 -0
  236. package/dist/packages/autonomous/src/auth/openai-codex.d.ts.map +1 -0
  237. package/dist/packages/autonomous/src/auth/openai-codex.js +72 -0
  238. package/dist/packages/autonomous/src/auth/types.d.ts +18 -0
  239. package/dist/packages/autonomous/src/auth/types.d.ts.map +1 -0
  240. package/dist/packages/autonomous/src/auth/types.js +8 -0
  241. package/dist/packages/autonomous/src/awareness/registry.d.ts +27 -0
  242. package/dist/packages/autonomous/src/awareness/registry.d.ts.map +1 -0
  243. package/dist/packages/autonomous/src/awareness/registry.js +161 -0
  244. package/dist/packages/autonomous/src/bin.d.ts +3 -0
  245. package/dist/packages/autonomous/src/bin.d.ts.map +1 -0
  246. package/dist/packages/autonomous/src/bin.js +6 -0
  247. package/dist/packages/autonomous/src/cli/index.d.ts +2 -0
  248. package/dist/packages/autonomous/src/cli/index.d.ts.map +1 -0
  249. package/dist/packages/autonomous/src/cli/index.js +30 -0
  250. package/dist/packages/autonomous/src/cli/parse-duration.d.ts +5 -0
  251. package/dist/packages/autonomous/src/cli/parse-duration.d.ts.map +1 -0
  252. package/dist/packages/autonomous/src/cli/parse-duration.js +27 -0
  253. package/dist/packages/autonomous/src/cloud/base-url.d.ts +3 -0
  254. package/dist/packages/autonomous/src/cloud/base-url.d.ts.map +1 -0
  255. package/dist/packages/autonomous/src/cloud/base-url.js +40 -0
  256. package/dist/packages/autonomous/src/cloud/validate-url.d.ts +2 -0
  257. package/dist/packages/autonomous/src/cloud/validate-url.d.ts.map +1 -0
  258. package/dist/packages/autonomous/src/cloud/validate-url.js +158 -0
  259. package/dist/packages/autonomous/src/config/character-schema.d.ts +25 -0
  260. package/dist/packages/autonomous/src/config/character-schema.d.ts.map +1 -0
  261. package/dist/packages/autonomous/src/config/character-schema.js +40 -0
  262. package/dist/packages/autonomous/src/config/config.d.ts +9 -0
  263. package/dist/packages/autonomous/src/config/config.d.ts.map +1 -0
  264. package/dist/packages/autonomous/src/config/config.js +119 -0
  265. package/dist/packages/autonomous/src/config/env-vars.d.ts +3 -0
  266. package/dist/packages/autonomous/src/config/env-vars.d.ts.map +1 -0
  267. package/dist/packages/autonomous/src/config/env-vars.js +77 -0
  268. package/dist/packages/autonomous/src/config/includes.d.ts +26 -0
  269. package/dist/packages/autonomous/src/config/includes.d.ts.map +1 -0
  270. package/dist/packages/autonomous/src/config/includes.js +148 -0
  271. package/dist/packages/autonomous/src/config/index.d.ts +16 -0
  272. package/dist/packages/autonomous/src/config/index.d.ts.map +1 -0
  273. package/dist/packages/autonomous/src/config/index.js +15 -0
  274. package/dist/packages/autonomous/src/config/object-utils.d.ts +2 -0
  275. package/dist/packages/autonomous/src/config/object-utils.d.ts.map +1 -0
  276. package/dist/packages/autonomous/src/config/object-utils.js +6 -0
  277. package/dist/packages/autonomous/src/config/paths.d.ts +12 -0
  278. package/dist/packages/autonomous/src/config/paths.d.ts.map +1 -0
  279. package/dist/packages/autonomous/src/config/paths.js +62 -0
  280. package/dist/packages/autonomous/src/config/plugin-auto-enable.d.ts +16 -0
  281. package/dist/packages/autonomous/src/config/plugin-auto-enable.d.ts.map +1 -0
  282. package/dist/packages/autonomous/src/config/plugin-auto-enable.js +384 -0
  283. package/dist/packages/autonomous/src/config/schema.d.ts +87 -0
  284. package/dist/packages/autonomous/src/config/schema.d.ts.map +1 -0
  285. package/dist/packages/autonomous/src/config/schema.js +928 -0
  286. package/dist/packages/autonomous/src/config/telegram-custom-commands.d.ts +25 -0
  287. package/dist/packages/autonomous/src/config/telegram-custom-commands.d.ts.map +1 -0
  288. package/dist/packages/autonomous/src/config/telegram-custom-commands.js +71 -0
  289. package/dist/packages/autonomous/src/config/types.agent-defaults.d.ts +331 -0
  290. package/dist/packages/autonomous/src/config/types.agent-defaults.d.ts.map +1 -0
  291. package/dist/packages/autonomous/src/config/types.agent-defaults.js +1 -0
  292. package/dist/packages/autonomous/src/config/types.agents.d.ts +109 -0
  293. package/dist/packages/autonomous/src/config/types.agents.d.ts.map +1 -0
  294. package/dist/packages/autonomous/src/config/types.agents.js +1 -0
  295. package/dist/packages/autonomous/src/config/types.autonomous.d.ts +3 -0
  296. package/dist/packages/autonomous/src/config/types.autonomous.d.ts.map +1 -0
  297. package/dist/packages/autonomous/src/config/types.autonomous.js +1 -0
  298. package/dist/packages/autonomous/src/config/types.d.ts +8 -0
  299. package/dist/packages/autonomous/src/config/types.d.ts.map +1 -0
  300. package/dist/packages/autonomous/src/config/types.gateway.d.ts +216 -0
  301. package/dist/packages/autonomous/src/config/types.gateway.d.ts.map +1 -0
  302. package/dist/packages/autonomous/src/config/types.gateway.js +1 -0
  303. package/dist/packages/autonomous/src/config/types.hooks.d.ts +107 -0
  304. package/dist/packages/autonomous/src/config/types.hooks.d.ts.map +1 -0
  305. package/dist/packages/autonomous/src/config/types.hooks.js +1 -0
  306. package/dist/packages/autonomous/src/config/types.js +7 -0
  307. package/dist/packages/autonomous/src/config/types.messages.d.ts +176 -0
  308. package/dist/packages/autonomous/src/config/types.messages.d.ts.map +1 -0
  309. package/dist/packages/autonomous/src/config/types.messages.js +1 -0
  310. package/dist/packages/autonomous/src/config/types.milady.d.ts +631 -0
  311. package/dist/packages/autonomous/src/config/types.milady.d.ts.map +1 -0
  312. package/dist/packages/autonomous/src/config/types.milady.js +1 -0
  313. package/dist/packages/autonomous/src/config/types.tools.d.ts +400 -0
  314. package/dist/packages/autonomous/src/config/types.tools.d.ts.map +1 -0
  315. package/dist/packages/autonomous/src/config/types.tools.js +1 -0
  316. package/dist/packages/autonomous/src/config/zod-schema.agent-runtime.d.ts +1062 -0
  317. package/dist/packages/autonomous/src/config/zod-schema.agent-runtime.d.ts.map +1 -0
  318. package/dist/packages/autonomous/src/config/zod-schema.agent-runtime.js +721 -0
  319. package/dist/packages/autonomous/src/config/zod-schema.core.d.ts +1021 -0
  320. package/dist/packages/autonomous/src/config/zod-schema.core.d.ts.map +1 -0
  321. package/dist/packages/autonomous/src/config/zod-schema.core.js +694 -0
  322. package/dist/packages/autonomous/src/config/zod-schema.d.ts +4817 -0
  323. package/dist/packages/autonomous/src/config/zod-schema.d.ts.map +1 -0
  324. package/dist/packages/autonomous/src/config/zod-schema.hooks.d.ts +88 -0
  325. package/dist/packages/autonomous/src/config/zod-schema.hooks.d.ts.map +1 -0
  326. package/dist/packages/autonomous/src/config/zod-schema.hooks.js +133 -0
  327. package/dist/packages/autonomous/src/config/zod-schema.js +779 -0
  328. package/dist/packages/autonomous/src/config/zod-schema.providers-core.d.ts +2976 -0
  329. package/dist/packages/autonomous/src/config/zod-schema.providers-core.d.ts.map +1 -0
  330. package/dist/packages/autonomous/src/config/zod-schema.providers-core.js +1006 -0
  331. package/dist/packages/autonomous/src/config/zod-schema.session.d.ts +183 -0
  332. package/dist/packages/autonomous/src/config/zod-schema.session.d.ts.map +1 -0
  333. package/dist/packages/autonomous/src/config/zod-schema.session.js +86 -0
  334. package/dist/packages/autonomous/src/contracts/apps.d.ts +42 -0
  335. package/dist/packages/autonomous/src/contracts/apps.d.ts.map +1 -0
  336. package/dist/packages/autonomous/src/contracts/apps.js +4 -0
  337. package/dist/packages/autonomous/src/contracts/awareness.d.ts +38 -0
  338. package/dist/packages/autonomous/src/contracts/awareness.d.ts.map +1 -0
  339. package/dist/packages/autonomous/src/contracts/awareness.js +7 -0
  340. package/dist/packages/autonomous/src/contracts/config.d.ts +146 -0
  341. package/dist/packages/autonomous/src/contracts/config.d.ts.map +1 -0
  342. package/dist/packages/autonomous/src/contracts/config.js +4 -0
  343. package/dist/packages/autonomous/src/contracts/drop.d.ts +20 -0
  344. package/dist/packages/autonomous/src/contracts/drop.d.ts.map +1 -0
  345. package/dist/packages/autonomous/src/contracts/drop.js +4 -0
  346. package/dist/packages/autonomous/src/contracts/index.d.ts +9 -0
  347. package/dist/packages/autonomous/src/contracts/index.d.ts.map +1 -0
  348. package/dist/packages/autonomous/src/contracts/index.js +8 -0
  349. package/dist/packages/autonomous/src/contracts/onboarding.d.ts +24 -0
  350. package/dist/packages/autonomous/src/contracts/onboarding.d.ts.map +1 -0
  351. package/dist/packages/autonomous/src/contracts/onboarding.js +4 -0
  352. package/dist/packages/autonomous/src/contracts/permissions.d.ts +35 -0
  353. package/dist/packages/autonomous/src/contracts/permissions.d.ts.map +1 -0
  354. package/dist/packages/autonomous/src/contracts/permissions.js +4 -0
  355. package/dist/packages/autonomous/src/contracts/verification.d.ts +9 -0
  356. package/dist/packages/autonomous/src/contracts/verification.d.ts.map +1 -0
  357. package/dist/packages/autonomous/src/contracts/verification.js +4 -0
  358. package/dist/packages/autonomous/src/contracts/wallet.d.ts +352 -0
  359. package/dist/packages/autonomous/src/contracts/wallet.d.ts.map +1 -0
  360. package/dist/packages/autonomous/src/contracts/wallet.js +4 -0
  361. package/dist/packages/autonomous/src/diagnostics/integration-observability.d.ts +40 -0
  362. package/dist/packages/autonomous/src/diagnostics/integration-observability.d.ts.map +1 -0
  363. package/dist/packages/autonomous/src/diagnostics/integration-observability.js +68 -0
  364. package/dist/packages/autonomous/src/emotes/catalog.d.ts +31 -0
  365. package/dist/packages/autonomous/src/emotes/catalog.d.ts.map +1 -0
  366. package/dist/packages/autonomous/src/emotes/catalog.js +618 -0
  367. package/dist/packages/autonomous/src/hooks/discovery.d.ts +13 -0
  368. package/dist/packages/autonomous/src/hooks/discovery.d.ts.map +1 -0
  369. package/dist/packages/autonomous/src/hooks/discovery.js +184 -0
  370. package/dist/packages/autonomous/src/hooks/eligibility.d.ts +12 -0
  371. package/dist/packages/autonomous/src/hooks/eligibility.d.ts.map +1 -0
  372. package/dist/packages/autonomous/src/hooks/eligibility.js +100 -0
  373. package/dist/packages/autonomous/src/hooks/index.d.ts +3 -0
  374. package/dist/packages/autonomous/src/hooks/index.d.ts.map +1 -0
  375. package/dist/packages/autonomous/src/hooks/index.js +2 -0
  376. package/dist/packages/autonomous/src/hooks/loader.d.ts +34 -0
  377. package/dist/packages/autonomous/src/hooks/loader.d.ts.map +1 -0
  378. package/dist/packages/autonomous/src/hooks/loader.js +176 -0
  379. package/dist/packages/autonomous/src/hooks/registry.d.ts +11 -0
  380. package/dist/packages/autonomous/src/hooks/registry.d.ts.map +1 -0
  381. package/dist/packages/autonomous/src/hooks/registry.js +58 -0
  382. package/dist/packages/autonomous/src/hooks/types.d.ts +104 -0
  383. package/dist/packages/autonomous/src/hooks/types.d.ts.map +1 -0
  384. package/dist/packages/autonomous/src/hooks/types.js +8 -0
  385. package/dist/packages/autonomous/src/index.d.ts +21 -0
  386. package/dist/packages/autonomous/src/index.d.ts.map +1 -0
  387. package/dist/packages/autonomous/src/index.js +20 -0
  388. package/dist/packages/autonomous/src/onboarding-presets.d.ts +62 -0
  389. package/dist/packages/autonomous/src/onboarding-presets.d.ts.map +1 -0
  390. package/dist/packages/autonomous/src/onboarding-presets.js +1340 -0
  391. package/dist/packages/autonomous/src/plugins/custom-rtmp/index.d.ts +12 -0
  392. package/dist/packages/autonomous/src/plugins/custom-rtmp/index.d.ts.map +1 -0
  393. package/dist/packages/autonomous/src/plugins/custom-rtmp/index.js +26 -0
  394. package/dist/packages/autonomous/src/providers/admin-trust.d.ts +4 -0
  395. package/dist/packages/autonomous/src/providers/admin-trust.d.ts.map +1 -0
  396. package/dist/packages/autonomous/src/providers/admin-trust.js +53 -0
  397. package/dist/packages/autonomous/src/providers/session-bridge.d.ts +24 -0
  398. package/dist/packages/autonomous/src/providers/session-bridge.d.ts.map +1 -0
  399. package/dist/packages/autonomous/src/providers/session-bridge.js +85 -0
  400. package/dist/packages/autonomous/src/providers/session-utils.d.ts +20 -0
  401. package/dist/packages/autonomous/src/providers/session-utils.d.ts.map +1 -0
  402. package/dist/packages/autonomous/src/providers/session-utils.js +33 -0
  403. package/dist/packages/autonomous/src/providers/simple-mode.d.ts +4 -0
  404. package/dist/packages/autonomous/src/providers/simple-mode.d.ts.map +1 -0
  405. package/dist/packages/autonomous/src/providers/simple-mode.js +86 -0
  406. package/dist/packages/autonomous/src/providers/ui-catalog.d.ts +3 -0
  407. package/dist/packages/autonomous/src/providers/ui-catalog.d.ts.map +1 -0
  408. package/dist/packages/autonomous/src/providers/ui-catalog.js +123 -0
  409. package/dist/packages/autonomous/src/providers/workspace-provider.d.ts +22 -0
  410. package/dist/packages/autonomous/src/providers/workspace-provider.d.ts.map +1 -0
  411. package/dist/packages/autonomous/src/providers/workspace-provider.js +163 -0
  412. package/dist/packages/autonomous/src/providers/workspace.d.ts +49 -0
  413. package/dist/packages/autonomous/src/providers/workspace.d.ts.map +1 -0
  414. package/dist/packages/autonomous/src/providers/workspace.js +395 -0
  415. package/dist/packages/autonomous/src/runtime/agent-event-service.d.ts +35 -0
  416. package/dist/packages/autonomous/src/runtime/agent-event-service.d.ts.map +1 -0
  417. package/dist/packages/autonomous/src/runtime/agent-event-service.js +15 -0
  418. package/dist/packages/autonomous/src/runtime/autonomous-plugin.d.ts +2 -0
  419. package/dist/packages/autonomous/src/runtime/autonomous-plugin.d.ts.map +1 -0
  420. package/dist/packages/autonomous/src/runtime/autonomous-plugin.js +1 -0
  421. package/dist/packages/autonomous/src/runtime/core-plugins.d.ts +14 -0
  422. package/dist/packages/autonomous/src/runtime/core-plugins.d.ts.map +1 -0
  423. package/dist/packages/autonomous/src/runtime/core-plugins.js +51 -0
  424. package/dist/packages/autonomous/src/runtime/custom-actions.d.ts +40 -0
  425. package/dist/packages/autonomous/src/runtime/custom-actions.d.ts.map +1 -0
  426. package/dist/packages/autonomous/src/runtime/custom-actions.js +454 -0
  427. package/dist/packages/autonomous/src/runtime/eliza.d.ts +200 -0
  428. package/dist/packages/autonomous/src/runtime/eliza.d.ts.map +1 -0
  429. package/dist/packages/autonomous/src/runtime/eliza.js +3767 -0
  430. package/dist/packages/autonomous/src/runtime/embedding-presets.d.ts +19 -0
  431. package/dist/packages/autonomous/src/runtime/embedding-presets.d.ts.map +1 -0
  432. package/dist/packages/autonomous/src/runtime/embedding-presets.js +53 -0
  433. package/dist/packages/autonomous/src/runtime/index.d.ts +9 -0
  434. package/dist/packages/autonomous/src/runtime/index.d.ts.map +1 -0
  435. package/dist/packages/autonomous/src/runtime/index.js +8 -0
  436. package/dist/packages/autonomous/src/runtime/milady-plugin.d.ts +16 -0
  437. package/dist/packages/autonomous/src/runtime/milady-plugin.d.ts.map +1 -0
  438. package/dist/packages/autonomous/src/runtime/milady-plugin.js +128 -0
  439. package/dist/packages/autonomous/src/runtime/onboarding-names.d.ts +11 -0
  440. package/dist/packages/autonomous/src/runtime/onboarding-names.d.ts.map +1 -0
  441. package/dist/packages/autonomous/src/runtime/onboarding-names.js +74 -0
  442. package/dist/packages/autonomous/src/runtime/release-plugin-policy.d.ts +20 -0
  443. package/dist/packages/autonomous/src/runtime/release-plugin-policy.d.ts.map +1 -0
  444. package/dist/packages/autonomous/src/runtime/release-plugin-policy.js +88 -0
  445. package/dist/packages/autonomous/src/runtime/restart.d.ts +45 -0
  446. package/dist/packages/autonomous/src/runtime/restart.d.ts.map +1 -0
  447. package/dist/packages/autonomous/src/runtime/restart.js +45 -0
  448. package/dist/packages/autonomous/src/runtime/trajectory-persistence.d.ts +214 -0
  449. package/dist/packages/autonomous/src/runtime/trajectory-persistence.d.ts.map +1 -0
  450. package/dist/packages/autonomous/src/runtime/trajectory-persistence.js +1835 -0
  451. package/dist/packages/autonomous/src/runtime/version.d.ts +2 -0
  452. package/dist/packages/autonomous/src/runtime/version.d.ts.map +1 -0
  453. package/dist/packages/autonomous/src/runtime/version.js +5 -0
  454. package/dist/packages/autonomous/src/security/audit-log.d.ts +49 -0
  455. package/dist/packages/autonomous/src/security/audit-log.d.ts.map +1 -0
  456. package/dist/packages/autonomous/src/security/audit-log.js +161 -0
  457. package/dist/packages/autonomous/src/security/network-policy.d.ts +6 -0
  458. package/dist/packages/autonomous/src/security/network-policy.d.ts.map +1 -0
  459. package/dist/packages/autonomous/src/security/network-policy.js +85 -0
  460. package/dist/packages/autonomous/src/server/index.d.ts +3 -0
  461. package/dist/packages/autonomous/src/server/index.d.ts.map +1 -0
  462. package/dist/packages/autonomous/src/server/index.js +1 -0
  463. package/dist/packages/autonomous/src/services/agent-export.d.ts +100 -0
  464. package/dist/packages/autonomous/src/services/agent-export.d.ts.map +1 -0
  465. package/dist/packages/autonomous/src/services/agent-export.js +716 -0
  466. package/dist/packages/autonomous/src/services/app-manager.d.ts +34 -0
  467. package/dist/packages/autonomous/src/services/app-manager.d.ts.map +1 -0
  468. package/dist/packages/autonomous/src/services/app-manager.js +543 -0
  469. package/dist/packages/autonomous/src/services/browser-capture.d.ts +39 -0
  470. package/dist/packages/autonomous/src/services/browser-capture.d.ts.map +1 -0
  471. package/dist/packages/autonomous/src/services/browser-capture.js +162 -0
  472. package/dist/packages/autonomous/src/services/coding-agent-context.d.ts +310 -0
  473. package/dist/packages/autonomous/src/services/coding-agent-context.d.ts.map +1 -0
  474. package/dist/packages/autonomous/src/services/coding-agent-context.js +281 -0
  475. package/dist/packages/autonomous/src/services/fallback-training-service.d.ts +78 -0
  476. package/dist/packages/autonomous/src/services/fallback-training-service.d.ts.map +1 -0
  477. package/dist/packages/autonomous/src/services/fallback-training-service.js +126 -0
  478. package/dist/packages/autonomous/src/services/index.d.ts +18 -0
  479. package/dist/packages/autonomous/src/services/index.d.ts.map +1 -0
  480. package/dist/packages/autonomous/src/services/index.js +17 -0
  481. package/dist/packages/autonomous/src/services/mcp-marketplace.d.ts +89 -0
  482. package/dist/packages/autonomous/src/services/mcp-marketplace.d.ts.map +1 -0
  483. package/dist/packages/autonomous/src/services/mcp-marketplace.js +200 -0
  484. package/dist/packages/autonomous/src/services/plugin-manager-types.d.ts +139 -0
  485. package/dist/packages/autonomous/src/services/plugin-manager-types.d.ts.map +1 -0
  486. package/dist/packages/autonomous/src/services/plugin-manager-types.js +18 -0
  487. package/dist/packages/autonomous/src/services/privy-wallets.d.ts +18 -0
  488. package/dist/packages/autonomous/src/services/privy-wallets.d.ts.map +1 -0
  489. package/dist/packages/autonomous/src/services/privy-wallets.js +225 -0
  490. package/dist/packages/autonomous/src/services/registry-client-app-meta.d.ts +6 -0
  491. package/dist/packages/autonomous/src/services/registry-client-app-meta.d.ts.map +1 -0
  492. package/dist/packages/autonomous/src/services/registry-client-app-meta.js +164 -0
  493. package/dist/packages/autonomous/src/services/registry-client-endpoints.d.ts +7 -0
  494. package/dist/packages/autonomous/src/services/registry-client-endpoints.d.ts.map +1 -0
  495. package/dist/packages/autonomous/src/services/registry-client-endpoints.js +183 -0
  496. package/dist/packages/autonomous/src/services/registry-client-local.d.ts +4 -0
  497. package/dist/packages/autonomous/src/services/registry-client-local.d.ts.map +1 -0
  498. package/dist/packages/autonomous/src/services/registry-client-local.js +377 -0
  499. package/dist/packages/autonomous/src/services/registry-client-network.d.ts +9 -0
  500. package/dist/packages/autonomous/src/services/registry-client-network.d.ts.map +1 -0
  501. package/dist/packages/autonomous/src/services/registry-client-network.js +109 -0
  502. package/dist/packages/autonomous/src/services/registry-client-queries.d.ts +15 -0
  503. package/dist/packages/autonomous/src/services/registry-client-queries.d.ts.map +1 -0
  504. package/dist/packages/autonomous/src/services/registry-client-queries.js +150 -0
  505. package/dist/packages/autonomous/src/services/registry-client-types.d.ts +115 -0
  506. package/dist/packages/autonomous/src/services/registry-client-types.d.ts.map +1 -0
  507. package/dist/packages/autonomous/src/services/registry-client-types.js +1 -0
  508. package/dist/packages/autonomous/src/services/registry-client.d.ts +39 -0
  509. package/dist/packages/autonomous/src/services/registry-client.d.ts.map +1 -0
  510. package/dist/packages/autonomous/src/services/registry-client.js +249 -0
  511. package/dist/packages/autonomous/src/services/remote-signing-service.d.ts +58 -0
  512. package/dist/packages/autonomous/src/services/remote-signing-service.d.ts.map +1 -0
  513. package/dist/packages/autonomous/src/services/remote-signing-service.js +185 -0
  514. package/dist/packages/autonomous/src/services/sandbox-engine.d.ts +96 -0
  515. package/dist/packages/autonomous/src/services/sandbox-engine.d.ts.map +1 -0
  516. package/dist/packages/autonomous/src/services/sandbox-engine.js +604 -0
  517. package/dist/packages/autonomous/src/services/sandbox-manager.d.ts +104 -0
  518. package/dist/packages/autonomous/src/services/sandbox-manager.d.ts.map +1 -0
  519. package/dist/packages/autonomous/src/services/sandbox-manager.js +353 -0
  520. package/dist/packages/autonomous/src/services/self-updater.d.ts +21 -0
  521. package/dist/packages/autonomous/src/services/self-updater.d.ts.map +1 -0
  522. package/dist/packages/autonomous/src/services/self-updater.js +162 -0
  523. package/dist/packages/autonomous/src/services/signal-pairing.d.ts +37 -0
  524. package/dist/packages/autonomous/src/services/signal-pairing.d.ts.map +1 -0
  525. package/dist/packages/autonomous/src/services/signal-pairing.js +124 -0
  526. package/dist/packages/autonomous/src/services/signing-policy.d.ts +44 -0
  527. package/dist/packages/autonomous/src/services/signing-policy.d.ts.map +1 -0
  528. package/dist/packages/autonomous/src/services/signing-policy.js +165 -0
  529. package/dist/packages/autonomous/src/services/skill-catalog-client.d.ts +47 -0
  530. package/dist/packages/autonomous/src/services/skill-catalog-client.d.ts.map +1 -0
  531. package/dist/packages/autonomous/src/services/skill-catalog-client.js +130 -0
  532. package/dist/packages/autonomous/src/services/skill-marketplace.d.ts +42 -0
  533. package/dist/packages/autonomous/src/services/skill-marketplace.d.ts.map +1 -0
  534. package/dist/packages/autonomous/src/services/skill-marketplace.js +680 -0
  535. package/dist/packages/autonomous/src/services/stream-manager.d.ts +121 -0
  536. package/dist/packages/autonomous/src/services/stream-manager.d.ts.map +1 -0
  537. package/dist/packages/autonomous/src/services/stream-manager.js +604 -0
  538. package/dist/packages/autonomous/src/services/tts-stream-bridge.d.ts +83 -0
  539. package/dist/packages/autonomous/src/services/tts-stream-bridge.d.ts.map +1 -0
  540. package/dist/packages/autonomous/src/services/tts-stream-bridge.js +349 -0
  541. package/dist/packages/autonomous/src/services/update-checker.d.ts +29 -0
  542. package/dist/packages/autonomous/src/services/update-checker.d.ts.map +1 -0
  543. package/dist/packages/autonomous/src/services/update-checker.js +134 -0
  544. package/dist/packages/autonomous/src/services/version-compat.d.ts +105 -0
  545. package/dist/packages/autonomous/src/services/version-compat.d.ts.map +1 -0
  546. package/dist/packages/autonomous/src/services/version-compat.js +274 -0
  547. package/dist/packages/autonomous/src/services/whatsapp-pairing.d.ts +41 -0
  548. package/dist/packages/autonomous/src/services/whatsapp-pairing.d.ts.map +1 -0
  549. package/dist/packages/autonomous/src/services/whatsapp-pairing.js +209 -0
  550. package/dist/packages/autonomous/src/shared/ui-catalog-prompt.d.ts +52 -0
  551. package/dist/packages/autonomous/src/shared/ui-catalog-prompt.d.ts.map +1 -0
  552. package/dist/packages/autonomous/src/shared/ui-catalog-prompt.js +1028 -0
  553. package/dist/packages/autonomous/src/test-support/process-helpers.d.ts +13 -0
  554. package/dist/packages/autonomous/src/test-support/process-helpers.d.ts.map +1 -0
  555. package/dist/packages/autonomous/src/test-support/process-helpers.js +23 -0
  556. package/dist/packages/autonomous/src/test-support/route-test-helpers.d.ts +37 -0
  557. package/dist/packages/autonomous/src/test-support/route-test-helpers.d.ts.map +1 -0
  558. package/dist/packages/autonomous/src/test-support/route-test-helpers.js +54 -0
  559. package/dist/packages/autonomous/src/test-support/test-helpers.d.ts +77 -0
  560. package/dist/packages/autonomous/src/test-support/test-helpers.d.ts.map +1 -0
  561. package/dist/packages/autonomous/src/test-support/test-helpers.js +210 -0
  562. package/dist/packages/autonomous/src/testing/index.d.ts +4 -0
  563. package/dist/packages/autonomous/src/testing/index.d.ts.map +1 -0
  564. package/dist/packages/autonomous/src/testing/index.js +3 -0
  565. package/dist/packages/autonomous/src/triggers/action.d.ts +3 -0
  566. package/dist/packages/autonomous/src/triggers/action.d.ts.map +1 -0
  567. package/dist/packages/autonomous/src/triggers/action.js +267 -0
  568. package/dist/packages/autonomous/src/triggers/runtime.d.ts +24 -0
  569. package/dist/packages/autonomous/src/triggers/runtime.d.ts.map +1 -0
  570. package/dist/packages/autonomous/src/triggers/runtime.js +319 -0
  571. package/dist/packages/autonomous/src/triggers/scheduling.d.ts +70 -0
  572. package/dist/packages/autonomous/src/triggers/scheduling.d.ts.map +1 -0
  573. package/dist/packages/autonomous/src/triggers/scheduling.js +355 -0
  574. package/dist/packages/autonomous/src/triggers/types.d.ts +115 -0
  575. package/dist/packages/autonomous/src/triggers/types.d.ts.map +1 -0
  576. package/dist/packages/autonomous/src/triggers/types.js +1 -0
  577. package/dist/packages/autonomous/src/utils/exec-safety.d.ts +2 -0
  578. package/dist/packages/autonomous/src/utils/exec-safety.d.ts.map +1 -0
  579. package/dist/packages/autonomous/src/utils/exec-safety.js +21 -0
  580. package/dist/packages/autonomous/src/utils/number-parsing.d.ts +26 -0
  581. package/dist/packages/autonomous/src/utils/number-parsing.d.ts.map +1 -0
  582. package/dist/packages/autonomous/src/utils/number-parsing.js +52 -0
  583. package/dist/packages/autonomous/src/utils/spoken-text.d.ts +2 -0
  584. package/dist/packages/autonomous/src/utils/spoken-text.d.ts.map +1 -0
  585. package/dist/packages/autonomous/src/utils/spoken-text.js +56 -0
  586. package/dist/packages/autonomous/src/version-resolver.d.ts +2 -0
  587. package/dist/packages/autonomous/src/version-resolver.d.ts.map +1 -0
  588. package/dist/packages/autonomous/src/version-resolver.js +50 -0
  589. package/package.json +235 -0
  590. package/src/actions/emote.ts +101 -0
  591. package/src/actions/restart.ts +101 -0
  592. package/src/actions/send-message.ts +168 -0
  593. package/src/actions/stream-control.ts +439 -0
  594. package/src/actions/switch-stream-source.ts +126 -0
  595. package/src/actions/terminal.ts +186 -0
  596. package/src/api/agent-admin-routes.ts +178 -0
  597. package/src/api/agent-lifecycle-routes.ts +120 -0
  598. package/src/api/agent-model.ts +143 -0
  599. package/src/api/agent-transfer-routes.ts +211 -0
  600. package/src/api/apps-routes.ts +207 -0
  601. package/src/api/auth-routes.ts +90 -0
  602. package/src/api/bsc-trade.ts +736 -0
  603. package/src/api/bug-report-routes.ts +161 -0
  604. package/src/api/character-routes.ts +423 -0
  605. package/src/api/cloud-billing-routes.ts +600 -0
  606. package/src/api/cloud-compat-routes.ts +194 -0
  607. package/src/api/cloud-routes.ts +529 -0
  608. package/src/api/cloud-status-routes.ts +234 -0
  609. package/src/api/compat-utils.ts +154 -0
  610. package/src/api/connector-health.ts +135 -0
  611. package/src/api/coordinator-wiring.ts +179 -0
  612. package/src/api/credit-detection.ts +47 -0
  613. package/src/api/database.ts +1357 -0
  614. package/src/api/diagnostics-routes.ts +389 -0
  615. package/src/api/drop-service.ts +205 -0
  616. package/src/api/early-logs.ts +111 -0
  617. package/src/api/http-helpers.ts +252 -0
  618. package/src/api/hyperscape-routes-loader.ts +38 -0
  619. package/src/api/index.ts +81 -0
  620. package/src/api/knowledge-routes.ts +1189 -0
  621. package/src/api/knowledge-service-loader.ts +92 -0
  622. package/src/api/memory-bounds.ts +121 -0
  623. package/src/api/memory-routes.ts +349 -0
  624. package/src/api/merkle-tree.ts +239 -0
  625. package/src/api/models-routes.ts +72 -0
  626. package/src/api/nfa-routes.ts +169 -0
  627. package/src/api/nft-verify.ts +188 -0
  628. package/src/api/og-tracker.ts +72 -0
  629. package/src/api/parse-action-block.ts +145 -0
  630. package/src/api/permissions-routes.ts +222 -0
  631. package/src/api/plugin-validation.ts +355 -0
  632. package/src/api/provider-switch-config.ts +47 -0
  633. package/src/api/registry-routes.ts +165 -0
  634. package/src/api/registry-service.ts +292 -0
  635. package/src/api/route-helpers.ts +21 -0
  636. package/src/api/sandbox-routes.ts +1481 -0
  637. package/src/api/server.ts +17590 -0
  638. package/src/api/signal-routes.ts +265 -0
  639. package/src/api/stream-persistence.ts +297 -0
  640. package/src/api/stream-route-state.ts +48 -0
  641. package/src/api/stream-routes.ts +1052 -0
  642. package/src/api/stream-voice-routes.ts +208 -0
  643. package/src/api/streaming-text.ts +129 -0
  644. package/src/api/streaming-types.ts +23 -0
  645. package/src/api/subscription-routes.ts +283 -0
  646. package/src/api/terminal-run-limits.ts +31 -0
  647. package/src/api/training-backend-check.ts +40 -0
  648. package/src/api/training-routes.ts +314 -0
  649. package/src/api/training-service-like.ts +46 -0
  650. package/src/api/trajectory-routes.ts +714 -0
  651. package/src/api/trigger-routes.ts +444 -0
  652. package/src/api/twitter-verify.ts +226 -0
  653. package/src/api/tx-service.ts +193 -0
  654. package/src/api/wallet-dex-prices.ts +206 -0
  655. package/src/api/wallet-evm-balance.ts +991 -0
  656. package/src/api/wallet-routes.ts +450 -0
  657. package/src/api/wallet-rpc.ts +235 -0
  658. package/src/api/wallet-trading-profile.ts +694 -0
  659. package/src/api/wallet.ts +745 -0
  660. package/src/api/whatsapp-routes.ts +282 -0
  661. package/src/api/zip-utils.ts +130 -0
  662. package/src/auth/anthropic.ts +63 -0
  663. package/src/auth/apply-stealth.ts +38 -0
  664. package/src/auth/claude-code-stealth.ts +141 -0
  665. package/src/auth/credentials.ts +226 -0
  666. package/src/auth/index.ts +18 -0
  667. package/src/auth/openai-codex.ts +94 -0
  668. package/src/auth/types.ts +24 -0
  669. package/src/awareness/registry.ts +220 -0
  670. package/src/bin.ts +10 -0
  671. package/src/cli/index.ts +38 -0
  672. package/src/cli/parse-duration.ts +43 -0
  673. package/src/cloud/base-url.ts +45 -0
  674. package/src/cloud/validate-url.ts +176 -0
  675. package/src/config/character-schema.ts +45 -0
  676. package/src/config/config.ts +153 -0
  677. package/src/config/env-vars.ts +86 -0
  678. package/src/config/includes.ts +196 -0
  679. package/src/config/index.ts +15 -0
  680. package/src/config/object-utils.ts +10 -0
  681. package/src/config/paths.ts +92 -0
  682. package/src/config/plugin-auto-enable.ts +520 -0
  683. package/src/config/schema.ts +1342 -0
  684. package/src/config/telegram-custom-commands.ts +99 -0
  685. package/src/config/types.agent-defaults.ts +342 -0
  686. package/src/config/types.agents.ts +111 -0
  687. package/src/config/types.autonomous.ts +16 -0
  688. package/src/config/types.gateway.ts +243 -0
  689. package/src/config/types.hooks.ts +124 -0
  690. package/src/config/types.messages.ts +201 -0
  691. package/src/config/types.milady.ts +787 -0
  692. package/src/config/types.tools.ts +416 -0
  693. package/src/config/types.ts +7 -0
  694. package/src/config/zod-schema.agent-runtime.ts +777 -0
  695. package/src/config/zod-schema.core.ts +778 -0
  696. package/src/config/zod-schema.hooks.ts +139 -0
  697. package/src/config/zod-schema.providers-core.ts +1126 -0
  698. package/src/config/zod-schema.session.ts +98 -0
  699. package/src/config/zod-schema.ts +866 -0
  700. package/src/contracts/apps.ts +46 -0
  701. package/src/contracts/awareness.ts +56 -0
  702. package/src/contracts/config.ts +172 -0
  703. package/src/contracts/drop.ts +21 -0
  704. package/src/contracts/index.ts +8 -0
  705. package/src/contracts/onboarding.ts +24 -0
  706. package/src/contracts/permissions.ts +52 -0
  707. package/src/contracts/verification.ts +9 -0
  708. package/src/contracts/wallet.ts +389 -0
  709. package/src/diagnostics/integration-observability.ts +132 -0
  710. package/src/emotes/catalog.ts +655 -0
  711. package/src/external-modules.d.ts +7 -0
  712. package/src/hooks/discovery.test.ts +357 -0
  713. package/src/hooks/discovery.ts +231 -0
  714. package/src/hooks/eligibility.ts +146 -0
  715. package/src/hooks/hooks.test.ts +320 -0
  716. package/src/hooks/index.ts +8 -0
  717. package/src/hooks/loader.test.ts +418 -0
  718. package/src/hooks/loader.ts +256 -0
  719. package/src/hooks/registry.test.ts +168 -0
  720. package/src/hooks/registry.ts +74 -0
  721. package/src/hooks/types.ts +121 -0
  722. package/src/index.ts +20 -0
  723. package/src/onboarding-presets.ts +1384 -0
  724. package/src/plugins/custom-rtmp/index.ts +40 -0
  725. package/src/providers/admin-trust.ts +76 -0
  726. package/src/providers/session-bridge.ts +143 -0
  727. package/src/providers/session-utils.ts +42 -0
  728. package/src/providers/simple-mode.ts +113 -0
  729. package/src/providers/ui-catalog.ts +135 -0
  730. package/src/providers/workspace-provider.ts +213 -0
  731. package/src/providers/workspace.ts +497 -0
  732. package/src/runtime/agent-event-service.ts +57 -0
  733. package/src/runtime/autonomous-plugin.ts +4 -0
  734. package/src/runtime/core-plugins.ts +53 -0
  735. package/src/runtime/custom-actions.ts +605 -0
  736. package/src/runtime/eliza.ts +4716 -0
  737. package/src/runtime/embedding-presets.ts +73 -0
  738. package/src/runtime/index.ts +8 -0
  739. package/src/runtime/milady-plugin.ts +180 -0
  740. package/src/runtime/onboarding-names.ts +76 -0
  741. package/src/runtime/release-plugin-policy.ts +119 -0
  742. package/src/runtime/restart.ts +59 -0
  743. package/src/runtime/trajectory-persistence.ts +2584 -0
  744. package/src/runtime/version.ts +6 -0
  745. package/src/security/audit-log.ts +222 -0
  746. package/src/security/network-policy.ts +91 -0
  747. package/src/server/index.ts +2 -0
  748. package/src/services/agent-export.ts +976 -0
  749. package/src/services/app-manager.ts +755 -0
  750. package/src/services/browser-capture.ts +215 -0
  751. package/src/services/coding-agent-context.ts +355 -0
  752. package/src/services/fallback-training-service.ts +196 -0
  753. package/src/services/index.ts +17 -0
  754. package/src/services/mcp-marketplace.ts +327 -0
  755. package/src/services/plugin-manager-types.ts +185 -0
  756. package/src/services/privy-wallets.ts +352 -0
  757. package/src/services/registry-client-app-meta.ts +201 -0
  758. package/src/services/registry-client-endpoints.ts +253 -0
  759. package/src/services/registry-client-local.ts +485 -0
  760. package/src/services/registry-client-network.ts +173 -0
  761. package/src/services/registry-client-queries.ts +176 -0
  762. package/src/services/registry-client-types.ts +104 -0
  763. package/src/services/registry-client.ts +366 -0
  764. package/src/services/remote-signing-service.ts +261 -0
  765. package/src/services/sandbox-engine.ts +753 -0
  766. package/src/services/sandbox-manager.ts +503 -0
  767. package/src/services/self-updater.ts +213 -0
  768. package/src/services/signal-pairing.ts +189 -0
  769. package/src/services/signing-policy.ts +230 -0
  770. package/src/services/skill-catalog-client.ts +195 -0
  771. package/src/services/skill-marketplace.ts +909 -0
  772. package/src/services/stream-manager.ts +707 -0
  773. package/src/services/tts-stream-bridge.ts +465 -0
  774. package/src/services/update-checker.ts +163 -0
  775. package/src/services/version-compat.ts +367 -0
  776. package/src/services/whatsapp-pairing.ts +282 -0
  777. package/src/shared/ui-catalog-prompt.ts +1158 -0
  778. package/src/test-support/process-helpers.ts +35 -0
  779. package/src/test-support/route-test-helpers.ts +113 -0
  780. package/src/test-support/test-helpers.ts +304 -0
  781. package/src/testing/index.ts +3 -0
  782. package/src/triggers/action.ts +342 -0
  783. package/src/triggers/runtime.ts +432 -0
  784. package/src/triggers/scheduling.ts +472 -0
  785. package/src/triggers/types.ts +133 -0
  786. package/src/types/app-hyperscape-routes-shim.d.ts +29 -0
  787. package/src/types/eliza-core-compat.d.ts +122 -0
  788. package/src/types/external-modules.d.ts +9 -0
  789. package/src/utils/exec-safety.ts +23 -0
  790. package/src/utils/number-parsing.ts +112 -0
  791. package/src/utils/spoken-text.ts +65 -0
  792. package/src/version-resolver.ts +60 -0
  793. package/test/api/lifecycle.test.ts +342 -0
  794. package/tsconfig.build.json +21 -0
  795. package/tsconfig.json +19 -0
@@ -0,0 +1,1835 @@
1
+ import { once } from "node:events";
2
+ import { createWriteStream } from "node:fs";
3
+ import fs from "node:fs/promises";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { createGzip } from "node:zlib";
7
+ import { ModelType, Service } from "@elizaos/core";
8
+ const initializedRuntimes = new WeakSet();
9
+ const patchedLoggers = new WeakSet();
10
+ const stepWriteQueues = new WeakMap();
11
+ const lastWritePromises = new WeakMap();
12
+ let cachedSqlRaw = null;
13
+ function asRecord(value) {
14
+ if (!value || typeof value !== "object" || Array.isArray(value))
15
+ return null;
16
+ return value;
17
+ }
18
+ function toText(value, fallback = "") {
19
+ if (typeof value === "string")
20
+ return value;
21
+ if (value === undefined || value === null)
22
+ return fallback;
23
+ return String(value);
24
+ }
25
+ function toNumber(value, fallback = 0) {
26
+ if (typeof value === "number" && Number.isFinite(value))
27
+ return value;
28
+ if (typeof value === "string") {
29
+ const parsed = Number(value);
30
+ if (Number.isFinite(parsed))
31
+ return parsed;
32
+ }
33
+ return fallback;
34
+ }
35
+ function toOptionalNumber(value) {
36
+ if (value === null || value === undefined)
37
+ return undefined;
38
+ const parsed = toNumber(value, Number.NaN);
39
+ return Number.isFinite(parsed) ? parsed : undefined;
40
+ }
41
+ function toOptionalBoolean(value) {
42
+ if (typeof value === "boolean")
43
+ return value;
44
+ if (typeof value === "number")
45
+ return value !== 0;
46
+ if (typeof value !== "string")
47
+ return undefined;
48
+ const normalized = value.trim().toLowerCase();
49
+ if (["1", "true", "yes", "on", "enabled"].includes(normalized))
50
+ return true;
51
+ if (["0", "false", "no", "off", "disabled"].includes(normalized))
52
+ return false;
53
+ return undefined;
54
+ }
55
+ function hasEvaluatorNamed(runtime, name) {
56
+ const runtimeLike = runtime;
57
+ const evaluators = runtimeLike.evaluators;
58
+ if (!Array.isArray(evaluators))
59
+ return false;
60
+ const target = name.trim().toUpperCase();
61
+ return evaluators.some((evaluator) => {
62
+ const evaluatorName = evaluator && typeof evaluator.name === "string"
63
+ ? evaluator.name.trim().toUpperCase()
64
+ : "";
65
+ return evaluatorName === target;
66
+ });
67
+ }
68
+ /** @internal Exported for testing. */
69
+ export function shouldRunObservationExtraction(runtime) {
70
+ const runtimeAny = runtime;
71
+ const explicitSetting = runtimeAny.getSetting?.("TRAJECTORY_OBSERVATION_EXTRACTION");
72
+ const explicitValue = toOptionalBoolean(explicitSetting);
73
+ if (explicitValue !== undefined)
74
+ return explicitValue;
75
+ // Reflection/relationship extraction already derives durable facts from chat.
76
+ // Default to off in that mode to avoid duplicated extraction cost.
77
+ if (hasEvaluatorNamed(runtime, "REFLECTION") ||
78
+ hasEvaluatorNamed(runtime, "RELATIONSHIP_EXTRACTION")) {
79
+ return false;
80
+ }
81
+ return true;
82
+ }
83
+ function readRecordValue(record, keys) {
84
+ for (const key of keys) {
85
+ if (key in record)
86
+ return record[key];
87
+ }
88
+ return undefined;
89
+ }
90
+ function parseJsonValue(value) {
91
+ if (typeof value !== "string")
92
+ return value;
93
+ try {
94
+ return JSON.parse(value);
95
+ }
96
+ catch {
97
+ return value;
98
+ }
99
+ }
100
+ // ---------------------------------------------------------------------------
101
+ // Truncation helpers — cap large text fields to reduce storage/context bloat
102
+ // ---------------------------------------------------------------------------
103
+ const DEFAULT_TRUNCATE_LIMIT = 500;
104
+ /** @internal Exported for testing. */
105
+ export function truncateField(value, limit = DEFAULT_TRUNCATE_LIMIT) {
106
+ if (value.length <= limit * 2)
107
+ return value;
108
+ const removed = value.length - limit * 2;
109
+ return `${value.slice(0, limit)}\n[...truncated ${removed} chars...]\n${value.slice(-limit)}`;
110
+ }
111
+ /** @internal Exported for testing. */
112
+ export function truncateRecord(obj, limit = DEFAULT_TRUNCATE_LIMIT) {
113
+ const serialized = JSON.stringify(obj);
114
+ if (serialized.length <= limit * 2)
115
+ return obj;
116
+ return { _truncated: truncateField(serialized, limit) };
117
+ }
118
+ // ---------------------------------------------------------------------------
119
+ // Insight extraction — pull key decision markers from LLM responses at write
120
+ // time so the feedback loop can read them from metadata without loading full
121
+ // trajectory details.
122
+ // ---------------------------------------------------------------------------
123
+ /** @internal Exported for testing. */
124
+ export function extractInsightsFromResponse(response, purpose) {
125
+ const insights = [];
126
+ const decisionPattern = /DECISION:\s*(.+?)(?:\n|$)/gi;
127
+ let match;
128
+ match = decisionPattern.exec(response);
129
+ while (match !== null) {
130
+ insights.push(match[1].trim());
131
+ match = decisionPattern.exec(response);
132
+ }
133
+ const keyDecisionPattern = /"keyDecision"\s*:\s*"([^"]+)"/g;
134
+ match = keyDecisionPattern.exec(response);
135
+ while (match !== null) {
136
+ insights.push(match[1].trim());
137
+ match = keyDecisionPattern.exec(response);
138
+ }
139
+ if ((purpose === "turn-complete" || purpose === "coordination") &&
140
+ insights.length === 0) {
141
+ const reasoningMatch = response.match(/"reasoning"\s*:\s*"([^"]{20,200})"/);
142
+ if (reasoningMatch)
143
+ insights.push(reasoningMatch[1].trim());
144
+ }
145
+ return insights;
146
+ }
147
+ const OBSERVATION_BUFFER_THRESHOLD = 5;
148
+ const OBSERVATION_FLUSH_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes
149
+ const observationBuffers = new WeakMap();
150
+ const observationFlushTimers = new WeakMap();
151
+ const observationFlushInProgress = new WeakMap();
152
+ const TRAJECTORY_ARCHIVE_DIRNAME = "trajectory-archive";
153
+ function getObservationBuffer(runtime) {
154
+ const key = runtime;
155
+ let buffer = observationBuffers.get(key);
156
+ if (!buffer) {
157
+ buffer = [];
158
+ observationBuffers.set(key, buffer);
159
+ }
160
+ return buffer;
161
+ }
162
+ function resolvePreferredTrajectoryArchiveRoot() {
163
+ const explicitWorkspace = process.env.MILADY_WORKSPACE_DIR?.trim();
164
+ if (explicitWorkspace)
165
+ return explicitWorkspace;
166
+ const workspaceRoot = process.env.MILADY_WORKSPACE_ROOT?.trim();
167
+ if (workspaceRoot)
168
+ return workspaceRoot;
169
+ return path.join(os.homedir(), ".milady", "workspace");
170
+ }
171
+ async function ensureArchiveDirectory(dir) {
172
+ await fs.mkdir(dir, { recursive: true });
173
+ }
174
+ async function resolveTrajectoryArchiveDirectory() {
175
+ const preferred = path.join(resolvePreferredTrajectoryArchiveRoot(), TRAJECTORY_ARCHIVE_DIRNAME);
176
+ try {
177
+ await ensureArchiveDirectory(preferred);
178
+ return preferred;
179
+ }
180
+ catch {
181
+ const fallback = path.join(process.env.TMPDIR || os.tmpdir(), "milady", TRAJECTORY_ARCHIVE_DIRNAME);
182
+ await ensureArchiveDirectory(fallback);
183
+ return fallback;
184
+ }
185
+ }
186
+ /** @internal Exported for testing. */
187
+ export function pushChatExchange(runtime, exchange) {
188
+ const buffer = getObservationBuffer(runtime);
189
+ buffer.push(exchange);
190
+ const key = runtime;
191
+ // Flush on threshold
192
+ if (buffer.length >= OBSERVATION_BUFFER_THRESHOLD) {
193
+ flushObservationBuffer(runtime).catch(() => { });
194
+ return;
195
+ }
196
+ // Set/reset flush timer
197
+ const existing = observationFlushTimers.get(key);
198
+ if (existing)
199
+ clearTimeout(existing);
200
+ observationFlushTimers.set(key, setTimeout(() => {
201
+ flushObservationBuffer(runtime).catch(() => { });
202
+ }, OBSERVATION_FLUSH_INTERVAL_MS));
203
+ }
204
+ const OBSERVATION_EXTRACTION_PROMPT = `You are analyzing recent conversation exchanges between a user and an AI assistant.
205
+ Extract any durable observations about the user that would be useful across future sessions.
206
+
207
+ Categories to look for:
208
+ - Preferences (tools, languages, workflows, communication style)
209
+ - Facts (role, location, projects they work on, tech stack)
210
+ - Standing instructions (things they always/never want)
211
+ - Patterns (recurring topics, how they like to work)
212
+
213
+ Return ONLY a JSON array of short observation strings (max 150 chars each).
214
+ If nothing meaningful is found, return an empty array [].
215
+ Do NOT include observations about the conversation itself, only about the user.
216
+
217
+ Recent exchanges:
218
+ `;
219
+ /** @internal Exported for testing. */
220
+ export async function flushObservationBuffer(runtime) {
221
+ const key = runtime;
222
+ // Prevent concurrent flushes
223
+ if (observationFlushInProgress.get(key))
224
+ return [];
225
+ observationFlushInProgress.set(key, true);
226
+ const buffer = getObservationBuffer(runtime);
227
+ if (buffer.length === 0) {
228
+ observationFlushInProgress.set(key, false);
229
+ return [];
230
+ }
231
+ // Take the current buffer and reset
232
+ const exchanges = buffer.splice(0, buffer.length);
233
+ const timer = observationFlushTimers.get(key);
234
+ if (timer)
235
+ clearTimeout(timer);
236
+ // Build the extraction prompt
237
+ const exchangeText = exchanges
238
+ .map((e, i) => `Exchange ${i + 1}:\nUser: ${e.userPrompt.slice(0, 500)}\nAssistant: ${e.response.slice(0, 500)}`)
239
+ .join("\n\n");
240
+ const prompt = OBSERVATION_EXTRACTION_PROMPT + exchangeText;
241
+ const runtimeAny = runtime;
242
+ try {
243
+ // Tag the call to prevent recursion — appendLlmCall skips observation
244
+ // extraction when orchestratorCtx is set.
245
+ runtimeAny.__orchestratorTrajectoryCtx = {
246
+ source: "orchestrator",
247
+ decisionType: "observation-extraction",
248
+ };
249
+ const result = await runtime.useModel(ModelType.TEXT_SMALL, {
250
+ prompt,
251
+ maxTokens: 512,
252
+ temperature: 0,
253
+ });
254
+ // Parse the JSON response
255
+ const jsonMatch = result.match(/\[[\s\S]*\]/);
256
+ if (!jsonMatch)
257
+ return [];
258
+ const parsed = JSON.parse(jsonMatch[0]);
259
+ if (!Array.isArray(parsed))
260
+ return [];
261
+ const observations = parsed
262
+ .filter((s) => typeof s === "string" && s.length > 0)
263
+ .map((s) => s.slice(0, 150));
264
+ if (observations.length === 0)
265
+ return [];
266
+ // Write observations to the most recent trajectory in the batch
267
+ const lastExchange = exchanges[exchanges.length - 1];
268
+ const trajectory = await loadTrajectoryById(runtime, lastExchange.trajectoryId);
269
+ if (trajectory) {
270
+ const meta = (trajectory.metadata ?? {});
271
+ const existing = Array.isArray(meta.observations)
272
+ ? meta.observations
273
+ : [];
274
+ meta.observations = [...existing, ...observations].slice(-30);
275
+ trajectory.metadata = meta;
276
+ await saveTrajectory(runtime, trajectory);
277
+ }
278
+ return observations;
279
+ }
280
+ catch {
281
+ // Non-critical — observations are best-effort
282
+ return [];
283
+ }
284
+ finally {
285
+ delete runtimeAny.__orchestratorTrajectoryCtx;
286
+ observationFlushInProgress.set(key, false);
287
+ }
288
+ }
289
+ function parseMetadata(value) {
290
+ const parsed = parseJsonValue(value);
291
+ const record = asRecord(parsed);
292
+ return record ?? {};
293
+ }
294
+ function parseSteps(value) {
295
+ const parsed = parseJsonValue(value);
296
+ if (Array.isArray(parsed)) {
297
+ return parsed;
298
+ }
299
+ const record = asRecord(parsed);
300
+ if (!record)
301
+ return [];
302
+ const nested = parseJsonValue(readRecordValue(record, ["steps"]));
303
+ return Array.isArray(nested) ? nested : [];
304
+ }
305
+ function sqlQuote(value) {
306
+ return `'${value.replace(/'/g, "''")}'`;
307
+ }
308
+ function sqlNumber(value) {
309
+ if (typeof value !== "number" || !Number.isFinite(value))
310
+ return "NULL";
311
+ return String(value);
312
+ }
313
+ async function getSqlRaw() {
314
+ if (cachedSqlRaw)
315
+ return cachedSqlRaw;
316
+ const drizzle = (await import("drizzle-orm"));
317
+ cachedSqlRaw = drizzle.sql.raw;
318
+ return cachedSqlRaw;
319
+ }
320
+ function getRuntimeDb(runtime) {
321
+ const runtimeLike = runtime;
322
+ const db = runtimeLike.adapter?.db || runtimeLike.databaseAdapter?.db;
323
+ if (!db || typeof db.execute !== "function")
324
+ return null;
325
+ return db;
326
+ }
327
+ function hasRuntimeDb(runtime) {
328
+ return Boolean(getRuntimeDb(runtime));
329
+ }
330
+ async function executeRawSql(runtime, sqlText) {
331
+ const db = getRuntimeDb(runtime);
332
+ if (!db) {
333
+ throw new Error("runtime database adapter unavailable");
334
+ }
335
+ const raw = await getSqlRaw();
336
+ return db.execute(raw(sqlText));
337
+ }
338
+ /** @internal Exported for testing. */
339
+ export function extractRows(result) {
340
+ if (Array.isArray(result))
341
+ return result;
342
+ const record = asRecord(result);
343
+ if (!record)
344
+ return [];
345
+ return Array.isArray(record.rows) ? record.rows : [];
346
+ }
347
+ /** @internal Exported for testing. */
348
+ export async function computeBySource(runtime) {
349
+ try {
350
+ const result = await executeRawSql(runtime, "SELECT source, count(*) AS cnt FROM trajectories GROUP BY source");
351
+ const rows = extractRows(result);
352
+ const bySource = {};
353
+ for (const row of rows) {
354
+ const r = asRecord(row);
355
+ if (!r)
356
+ continue;
357
+ const src = typeof r.source === "string" ? r.source : "";
358
+ if (src)
359
+ bySource[src] = toNumber(r.cnt, 0);
360
+ }
361
+ return bySource;
362
+ }
363
+ catch {
364
+ return {};
365
+ }
366
+ }
367
+ function warnRuntime(runtime, message, err) {
368
+ const runtimeLike = runtime;
369
+ if (runtimeLike.logger?.warn) {
370
+ runtimeLike.logger.warn({ err, src: "milady", subsystem: "trajectory-db" }, message);
371
+ }
372
+ }
373
+ // Module version - changes on each hot reload, ensuring schema checks run
374
+ const SCHEMA_VERSION = Date.now();
375
+ const schemaVersions = new WeakMap();
376
+ async function ensureTrajectoriesTable(runtime) {
377
+ const key = runtime;
378
+ // Only skip if verified with current module version
379
+ if (schemaVersions.get(key) === SCHEMA_VERSION)
380
+ return true;
381
+ try {
382
+ // First, check if the table exists and has the correct schema
383
+ // by attempting to select all required columns
384
+ let needsRecreate = false;
385
+ try {
386
+ await executeRawSql(runtime, `SELECT trajectory_id, metadata, steps_json, archetype FROM trajectories LIMIT 1`);
387
+ }
388
+ catch {
389
+ // Table doesn't exist or is missing trajectory_id column
390
+ // Try to drop and recreate
391
+ needsRecreate = true;
392
+ console.warn("[trajectory-persistence] Trajectories table missing or has outdated schema, recreating...");
393
+ try {
394
+ await executeRawSql(runtime, `DROP TABLE IF EXISTS trajectories CASCADE`);
395
+ }
396
+ catch (dropErr) {
397
+ console.warn("[trajectory-persistence] Could not drop old table:", dropErr);
398
+ }
399
+ }
400
+ await executeRawSql(runtime, `CREATE TABLE IF NOT EXISTS trajectories (
401
+ id TEXT PRIMARY KEY,
402
+ trajectory_id TEXT,
403
+ agent_id TEXT NOT NULL,
404
+ source TEXT NOT NULL DEFAULT 'runtime',
405
+ status TEXT NOT NULL DEFAULT 'completed',
406
+ start_time BIGINT NOT NULL,
407
+ end_time BIGINT,
408
+ duration_ms BIGINT,
409
+ step_count INTEGER NOT NULL DEFAULT 0,
410
+ llm_call_count INTEGER NOT NULL DEFAULT 0,
411
+ provider_access_count INTEGER NOT NULL DEFAULT 0,
412
+ total_prompt_tokens INTEGER NOT NULL DEFAULT 0,
413
+ total_completion_tokens INTEGER NOT NULL DEFAULT 0,
414
+ total_reward REAL NOT NULL DEFAULT 0,
415
+ steps_json TEXT NOT NULL DEFAULT '[]',
416
+ metadata TEXT NOT NULL DEFAULT '{}',
417
+ created_at TEXT NOT NULL,
418
+ updated_at TEXT NOT NULL,
419
+ episode_length INTEGER,
420
+ ai_judge_reward REAL,
421
+ ai_judge_reasoning TEXT,
422
+ archetype TEXT
423
+ )`);
424
+ // Archive table — lightweight summary rows that persist after TTL pruning
425
+ // deletes the heavy steps_json data from the main table.
426
+ await executeRawSql(runtime, `CREATE TABLE IF NOT EXISTS trajectory_archive (
427
+ id TEXT PRIMARY KEY,
428
+ agent_id TEXT NOT NULL,
429
+ source TEXT NOT NULL DEFAULT 'runtime',
430
+ status TEXT NOT NULL DEFAULT 'completed',
431
+ start_time BIGINT NOT NULL,
432
+ end_time BIGINT,
433
+ duration_ms BIGINT,
434
+ step_count INTEGER NOT NULL DEFAULT 0,
435
+ llm_call_count INTEGER NOT NULL DEFAULT 0,
436
+ provider_access_count INTEGER NOT NULL DEFAULT 0,
437
+ total_prompt_tokens INTEGER NOT NULL DEFAULT 0,
438
+ total_completion_tokens INTEGER NOT NULL DEFAULT 0,
439
+ total_reward REAL NOT NULL DEFAULT 0,
440
+ metadata TEXT NOT NULL DEFAULT '{}',
441
+ observations TEXT NOT NULL DEFAULT '[]',
442
+ archive_blob_path TEXT,
443
+ created_at TEXT NOT NULL,
444
+ updated_at TEXT NOT NULL,
445
+ archived_at TEXT NOT NULL
446
+ )`);
447
+ // Best-effort forward migration for existing archive tables.
448
+ try {
449
+ await executeRawSql(runtime, `ALTER TABLE trajectory_archive ADD COLUMN archive_blob_path TEXT`);
450
+ }
451
+ catch {
452
+ // ignore when column already exists
453
+ }
454
+ if (needsRecreate) {
455
+ console.warn("[trajectory-persistence] Recreated trajectories table with updated schema");
456
+ }
457
+ schemaVersions.set(key, SCHEMA_VERSION);
458
+ initializedRuntimes.add(key);
459
+ return true;
460
+ }
461
+ catch (err) {
462
+ console.error("[trajectory-persistence] ensureTrajectoriesTable error:", err);
463
+ return false;
464
+ }
465
+ }
466
+ function normalizeStatus(value, fallback) {
467
+ const status = toText(value, "").toLowerCase();
468
+ if (status === "active" ||
469
+ status === "completed" ||
470
+ status === "error" ||
471
+ status === "timeout") {
472
+ return status;
473
+ }
474
+ return fallback;
475
+ }
476
+ function normalizeStepId(value) {
477
+ const stepId = toText(value, "").trim();
478
+ return stepId.length > 0 ? stepId : null;
479
+ }
480
+ function normalizeLlmCallPayload(args) {
481
+ if (args.length === 0)
482
+ return null;
483
+ if (typeof args[0] === "string") {
484
+ const stepId = normalizeStepId(args[0]);
485
+ const details = asRecord(args[1]);
486
+ if (!stepId || !details)
487
+ return null;
488
+ return {
489
+ stepId,
490
+ params: {
491
+ ...details,
492
+ stepId,
493
+ },
494
+ };
495
+ }
496
+ const params = asRecord(args[0]);
497
+ if (!params)
498
+ return null;
499
+ const stepId = normalizeStepId(params.stepId);
500
+ if (!stepId)
501
+ return null;
502
+ if (params.stepId === stepId) {
503
+ return {
504
+ stepId,
505
+ params,
506
+ };
507
+ }
508
+ return {
509
+ stepId,
510
+ params: {
511
+ ...params,
512
+ stepId,
513
+ },
514
+ };
515
+ }
516
+ function normalizeProviderAccessPayload(args) {
517
+ if (args.length === 0)
518
+ return null;
519
+ if (typeof args[0] === "string") {
520
+ const stepId = normalizeStepId(args[0]);
521
+ const details = asRecord(args[1]);
522
+ if (!stepId || !details)
523
+ return null;
524
+ return {
525
+ stepId,
526
+ params: {
527
+ ...details,
528
+ stepId,
529
+ },
530
+ };
531
+ }
532
+ const params = asRecord(args[0]);
533
+ if (!params)
534
+ return null;
535
+ const stepId = normalizeStepId(params.stepId);
536
+ if (!stepId)
537
+ return null;
538
+ if (params.stepId === stepId) {
539
+ return {
540
+ stepId,
541
+ params,
542
+ };
543
+ }
544
+ return {
545
+ stepId,
546
+ params: {
547
+ ...params,
548
+ stepId,
549
+ },
550
+ };
551
+ }
552
+ function isNumericVectorString(value) {
553
+ const trimmed = value.trim();
554
+ if (trimmed === "[array]")
555
+ return true;
556
+ if (!trimmed.startsWith("[") || !trimmed.endsWith("]"))
557
+ return false;
558
+ const inner = trimmed.slice(1, -1).trim();
559
+ if (!inner)
560
+ return false;
561
+ const parts = inner
562
+ .split(",")
563
+ .map((part) => part.trim())
564
+ .filter((part) => part.length > 0);
565
+ if (parts.length < 8)
566
+ return false;
567
+ const sampleSize = Math.min(parts.length, 16);
568
+ for (let i = 0; i < sampleSize; i += 1) {
569
+ const numeric = Number(parts[i]);
570
+ if (!Number.isFinite(numeric))
571
+ return false;
572
+ }
573
+ return true;
574
+ }
575
+ function shouldSuppressNoInputEmbeddingCall(params) {
576
+ const model = toText(params.model, "").toLowerCase();
577
+ const actionType = toText(params.actionType, "").toLowerCase();
578
+ const purpose = toText(params.purpose, "").toLowerCase();
579
+ const isEmbedding = model.includes("embed") ||
580
+ actionType.includes("embed") ||
581
+ purpose.includes("embed");
582
+ if (!isEmbedding)
583
+ return false;
584
+ const userPrompt = toText(params.userPrompt ?? params.input, "").trim();
585
+ if (userPrompt.length > 0)
586
+ return false;
587
+ const response = toText(params.response, "");
588
+ if (!response.trim())
589
+ return true;
590
+ return isNumericVectorString(response);
591
+ }
592
+ function isLegacyTrajectoryLogger(logger) {
593
+ return (typeof logger.listTrajectories === "function" &&
594
+ typeof logger.getTrajectoryDetail === "function");
595
+ }
596
+ function resolveTrajectoryLogger(runtime) {
597
+ const runtimeLike = runtime;
598
+ const candidates = [];
599
+ const seen = new Set();
600
+ const push = (candidate) => {
601
+ if (!candidate || typeof candidate !== "object" || seen.has(candidate))
602
+ return;
603
+ seen.add(candidate);
604
+ candidates.push(candidate);
605
+ };
606
+ if (typeof runtimeLike.getServicesByType === "function") {
607
+ const byType = runtimeLike.getServicesByType("trajectory_logger");
608
+ if (Array.isArray(byType)) {
609
+ for (const item of byType)
610
+ push(item);
611
+ }
612
+ else {
613
+ push(byType);
614
+ }
615
+ }
616
+ if (typeof runtimeLike.getService === "function") {
617
+ push(runtimeLike.getService("trajectory_logger"));
618
+ }
619
+ if (candidates.length === 0)
620
+ return null;
621
+ let best = null;
622
+ let bestScore = -1;
623
+ for (const candidate of candidates) {
624
+ let score = 0;
625
+ if (isLegacyTrajectoryLogger(candidate))
626
+ score += 100;
627
+ if (typeof candidate.logLlmCall === "function")
628
+ score += 10;
629
+ if (typeof candidate.logProviderAccess === "function")
630
+ score += 10;
631
+ if (typeof candidate.getLlmCallLogs === "function")
632
+ score += 2;
633
+ if (typeof candidate.getProviderAccessLogs === "function")
634
+ score += 2;
635
+ if (score > bestScore) {
636
+ best = candidate;
637
+ bestScore = score;
638
+ }
639
+ }
640
+ return best;
641
+ }
642
+ function enqueueStepWrite(runtime, stepId, work) {
643
+ const runtimeKey = runtime;
644
+ let perStep = stepWriteQueues.get(runtimeKey);
645
+ if (!perStep) {
646
+ perStep = new Map();
647
+ stepWriteQueues.set(runtimeKey, perStep);
648
+ }
649
+ const previous = perStep.get(stepId) ?? Promise.resolve();
650
+ const current = previous
651
+ .catch(() => undefined)
652
+ .then(work)
653
+ .catch((err) => {
654
+ warnRuntime(runtime, "Failed to write trajectory update to database", err);
655
+ })
656
+ .finally(() => {
657
+ const latest = perStep?.get(stepId);
658
+ if (latest === current) {
659
+ perStep?.delete(stepId);
660
+ }
661
+ });
662
+ perStep.set(stepId, current);
663
+ return current;
664
+ }
665
+ function createBaseTrajectory(stepId, now, source, metadata) {
666
+ const normalizedSource = source?.trim() || "runtime";
667
+ const createdAt = new Date(now).toISOString();
668
+ return {
669
+ id: stepId,
670
+ source: normalizedSource,
671
+ status: "active",
672
+ startTime: now,
673
+ endTime: null,
674
+ steps: [
675
+ {
676
+ stepId,
677
+ stepNumber: 0,
678
+ timestamp: now,
679
+ llmCalls: [],
680
+ providerAccesses: [],
681
+ },
682
+ ],
683
+ metadata: {
684
+ ...(metadata ?? {}),
685
+ },
686
+ totalReward: 0,
687
+ createdAt,
688
+ updatedAt: createdAt,
689
+ };
690
+ }
691
+ function ensureStep(trajectory, stepId, now) {
692
+ let step = trajectory.steps.find((item) => item.stepId === stepId);
693
+ if (!step) {
694
+ step = {
695
+ stepId,
696
+ stepNumber: trajectory.steps.length,
697
+ timestamp: now,
698
+ llmCalls: [],
699
+ providerAccesses: [],
700
+ };
701
+ trajectory.steps.push(step);
702
+ }
703
+ return step;
704
+ }
705
+ function mergeMetadata(existing, incoming) {
706
+ if (!incoming)
707
+ return existing;
708
+ const merged = { ...existing };
709
+ for (const [key, value] of Object.entries(incoming)) {
710
+ if (value !== undefined)
711
+ merged[key] = value;
712
+ }
713
+ return merged;
714
+ }
715
+ function collectTrajectoryTimestamps(trajectory) {
716
+ const timestamps = [trajectory.startTime];
717
+ for (const step of trajectory.steps) {
718
+ timestamps.push(step.timestamp);
719
+ for (const call of step.llmCalls) {
720
+ timestamps.push(call.timestamp);
721
+ }
722
+ for (const access of step.providerAccesses) {
723
+ timestamps.push(access.timestamp);
724
+ }
725
+ }
726
+ return timestamps.filter((value) => Number.isFinite(value));
727
+ }
728
+ function summarizeTrajectory(trajectory) {
729
+ const timestamps = collectTrajectoryTimestamps(trajectory);
730
+ const startTime = timestamps.length > 0 ? Math.min(...timestamps) : Date.now();
731
+ const endTime = timestamps.length > 0 ? Math.max(...timestamps) : startTime;
732
+ let llmCallCount = 0;
733
+ let providerAccessCount = 0;
734
+ let totalPromptTokens = 0;
735
+ let totalCompletionTokens = 0;
736
+ for (const step of trajectory.steps) {
737
+ llmCallCount += step.llmCalls.length;
738
+ providerAccessCount += step.providerAccesses.length;
739
+ for (const call of step.llmCalls) {
740
+ totalPromptTokens += call.promptTokens ?? 0;
741
+ totalCompletionTokens += call.completionTokens ?? 0;
742
+ }
743
+ }
744
+ return {
745
+ startTime,
746
+ endTime,
747
+ llmCallCount,
748
+ providerAccessCount,
749
+ totalPromptTokens,
750
+ totalCompletionTokens,
751
+ };
752
+ }
753
+ async function loadTrajectoryById(runtime, stepId) {
754
+ const safeId = sqlQuote(stepId);
755
+ try {
756
+ const result = await executeRawSql(runtime, `SELECT * FROM trajectories WHERE id = ${safeId} LIMIT 1`);
757
+ const rows = extractRows(result);
758
+ if (rows.length === 0)
759
+ return null;
760
+ const row = asRecord(rows[0]);
761
+ if (!row)
762
+ return null;
763
+ const startTime = toNumber(readRecordValue(row, ["start_time", "startTime"]), Date.now());
764
+ const endTime = toOptionalNumber(readRecordValue(row, ["end_time", "endTime"])) ?? null;
765
+ const steps = parseSteps(readRecordValue(row, ["steps_json", "stepsJson", "steps"]));
766
+ return {
767
+ id: toText(readRecordValue(row, ["id", "trajectory_id", "trajectoryId"]), stepId),
768
+ source: toText(readRecordValue(row, ["source"]), "runtime"),
769
+ status: normalizeStatus(readRecordValue(row, ["status"]), "completed"),
770
+ startTime,
771
+ endTime,
772
+ steps,
773
+ metadata: parseMetadata(readRecordValue(row, ["metadata", "meta"])),
774
+ totalReward: toNumber(readRecordValue(row, ["total_reward", "totalReward"]), 0),
775
+ createdAt: toText(readRecordValue(row, ["created_at", "createdAt"]), new Date(startTime).toISOString()),
776
+ updatedAt: toText(readRecordValue(row, ["updated_at", "updatedAt"]), new Date(endTime ?? startTime).toISOString()),
777
+ };
778
+ }
779
+ catch {
780
+ return null;
781
+ }
782
+ }
783
+ async function saveTrajectory(runtime, trajectory) {
784
+ const summary = summarizeTrajectory(trajectory);
785
+ const isActive = trajectory.status === "active";
786
+ const endTime = isActive ? null : (trajectory.endTime ?? summary.endTime);
787
+ const durationMs = typeof endTime === "number"
788
+ ? Math.max(0, endTime - summary.startTime)
789
+ : null;
790
+ const createdAt = trajectory.createdAt || new Date(summary.startTime).toISOString();
791
+ const updatedAt = trajectory.updatedAt || new Date(endTime ?? summary.endTime).toISOString();
792
+ const sql = `INSERT INTO trajectories (
793
+ id,
794
+ trajectory_id,
795
+ agent_id,
796
+ source,
797
+ status,
798
+ start_time,
799
+ end_time,
800
+ duration_ms,
801
+ step_count,
802
+ llm_call_count,
803
+ provider_access_count,
804
+ total_prompt_tokens,
805
+ total_completion_tokens,
806
+ total_reward,
807
+ steps_json,
808
+ metadata,
809
+ created_at,
810
+ updated_at,
811
+ episode_length
812
+ ) VALUES (
813
+ ${sqlQuote(trajectory.id)},
814
+ ${sqlQuote(trajectory.id)},
815
+ ${sqlQuote(runtime.agentId)},
816
+ ${sqlQuote(trajectory.source)},
817
+ ${sqlQuote(trajectory.status)},
818
+ ${sqlNumber(summary.startTime)},
819
+ ${sqlNumber(endTime)},
820
+ ${sqlNumber(durationMs)},
821
+ ${sqlNumber(trajectory.steps.length)},
822
+ ${sqlNumber(summary.llmCallCount)},
823
+ ${sqlNumber(summary.providerAccessCount)},
824
+ ${sqlNumber(summary.totalPromptTokens)},
825
+ ${sqlNumber(summary.totalCompletionTokens)},
826
+ ${sqlNumber(trajectory.totalReward)},
827
+ ${sqlQuote(JSON.stringify(trajectory.steps))},
828
+ ${sqlQuote(JSON.stringify(trajectory.metadata))},
829
+ ${sqlQuote(createdAt)},
830
+ ${sqlQuote(updatedAt)},
831
+ ${sqlNumber(trajectory.steps.length)}
832
+ )
833
+ ON CONFLICT (id) DO UPDATE SET
834
+ trajectory_id = EXCLUDED.trajectory_id,
835
+ agent_id = EXCLUDED.agent_id,
836
+ source = EXCLUDED.source,
837
+ status = EXCLUDED.status,
838
+ start_time = EXCLUDED.start_time,
839
+ end_time = EXCLUDED.end_time,
840
+ duration_ms = EXCLUDED.duration_ms,
841
+ step_count = EXCLUDED.step_count,
842
+ llm_call_count = EXCLUDED.llm_call_count,
843
+ provider_access_count = EXCLUDED.provider_access_count,
844
+ total_prompt_tokens = EXCLUDED.total_prompt_tokens,
845
+ total_completion_tokens = EXCLUDED.total_completion_tokens,
846
+ total_reward = EXCLUDED.total_reward,
847
+ steps_json = EXCLUDED.steps_json,
848
+ metadata = EXCLUDED.metadata,
849
+ created_at = EXCLUDED.created_at,
850
+ updated_at = EXCLUDED.updated_at,
851
+ episode_length = EXCLUDED.episode_length`;
852
+ try {
853
+ await executeRawSql(runtime, sql);
854
+ return true;
855
+ }
856
+ catch (err) {
857
+ console.error("[trajectory-persistence] saveTrajectory error:", err);
858
+ return false;
859
+ }
860
+ }
861
+ /**
862
+ * Read orchestrator trajectory context from the runtime, if set.
863
+ * The coding agent orchestrator plugin sets `__orchestratorTrajectoryCtx` on
864
+ * the runtime around `useModel()` calls so we can tag them here.
865
+ */
866
+ /** @internal Exported for testing. */
867
+ export function readOrchestratorTrajectoryContext(runtime) {
868
+ if (!runtime || typeof runtime !== "object")
869
+ return undefined;
870
+ const ctx = runtime.__orchestratorTrajectoryCtx;
871
+ if (!ctx || typeof ctx !== "object")
872
+ return undefined;
873
+ const candidate = ctx;
874
+ if (candidate.source !== "orchestrator" ||
875
+ typeof candidate.decisionType !== "string")
876
+ return undefined;
877
+ return candidate;
878
+ }
879
+ async function appendLlmCall(runtime, stepId, params) {
880
+ if (shouldSuppressNoInputEmbeddingCall(params))
881
+ return;
882
+ const now = toNumber(params.timestamp, Date.now());
883
+ const trajectory = (await loadTrajectoryById(runtime, stepId)) ??
884
+ createBaseTrajectory(stepId, now);
885
+ trajectory.source = trajectory.source || "runtime";
886
+ trajectory.status =
887
+ trajectory.status === "active" ? "active" : trajectory.status;
888
+ // Check for orchestrator trajectory context set by the coding agent plugin.
889
+ // When present, it overrides the generic "action" / "runtime.useModel" defaults
890
+ // so orchestrator LLM calls are identifiable in the trajectories viewer.
891
+ const orchestratorCtx = readOrchestratorTrajectoryContext(runtime);
892
+ // Extract insights from the full response and persist them into metadata
893
+ // so the feedback loop can read summaries without loading full details.
894
+ const fullResponse = toText(params.response, "");
895
+ const purpose = orchestratorCtx?.decisionType ?? toText(params.purpose, "action");
896
+ const insights = extractInsightsFromResponse(fullResponse, purpose);
897
+ const step = ensureStep(trajectory, stepId, now);
898
+ const call = {
899
+ callId: toText(params.callId, `${stepId}-call-${step.llmCalls.length + 1}`),
900
+ timestamp: now,
901
+ model: toText(params.model, "unknown"),
902
+ // Keep full prompts/responses for training data fidelity.
903
+ systemPrompt: toText(params.systemPrompt, ""),
904
+ userPrompt: toText(params.userPrompt ?? params.input, ""),
905
+ response: fullResponse,
906
+ temperature: toNumber(params.temperature, 0),
907
+ maxTokens: toNumber(params.maxTokens, 0),
908
+ purpose,
909
+ actionType: orchestratorCtx
910
+ ? "orchestrator.useModel"
911
+ : toText(params.actionType, "runtime.useModel"),
912
+ latencyMs: toNumber(params.latencyMs, 0),
913
+ };
914
+ const promptTokens = toOptionalNumber(params.promptTokens);
915
+ const completionTokens = toOptionalNumber(params.completionTokens);
916
+ if (promptTokens !== undefined)
917
+ call.promptTokens = promptTokens;
918
+ if (completionTokens !== undefined)
919
+ call.completionTokens = completionTokens;
920
+ step.llmCalls.push(call);
921
+ trajectory.startTime = Math.min(trajectory.startTime, now);
922
+ trajectory.endTime = Math.max(trajectory.endTime ?? now, now);
923
+ trajectory.updatedAt = new Date(now).toISOString();
924
+ // Store extracted insights in metadata for lightweight querying
925
+ if (insights.length > 0) {
926
+ const meta = (trajectory.metadata ?? {});
927
+ const existing = Array.isArray(meta.insights)
928
+ ? meta.insights
929
+ : [];
930
+ meta.insights = [...existing, ...insights].slice(-20);
931
+ trajectory.metadata = meta;
932
+ }
933
+ // Buffer chat exchanges for background LLM observation extraction.
934
+ // The buffer flushes after 5 messages or 10 minutes, whichever comes first.
935
+ if (!orchestratorCtx &&
936
+ trajectory.source === "chat" &&
937
+ shouldRunObservationExtraction(runtime)) {
938
+ pushChatExchange(runtime, {
939
+ userPrompt: toText(params.userPrompt ?? params.input, ""),
940
+ response: fullResponse,
941
+ trajectoryId: trajectory.id,
942
+ timestamp: now,
943
+ });
944
+ }
945
+ // Merge orchestrator metadata into trajectory metadata for filtering/display
946
+ if (orchestratorCtx) {
947
+ trajectory.source = "orchestrator";
948
+ const meta = (trajectory.metadata ?? {});
949
+ meta.orchestrator = {
950
+ decisionType: orchestratorCtx.decisionType,
951
+ ...(orchestratorCtx.sessionId && {
952
+ sessionId: orchestratorCtx.sessionId,
953
+ }),
954
+ ...(orchestratorCtx.taskLabel && {
955
+ taskLabel: orchestratorCtx.taskLabel,
956
+ }),
957
+ ...(orchestratorCtx.repo && {
958
+ repo: orchestratorCtx.repo,
959
+ }),
960
+ ...(orchestratorCtx.workdir && {
961
+ workdir: orchestratorCtx.workdir,
962
+ }),
963
+ ...(orchestratorCtx.originalTask && {
964
+ originalTask: orchestratorCtx.originalTask,
965
+ }),
966
+ };
967
+ trajectory.metadata = meta;
968
+ }
969
+ await saveTrajectory(runtime, trajectory);
970
+ }
971
+ async function appendProviderAccess(runtime, stepId, params) {
972
+ const now = toNumber(params.timestamp, Date.now());
973
+ const trajectory = (await loadTrajectoryById(runtime, stepId)) ??
974
+ createBaseTrajectory(stepId, now);
975
+ trajectory.source = trajectory.source || "runtime";
976
+ trajectory.status =
977
+ trajectory.status === "active" ? "active" : trajectory.status;
978
+ const step = ensureStep(trajectory, stepId, now);
979
+ const access = {
980
+ providerId: toText(params.providerId, `${stepId}-provider-${step.providerAccesses.length + 1}`),
981
+ providerName: toText(params.providerName, "unknown"),
982
+ timestamp: now,
983
+ data: truncateRecord(asRecord(params.data) ?? {}),
984
+ query: (() => {
985
+ const queryRecord = asRecord(params.query);
986
+ return queryRecord ? truncateRecord(queryRecord) : undefined;
987
+ })(),
988
+ purpose: toText(params.purpose, "provider"),
989
+ };
990
+ step.providerAccesses.push(access);
991
+ trajectory.startTime = Math.min(trajectory.startTime, now);
992
+ trajectory.endTime = Math.max(trajectory.endTime ?? now, now);
993
+ trajectory.updatedAt = new Date(now).toISOString();
994
+ await saveTrajectory(runtime, trajectory);
995
+ }
996
+ export function installDatabaseTrajectoryLogger(runtime) {
997
+ if (!hasRuntimeDb(runtime)) {
998
+ console.warn("[trajectory-persistence] installDatabaseTrajectoryLogger: no database adapter found on runtime");
999
+ return;
1000
+ }
1001
+ const logger = resolveTrajectoryLogger(runtime);
1002
+ if (!logger) {
1003
+ console.warn("[trajectory-persistence] installDatabaseTrajectoryLogger: no logger found to patch");
1004
+ return;
1005
+ }
1006
+ console.warn("[trajectory-persistence] installDatabaseTrajectoryLogger: patched logger!");
1007
+ const loggerObject = logger;
1008
+ if (patchedLoggers.has(loggerObject))
1009
+ return;
1010
+ const shouldEnableByDefault = shouldEnableTrajectoryLoggingByDefault();
1011
+ const isEnabled = typeof logger.isEnabled === "function"
1012
+ ? logger.isEnabled()
1013
+ : shouldEnableByDefault;
1014
+ if (typeof logger.setEnabled === "function" &&
1015
+ isEnabled !== shouldEnableByDefault) {
1016
+ try {
1017
+ logger.setEnabled(shouldEnableByDefault);
1018
+ }
1019
+ catch {
1020
+ // Ignore logger enable failures and continue.
1021
+ }
1022
+ }
1023
+ if (Array.isArray(logger.llmCalls)) {
1024
+ logger.llmCalls.splice(0, logger.llmCalls.length);
1025
+ }
1026
+ if (Array.isArray(logger.providerAccess)) {
1027
+ logger.providerAccess.splice(0, logger.providerAccess.length);
1028
+ }
1029
+ const originalLogLlmCall = typeof logger.logLlmCall === "function"
1030
+ ? logger.logLlmCall.bind(logger)
1031
+ : null;
1032
+ const originalLogProviderAccess = typeof logger.logProviderAccess === "function"
1033
+ ? logger.logProviderAccess.bind(logger)
1034
+ : null;
1035
+ logger.logLlmCall = ((...args) => {
1036
+ if (originalLogLlmCall) {
1037
+ try {
1038
+ originalLogLlmCall(...args);
1039
+ }
1040
+ catch (err) {
1041
+ warnRuntime(runtime, "Trajectory logger logLlmCall threw", err);
1042
+ }
1043
+ }
1044
+ const normalized = normalizeLlmCallPayload(args);
1045
+ if (!normalized)
1046
+ return;
1047
+ const writePromise = enqueueStepWrite(runtime, normalized.stepId, async () => {
1048
+ const tableReady = await ensureTrajectoriesTable(runtime);
1049
+ if (!tableReady)
1050
+ return;
1051
+ await appendLlmCall(runtime, normalized.stepId, normalized.params);
1052
+ });
1053
+ const runtimeKey = runtime;
1054
+ lastWritePromises.set(runtimeKey, writePromise);
1055
+ });
1056
+ logger.logProviderAccess = ((...args) => {
1057
+ if (originalLogProviderAccess) {
1058
+ try {
1059
+ originalLogProviderAccess(...args);
1060
+ }
1061
+ catch (err) {
1062
+ warnRuntime(runtime, "Trajectory logger logProviderAccess threw", err);
1063
+ }
1064
+ }
1065
+ const normalized = normalizeProviderAccessPayload(args);
1066
+ if (!normalized)
1067
+ return;
1068
+ const writePromise = enqueueStepWrite(runtime, normalized.stepId, async () => {
1069
+ const tableReady = await ensureTrajectoriesTable(runtime);
1070
+ if (!tableReady)
1071
+ return;
1072
+ await appendProviderAccess(runtime, normalized.stepId, normalized.params);
1073
+ });
1074
+ const runtimeKey = runtime;
1075
+ lastWritePromises.set(runtimeKey, writePromise);
1076
+ });
1077
+ logger.getLlmCallLogs = () => [];
1078
+ logger.getProviderAccessLogs = () => [];
1079
+ // Add startTrajectory, startStep, endTrajectory methods expected by plugin-trajectory-logger
1080
+ // and query methods for API endpoints
1081
+ const loggerAny = logger;
1082
+ loggerAny.startTrajectory = async (stepIdOrAgentId, options) => {
1083
+ const isLegacySignature = typeof options?.agentId === "string";
1084
+ const stepId = isLegacySignature
1085
+ ? stepIdOrAgentId
1086
+ : `step-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1087
+ const writePromise = enqueueStepWrite(runtime, stepId, async () => {
1088
+ const tableReady = await ensureTrajectoriesTable(runtime);
1089
+ if (!tableReady)
1090
+ return;
1091
+ await startTrajectoryStepInDatabase({
1092
+ runtime,
1093
+ stepId,
1094
+ source: options?.source ?? "chat",
1095
+ metadata: options?.metadata,
1096
+ });
1097
+ });
1098
+ const runtimeKey = runtime;
1099
+ lastWritePromises.set(runtimeKey, writePromise);
1100
+ return stepId;
1101
+ };
1102
+ loggerAny.startStep = (_trajectoryId) => {
1103
+ return `step-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1104
+ };
1105
+ loggerAny.endTrajectory = async (stepIdOrTrajectoryId, status = "completed") => {
1106
+ const writePromise = enqueueStepWrite(runtime, stepIdOrTrajectoryId, async () => {
1107
+ const tableReady = await ensureTrajectoriesTable(runtime);
1108
+ if (!tableReady)
1109
+ return;
1110
+ await completeTrajectoryStepInDatabase({
1111
+ runtime,
1112
+ stepId: stepIdOrTrajectoryId,
1113
+ status: status,
1114
+ });
1115
+ });
1116
+ const runtimeKey = runtime;
1117
+ lastWritePromises.set(runtimeKey, writePromise);
1118
+ };
1119
+ // Add query methods for API endpoints
1120
+ loggerAny.listTrajectories = async (options = {}) => {
1121
+ if (!hasRuntimeDb(runtime)) {
1122
+ return { trajectories: [], total: 0, offset: 0, limit: 50 };
1123
+ }
1124
+ const tableReady = await ensureTrajectoriesTable(runtime);
1125
+ if (!tableReady) {
1126
+ return { trajectories: [], total: 0, offset: 0, limit: 50 };
1127
+ }
1128
+ const limit = Math.min(500, Math.max(1, options.limit ?? 50));
1129
+ const offset = Math.max(0, options.offset ?? 0);
1130
+ const whereClauses = [];
1131
+ if (options.source) {
1132
+ whereClauses.push(`source = ${sqlQuote(options.source)}`);
1133
+ }
1134
+ if (options.status) {
1135
+ whereClauses.push(`status = ${sqlQuote(options.status)}`);
1136
+ }
1137
+ if (options.startDate) {
1138
+ const startTime = new Date(options.startDate).getTime();
1139
+ if (Number.isFinite(startTime)) {
1140
+ whereClauses.push(`start_time >= ${startTime}`);
1141
+ }
1142
+ }
1143
+ if (options.endDate) {
1144
+ const endTime = new Date(options.endDate).getTime();
1145
+ if (Number.isFinite(endTime)) {
1146
+ whereClauses.push(`start_time <= ${endTime}`);
1147
+ }
1148
+ }
1149
+ if (options.search) {
1150
+ const searchPattern = `%${options.search.replace(/[%_]/g, "\\$&")}%`;
1151
+ whereClauses.push(`id LIKE ${sqlQuote(searchPattern)}`);
1152
+ }
1153
+ const whereClause = whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
1154
+ try {
1155
+ const countResult = await executeRawSql(runtime, `SELECT count(*) AS total FROM trajectories ${whereClause}`);
1156
+ const countRow = asRecord(extractRows(countResult)[0]);
1157
+ const total = toNumber(countRow?.total, 0);
1158
+ const result = await executeRawSql(runtime, `SELECT * FROM trajectories ${whereClause} ORDER BY created_at DESC LIMIT ${limit} OFFSET ${offset}`);
1159
+ const rows = extractRows(result);
1160
+ const trajectories = rows
1161
+ .map((row) => {
1162
+ const r = asRecord(row);
1163
+ if (!r)
1164
+ return null;
1165
+ return {
1166
+ id: toText(r.id ?? r.trajectory_id, ""),
1167
+ agentId: toText(r.agent_id, runtime.agentId),
1168
+ source: toText(r.source, "runtime"),
1169
+ status: normalizeStatus(r.status, "completed"),
1170
+ startTime: toNumber(r.start_time, Date.now()),
1171
+ endTime: toOptionalNumber(r.end_time) ?? null,
1172
+ durationMs: toOptionalNumber(r.duration_ms) ?? null,
1173
+ stepCount: toNumber(r.step_count, 0),
1174
+ llmCallCount: toNumber(r.llm_call_count, 0),
1175
+ providerAccessCount: toNumber(r.provider_access_count, 0),
1176
+ totalPromptTokens: toNumber(r.total_prompt_tokens, 0),
1177
+ totalCompletionTokens: toNumber(r.total_completion_tokens, 0),
1178
+ createdAt: toText(r.created_at, new Date(toNumber(r.start_time, Date.now())).toISOString()),
1179
+ metadata: parseMetadata(r.metadata),
1180
+ };
1181
+ })
1182
+ .filter(Boolean);
1183
+ return { trajectories, total, offset, limit };
1184
+ }
1185
+ catch (err) {
1186
+ console.error("[trajectory-persistence] listTrajectories error:", err);
1187
+ return { trajectories: [], total: 0, offset, limit };
1188
+ }
1189
+ };
1190
+ loggerAny.getTrajectoryDetail = async (trajectoryId) => {
1191
+ if (!hasRuntimeDb(runtime))
1192
+ return null;
1193
+ const tableReady = await ensureTrajectoriesTable(runtime);
1194
+ if (!tableReady)
1195
+ return null;
1196
+ const persisted = await loadTrajectoryById(runtime, trajectoryId);
1197
+ if (!persisted)
1198
+ return null;
1199
+ return {
1200
+ trajectoryId: persisted.id,
1201
+ agentId: runtime.agentId,
1202
+ startTime: persisted.startTime,
1203
+ endTime: persisted.endTime ?? undefined,
1204
+ durationMs: persisted.endTime
1205
+ ? persisted.endTime - persisted.startTime
1206
+ : undefined,
1207
+ steps: persisted.steps.map((step) => ({
1208
+ stepId: step.stepId,
1209
+ timestamp: step.timestamp,
1210
+ llmCalls: step.llmCalls,
1211
+ providerAccesses: step.providerAccesses,
1212
+ })),
1213
+ metrics: { finalStatus: persisted.status },
1214
+ metadata: persisted.metadata,
1215
+ stepsJson: JSON.stringify(persisted.steps),
1216
+ };
1217
+ };
1218
+ loggerAny.getStats = async () => {
1219
+ if (!hasRuntimeDb(runtime)) {
1220
+ return { total: 0, byStatus: {}, bySource: {} };
1221
+ }
1222
+ const tableReady = await ensureTrajectoriesTable(runtime);
1223
+ if (!tableReady) {
1224
+ return { total: 0, byStatus: {}, bySource: {} };
1225
+ }
1226
+ try {
1227
+ const countResult = await executeRawSql(runtime, "SELECT count(*) AS total FROM trajectories");
1228
+ const countRow = asRecord(extractRows(countResult)[0]);
1229
+ const total = toNumber(countRow?.total, 0);
1230
+ const bySource = await computeBySource(runtime);
1231
+ return {
1232
+ total,
1233
+ enabled: true,
1234
+ byStatus: {},
1235
+ bySource,
1236
+ };
1237
+ }
1238
+ catch {
1239
+ return { total: 0, byStatus: {}, bySource: {} };
1240
+ }
1241
+ };
1242
+ patchedLoggers.add(loggerObject);
1243
+ void ensureTrajectoriesTable(runtime);
1244
+ }
1245
+ export async function startTrajectoryStepInDatabase({ runtime, stepId, source, metadata, }) {
1246
+ if (!hasRuntimeDb(runtime))
1247
+ return false;
1248
+ const normalizedStepId = normalizeStepId(stepId);
1249
+ if (!normalizedStepId)
1250
+ return false;
1251
+ const tableReady = await ensureTrajectoriesTable(runtime);
1252
+ if (!tableReady)
1253
+ return false;
1254
+ await enqueueStepWrite(runtime, normalizedStepId, async () => {
1255
+ const now = Date.now();
1256
+ const trajectory = (await loadTrajectoryById(runtime, normalizedStepId)) ??
1257
+ createBaseTrajectory(normalizedStepId, now, source, metadata);
1258
+ trajectory.source = source?.trim() || trajectory.source || "runtime";
1259
+ trajectory.status = "active";
1260
+ trajectory.metadata = mergeMetadata(trajectory.metadata, metadata);
1261
+ trajectory.startTime = Math.min(trajectory.startTime, now);
1262
+ trajectory.endTime = null;
1263
+ ensureStep(trajectory, normalizedStepId, now);
1264
+ trajectory.updatedAt = new Date(now).toISOString();
1265
+ await saveTrajectory(runtime, trajectory);
1266
+ });
1267
+ return true;
1268
+ }
1269
+ export async function completeTrajectoryStepInDatabase({ runtime, stepId, status = "completed", source, metadata, }) {
1270
+ if (!hasRuntimeDb(runtime))
1271
+ return false;
1272
+ const normalizedStepId = normalizeStepId(stepId);
1273
+ if (!normalizedStepId)
1274
+ return false;
1275
+ const tableReady = await ensureTrajectoriesTable(runtime);
1276
+ if (!tableReady)
1277
+ return false;
1278
+ await enqueueStepWrite(runtime, normalizedStepId, async () => {
1279
+ const now = Date.now();
1280
+ const trajectory = (await loadTrajectoryById(runtime, normalizedStepId)) ??
1281
+ createBaseTrajectory(normalizedStepId, now, source, metadata);
1282
+ trajectory.source = source?.trim() || trajectory.source || "runtime";
1283
+ trajectory.status = normalizeStatus(status, "completed");
1284
+ trajectory.metadata = mergeMetadata(trajectory.metadata, metadata);
1285
+ trajectory.endTime = Math.max(trajectory.endTime ?? now, now);
1286
+ trajectory.startTime = Math.min(trajectory.startTime, now);
1287
+ ensureStep(trajectory, normalizedStepId, now);
1288
+ trajectory.updatedAt = new Date(now).toISOString();
1289
+ await saveTrajectory(runtime, trajectory);
1290
+ });
1291
+ return true;
1292
+ }
1293
+ export async function loadPersistedTrajectoryRows(runtime, maxRows = 5000) {
1294
+ if (!hasRuntimeDb(runtime))
1295
+ return null;
1296
+ const tableReady = await ensureTrajectoriesTable(runtime);
1297
+ if (!tableReady)
1298
+ return [];
1299
+ const safeLimit = Math.max(1, Math.min(10000, Math.trunc(maxRows)));
1300
+ try {
1301
+ const result = await executeRawSql(runtime, `SELECT * FROM trajectories ORDER BY created_at DESC LIMIT ${safeLimit}`);
1302
+ const rows = extractRows(result);
1303
+ return rows
1304
+ .map((row) => asRecord(row))
1305
+ .filter((row) => Boolean(row));
1306
+ }
1307
+ catch {
1308
+ return null;
1309
+ }
1310
+ }
1311
+ export async function deletePersistedTrajectoryRows(runtime, trajectoryIds) {
1312
+ if (!hasRuntimeDb(runtime))
1313
+ return null;
1314
+ const tableReady = await ensureTrajectoriesTable(runtime);
1315
+ if (!tableReady)
1316
+ return 0;
1317
+ const normalized = trajectoryIds
1318
+ .map((id) => id.trim())
1319
+ .filter((id) => id.length > 0);
1320
+ if (normalized.length === 0)
1321
+ return 0;
1322
+ const values = normalized.map((id) => sqlQuote(id)).join(", ");
1323
+ try {
1324
+ const result = await executeRawSql(runtime, `DELETE FROM trajectories WHERE id IN (${values}) RETURNING id`);
1325
+ return extractRows(result).length;
1326
+ }
1327
+ catch {
1328
+ try {
1329
+ await executeRawSql(runtime, `DELETE FROM trajectories WHERE id IN (${values})`);
1330
+ return normalized.length;
1331
+ }
1332
+ catch {
1333
+ return null;
1334
+ }
1335
+ }
1336
+ }
1337
+ export async function clearPersistedTrajectoryRows(runtime) {
1338
+ if (!hasRuntimeDb(runtime))
1339
+ return null;
1340
+ const tableReady = await ensureTrajectoriesTable(runtime);
1341
+ if (!tableReady)
1342
+ return 0;
1343
+ try {
1344
+ const countResult = await executeRawSql(runtime, "SELECT count(*) AS total FROM trajectories");
1345
+ const countRow = asRecord(extractRows(countResult)[0]);
1346
+ const total = toNumber(countRow?.total, 0);
1347
+ await executeRawSql(runtime, "DELETE FROM trajectories");
1348
+ return total;
1349
+ }
1350
+ catch {
1351
+ return null;
1352
+ }
1353
+ }
1354
+ function toArchiveSafeTimestamp(isoTimestamp) {
1355
+ return isoTimestamp.replace(/[:.]/g, "-");
1356
+ }
1357
+ function stringifyArchiveRow(row) {
1358
+ return JSON.stringify(row, (_key, value) => typeof value === "bigint" ? value.toString() : value);
1359
+ }
1360
+ async function writeCompressedJsonlRows(archivePath, rows) {
1361
+ const gzipStream = createGzip({ level: 9 });
1362
+ const outStream = createWriteStream(archivePath);
1363
+ gzipStream.pipe(outStream);
1364
+ for (const row of rows) {
1365
+ if (!gzipStream.write(`${stringifyArchiveRow(row)}\n`, "utf8")) {
1366
+ await once(gzipStream, "drain");
1367
+ }
1368
+ }
1369
+ gzipStream.end();
1370
+ await once(outStream, "finish");
1371
+ }
1372
+ async function exportRawTrajectoriesToCompressedArchive(runtime, cutoff, archivedAt) {
1373
+ const rawRowsResult = await executeRawSql(runtime, `SELECT
1374
+ id, trajectory_id, agent_id, source, status, start_time, end_time,
1375
+ duration_ms, step_count, llm_call_count, provider_access_count,
1376
+ total_prompt_tokens, total_completion_tokens, total_reward, steps_json,
1377
+ metadata, created_at, updated_at, episode_length, ai_judge_reward,
1378
+ ai_judge_reasoning, archetype
1379
+ FROM trajectories
1380
+ WHERE created_at < ${sqlQuote(cutoff)}`);
1381
+ const rawRows = extractRows(rawRowsResult)
1382
+ .map((row) => asRecord(row))
1383
+ .filter(Boolean);
1384
+ if (rawRows.length === 0) {
1385
+ return { archivePath: "", rowCount: 0 };
1386
+ }
1387
+ const archiveDir = await resolveTrajectoryArchiveDirectory();
1388
+ const archiveName = `trajectories-before-${toArchiveSafeTimestamp(cutoff)}-archived-${toArchiveSafeTimestamp(archivedAt)}.jsonl.gz`;
1389
+ const archivePath = path.join(archiveDir, archiveName);
1390
+ await writeCompressedJsonlRows(archivePath, rawRows);
1391
+ return { archivePath, rowCount: rawRows.length };
1392
+ }
1393
+ /**
1394
+ * Archive and then delete trajectories older than `maxAgeDays`.
1395
+ * Summary rows (without steps_json) are copied to `trajectory_archive`
1396
+ * before the heavy raw data is removed. Returns the number of rows
1397
+ * pruned, or null if the DB is unavailable.
1398
+ */
1399
+ export async function pruneOldTrajectories(runtime, maxAgeDays = 30) {
1400
+ if (!hasRuntimeDb(runtime))
1401
+ return null;
1402
+ const tableReady = await ensureTrajectoriesTable(runtime);
1403
+ if (!tableReady)
1404
+ return 0;
1405
+ const cutoff = new Date(Date.now() - maxAgeDays * 24 * 60 * 60 * 1000).toISOString();
1406
+ const archivedAt = new Date().toISOString();
1407
+ try {
1408
+ // Step 1: Persist full training rows to compressed local archive.
1409
+ // If this fails, abort pruning to avoid data loss.
1410
+ let archivePath = "";
1411
+ try {
1412
+ const archived = await exportRawTrajectoriesToCompressedArchive(runtime, cutoff, archivedAt);
1413
+ archivePath = archived.archivePath;
1414
+ if (archived.rowCount > 0 && !archivePath) {
1415
+ return 0;
1416
+ }
1417
+ }
1418
+ catch (err) {
1419
+ console.warn("[trajectory-persistence] Could not write compressed trajectory archive, skipping prune", err);
1420
+ return null;
1421
+ }
1422
+ // Step 2: Copy summary rows to archive table (idempotent).
1423
+ // This must succeed before deletion to preserve the summary index contract.
1424
+ let summaryArchived = false;
1425
+ try {
1426
+ await executeRawSql(runtime, `INSERT OR IGNORE INTO trajectory_archive (
1427
+ id, agent_id, source, status, start_time, end_time, duration_ms,
1428
+ step_count, llm_call_count, provider_access_count,
1429
+ total_prompt_tokens, total_completion_tokens, total_reward,
1430
+ metadata, observations, archive_blob_path, created_at, updated_at, archived_at
1431
+ )
1432
+ SELECT
1433
+ id, agent_id, source, status, start_time, end_time, duration_ms,
1434
+ step_count, llm_call_count, provider_access_count,
1435
+ total_prompt_tokens, total_completion_tokens, total_reward,
1436
+ metadata,
1437
+ COALESCE(json_extract(metadata, '$.observations'), '[]'),
1438
+ ${sqlQuote(archivePath)},
1439
+ created_at, updated_at,
1440
+ ${sqlQuote(archivedAt)}
1441
+ FROM trajectories
1442
+ WHERE created_at < ${sqlQuote(cutoff)}`);
1443
+ summaryArchived = true;
1444
+ }
1445
+ catch {
1446
+ // PostgreSQL uses ON CONFLICT DO NOTHING instead of INSERT OR IGNORE
1447
+ try {
1448
+ await executeRawSql(runtime, `INSERT INTO trajectory_archive (
1449
+ id, agent_id, source, status, start_time, end_time, duration_ms,
1450
+ step_count, llm_call_count, provider_access_count,
1451
+ total_prompt_tokens, total_completion_tokens, total_reward,
1452
+ metadata, observations, archive_blob_path, created_at, updated_at, archived_at
1453
+ )
1454
+ SELECT
1455
+ id, agent_id, source, status, start_time, end_time, duration_ms,
1456
+ step_count, llm_call_count, provider_access_count,
1457
+ total_prompt_tokens, total_completion_tokens, total_reward,
1458
+ metadata,
1459
+ COALESCE(metadata::json->>'observations', '[]'),
1460
+ ${sqlQuote(archivePath)},
1461
+ created_at, updated_at,
1462
+ ${sqlQuote(archivedAt)}
1463
+ FROM trajectories
1464
+ WHERE created_at < ${sqlQuote(cutoff)}
1465
+ ON CONFLICT (id) DO NOTHING`);
1466
+ summaryArchived = true;
1467
+ }
1468
+ catch {
1469
+ console.warn("[trajectory-persistence] Could not write summary trajectory archive rows");
1470
+ }
1471
+ }
1472
+ if (!summaryArchived) {
1473
+ console.warn("[trajectory-persistence] Summary archive insert failed, skipping prune delete");
1474
+ return null;
1475
+ }
1476
+ // Step 3: Delete the archived rows from the main table.
1477
+ const countResult = await executeRawSql(runtime, `SELECT count(*) AS total FROM trajectories WHERE created_at < ${sqlQuote(cutoff)}`);
1478
+ const countRow = asRecord(extractRows(countResult)[0]);
1479
+ const count = toNumber(countRow?.total, 0);
1480
+ if (count > 0) {
1481
+ await executeRawSql(runtime, `DELETE FROM trajectories WHERE created_at < ${sqlQuote(cutoff)}`);
1482
+ }
1483
+ return count;
1484
+ }
1485
+ catch {
1486
+ return null;
1487
+ }
1488
+ }
1489
+ /**
1490
+ * Wait for all pending trajectory writes to complete.
1491
+ * Useful for tests to ensure writes are flushed before assertions.
1492
+ */
1493
+ export async function flushTrajectoryWrites(runtime) {
1494
+ const runtimeKey = runtime;
1495
+ const perStep = stepWriteQueues.get(runtimeKey);
1496
+ if (perStep) {
1497
+ const pending = Array.from(perStep.values());
1498
+ if (pending.length > 0) {
1499
+ await Promise.all(pending);
1500
+ }
1501
+ }
1502
+ const lastWrite = lastWritePromises.get(runtimeKey);
1503
+ if (lastWrite) {
1504
+ await lastWrite;
1505
+ }
1506
+ }
1507
+ // ============================================================================
1508
+ // DatabaseTrajectoryLogger - Full implementation for trajectory-routes.ts
1509
+ // ============================================================================
1510
+ /**
1511
+ * Database-backed trajectory logger service that implements the full API
1512
+ * expected by trajectory-routes.ts. This service reads from and writes to
1513
+ * the database for trajectory persistence.
1514
+ */
1515
+ export class DatabaseTrajectoryLogger extends Service {
1516
+ static serviceType = "trajectory_logger";
1517
+ capabilityDescription = "Database-backed trajectory logging service for LLM call persistence";
1518
+ enabled = shouldEnableTrajectoryLoggingByDefault();
1519
+ /**
1520
+ * Static start method required by @elizaos/core runtime.
1521
+ */
1522
+ static async start(runtime) {
1523
+ const service = new DatabaseTrajectoryLogger(runtime);
1524
+ await service.initialize();
1525
+ return service;
1526
+ }
1527
+ async initialize() {
1528
+ if (hasRuntimeDb(this.runtime)) {
1529
+ await ensureTrajectoriesTable(this.runtime);
1530
+ // Fire-and-forget TTL pruning on startup
1531
+ pruneOldTrajectories(this.runtime, 30)
1532
+ .then((count) => {
1533
+ if (count && count > 0) {
1534
+ console.warn(`[trajectory-persistence] Pruned ${count} trajectories older than 30 days`);
1535
+ }
1536
+ })
1537
+ .catch(() => {
1538
+ /* non-critical */
1539
+ });
1540
+ }
1541
+ }
1542
+ async stop() {
1543
+ await flushTrajectoryWrites(this.runtime);
1544
+ }
1545
+ isEnabled() {
1546
+ return this.enabled;
1547
+ }
1548
+ setEnabled(enabled) {
1549
+ this.enabled = enabled;
1550
+ }
1551
+ /**
1552
+ * Start a new trajectory for tracking LLM interactions.
1553
+ * Supports both legacy (stepId, {agentId}) and new (agentId, options) signatures.
1554
+ */
1555
+ async startTrajectory(stepIdOrAgentId, options) {
1556
+ if (!this.enabled)
1557
+ return stepIdOrAgentId;
1558
+ const isLegacySignature = typeof options?.agentId === "string";
1559
+ const stepId = isLegacySignature
1560
+ ? stepIdOrAgentId
1561
+ : `step-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1562
+ // Initialize trajectory in database
1563
+ const writePromise = enqueueStepWrite(this.runtime, stepId, async () => {
1564
+ const tableReady = await ensureTrajectoriesTable(this.runtime);
1565
+ if (!tableReady)
1566
+ return;
1567
+ await startTrajectoryStepInDatabase({
1568
+ runtime: this.runtime,
1569
+ stepId,
1570
+ source: options?.source ?? "chat",
1571
+ metadata: options?.metadata,
1572
+ });
1573
+ });
1574
+ const runtimeKey = this.runtime;
1575
+ lastWritePromises.set(runtimeKey, writePromise);
1576
+ return stepId;
1577
+ }
1578
+ /**
1579
+ * Start a new step within an existing trajectory.
1580
+ */
1581
+ startStep(_trajectoryId) {
1582
+ const stepId = `step-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1583
+ // For database logger, steps are independent - we just return the new stepId
1584
+ return stepId;
1585
+ }
1586
+ /**
1587
+ * End a trajectory and mark it with the given status.
1588
+ */
1589
+ async endTrajectory(stepIdOrTrajectoryId, status = "completed") {
1590
+ if (!this.enabled)
1591
+ return;
1592
+ const writePromise = enqueueStepWrite(this.runtime, stepIdOrTrajectoryId, async () => {
1593
+ const tableReady = await ensureTrajectoriesTable(this.runtime);
1594
+ if (!tableReady)
1595
+ return;
1596
+ await completeTrajectoryStepInDatabase({
1597
+ runtime: this.runtime,
1598
+ stepId: stepIdOrTrajectoryId,
1599
+ status,
1600
+ });
1601
+ });
1602
+ const runtimeKey = this.runtime;
1603
+ lastWritePromises.set(runtimeKey, writePromise);
1604
+ }
1605
+ logLlmCall(params) {
1606
+ if (!this.enabled)
1607
+ return;
1608
+ const normalized = normalizeLlmCallPayload([params]);
1609
+ if (!normalized)
1610
+ return;
1611
+ const writePromise = enqueueStepWrite(this.runtime, normalized.stepId, async () => {
1612
+ const tableReady = await ensureTrajectoriesTable(this.runtime);
1613
+ if (!tableReady)
1614
+ return;
1615
+ await appendLlmCall(this.runtime, normalized.stepId, normalized.params);
1616
+ });
1617
+ const runtimeKey = this.runtime;
1618
+ lastWritePromises.set(runtimeKey, writePromise);
1619
+ }
1620
+ logProviderAccess(params) {
1621
+ if (!this.enabled)
1622
+ return;
1623
+ const normalized = normalizeProviderAccessPayload([params]);
1624
+ if (!normalized)
1625
+ return;
1626
+ const writePromise = enqueueStepWrite(this.runtime, normalized.stepId, async () => {
1627
+ const tableReady = await ensureTrajectoriesTable(this.runtime);
1628
+ if (!tableReady)
1629
+ return;
1630
+ await appendProviderAccess(this.runtime, normalized.stepId, normalized.params);
1631
+ });
1632
+ const runtimeKey = this.runtime;
1633
+ lastWritePromises.set(runtimeKey, writePromise);
1634
+ }
1635
+ getLlmCallLogs() {
1636
+ return [];
1637
+ }
1638
+ getProviderAccessLogs() {
1639
+ return [];
1640
+ }
1641
+ async listTrajectories(options) {
1642
+ if (!hasRuntimeDb(this.runtime)) {
1643
+ return { trajectories: [], total: 0, offset: 0, limit: 50 };
1644
+ }
1645
+ const tableReady = await ensureTrajectoriesTable(this.runtime);
1646
+ if (!tableReady) {
1647
+ return { trajectories: [], total: 0, offset: 0, limit: 50 };
1648
+ }
1649
+ const limit = Math.min(500, Math.max(1, options.limit ?? 50));
1650
+ const offset = Math.max(0, options.offset ?? 0);
1651
+ // Build WHERE clause
1652
+ const whereClauses = [];
1653
+ if (options.source) {
1654
+ whereClauses.push(`source = ${sqlQuote(options.source)}`);
1655
+ }
1656
+ if (options.status) {
1657
+ whereClauses.push(`status = ${sqlQuote(options.status)}`);
1658
+ }
1659
+ if (options.startDate) {
1660
+ const startTime = new Date(options.startDate).getTime();
1661
+ if (Number.isFinite(startTime)) {
1662
+ whereClauses.push(`start_time >= ${startTime}`);
1663
+ }
1664
+ }
1665
+ if (options.endDate) {
1666
+ const endTime = new Date(options.endDate).getTime();
1667
+ if (Number.isFinite(endTime)) {
1668
+ whereClauses.push(`start_time <= ${endTime}`);
1669
+ }
1670
+ }
1671
+ if (options.search) {
1672
+ const searchPattern = `%${options.search.replace(/[%_]/g, "\\$&")}%`;
1673
+ whereClauses.push(`id LIKE ${sqlQuote(searchPattern)}`);
1674
+ }
1675
+ const whereClause = whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
1676
+ try {
1677
+ // Get total count
1678
+ const countResult = await executeRawSql(this.runtime, `SELECT count(*) AS total FROM trajectories ${whereClause}`);
1679
+ const countRow = asRecord(extractRows(countResult)[0]);
1680
+ const total = toNumber(countRow?.total, 0);
1681
+ // Get rows
1682
+ const result = await executeRawSql(this.runtime, `SELECT * FROM trajectories ${whereClause} ORDER BY created_at DESC LIMIT ${limit} OFFSET ${offset}`);
1683
+ const rows = extractRows(result);
1684
+ const trajectories = rows
1685
+ .map((row) => {
1686
+ const r = asRecord(row);
1687
+ if (!r)
1688
+ return null;
1689
+ return {
1690
+ id: toText(r.id ?? r.trajectory_id, ""),
1691
+ agentId: toText(r.agent_id, this.runtime.agentId),
1692
+ source: toText(r.source, "runtime"),
1693
+ status: normalizeStatus(r.status, "completed"),
1694
+ startTime: toNumber(r.start_time, Date.now()),
1695
+ endTime: toOptionalNumber(r.end_time) ?? null,
1696
+ durationMs: toOptionalNumber(r.duration_ms) ?? null,
1697
+ stepCount: toNumber(r.step_count, 0),
1698
+ llmCallCount: toNumber(r.llm_call_count, 0),
1699
+ providerAccessCount: toNumber(r.provider_access_count, 0),
1700
+ totalPromptTokens: toNumber(r.total_prompt_tokens, 0),
1701
+ totalCompletionTokens: toNumber(r.total_completion_tokens, 0),
1702
+ createdAt: toText(r.created_at, new Date(toNumber(r.start_time, Date.now())).toISOString()),
1703
+ metadata: parseMetadata(r.metadata),
1704
+ };
1705
+ })
1706
+ .filter(Boolean);
1707
+ return { trajectories, total, offset, limit };
1708
+ }
1709
+ catch (err) {
1710
+ console.error("[DatabaseTrajectoryLogger] listTrajectories error:", err);
1711
+ return { trajectories: [], total: 0, offset, limit };
1712
+ }
1713
+ }
1714
+ async getTrajectoryDetail(trajectoryId) {
1715
+ if (!hasRuntimeDb(this.runtime))
1716
+ return null;
1717
+ const tableReady = await ensureTrajectoriesTable(this.runtime);
1718
+ if (!tableReady)
1719
+ return null;
1720
+ const persisted = await loadTrajectoryById(this.runtime, trajectoryId);
1721
+ if (!persisted)
1722
+ return null;
1723
+ return {
1724
+ trajectoryId: persisted.id,
1725
+ agentId: this.runtime.agentId,
1726
+ startTime: persisted.startTime,
1727
+ endTime: persisted.endTime ?? undefined,
1728
+ durationMs: persisted.endTime
1729
+ ? persisted.endTime - persisted.startTime
1730
+ : undefined,
1731
+ steps: persisted.steps.map((step) => ({
1732
+ stepId: step.stepId,
1733
+ timestamp: step.timestamp,
1734
+ llmCalls: step.llmCalls,
1735
+ providerAccesses: step.providerAccesses,
1736
+ })),
1737
+ metrics: { finalStatus: persisted.status },
1738
+ metadata: persisted.metadata,
1739
+ stepsJson: JSON.stringify(persisted.steps),
1740
+ };
1741
+ }
1742
+ async getStats() {
1743
+ if (!hasRuntimeDb(this.runtime)) {
1744
+ return { total: 0, byStatus: {}, bySource: {} };
1745
+ }
1746
+ const tableReady = await ensureTrajectoriesTable(this.runtime);
1747
+ if (!tableReady) {
1748
+ return { total: 0, byStatus: {}, bySource: {} };
1749
+ }
1750
+ try {
1751
+ const countResult = await executeRawSql(this.runtime, "SELECT count(*) AS total FROM trajectories");
1752
+ const countRow = asRecord(extractRows(countResult)[0]);
1753
+ const total = toNumber(countRow?.total, 0);
1754
+ const bySource = await computeBySource(this.runtime);
1755
+ return {
1756
+ total,
1757
+ enabled: this.enabled,
1758
+ byStatus: {},
1759
+ bySource,
1760
+ };
1761
+ }
1762
+ catch {
1763
+ return { total: 0, byStatus: {}, bySource: {} };
1764
+ }
1765
+ }
1766
+ async deleteTrajectories(trajectoryIds) {
1767
+ const result = await deletePersistedTrajectoryRows(this.runtime, trajectoryIds);
1768
+ return result ?? 0;
1769
+ }
1770
+ async clearAllTrajectories() {
1771
+ const result = await clearPersistedTrajectoryRows(this.runtime);
1772
+ return result ?? 0;
1773
+ }
1774
+ async exportTrajectories(options) {
1775
+ const listResult = await this.listTrajectories({
1776
+ limit: 10000,
1777
+ startDate: options.startDate,
1778
+ endDate: options.endDate,
1779
+ });
1780
+ let ids = listResult.trajectories.map((t) => t.id);
1781
+ if (options.trajectoryIds && options.trajectoryIds.length > 0) {
1782
+ const idSet = new Set(options.trajectoryIds);
1783
+ ids = ids.filter((id) => idSet.has(id));
1784
+ }
1785
+ const trajectories = [];
1786
+ for (const id of ids) {
1787
+ const detail = await this.getTrajectoryDetail(id);
1788
+ if (detail)
1789
+ trajectories.push(detail);
1790
+ }
1791
+ if (options.format === "json") {
1792
+ return {
1793
+ filename: `trajectories-${Date.now()}.json`,
1794
+ data: JSON.stringify(trajectories, null, 2),
1795
+ mimeType: "application/json",
1796
+ };
1797
+ }
1798
+ if (options.format === "csv") {
1799
+ const rows = [
1800
+ "id,agentId,startTime,endTime,status,llmCallCount,promptTokens,completionTokens",
1801
+ ];
1802
+ for (const t of trajectories) {
1803
+ const llmCount = t.steps?.reduce((sum, s) => sum + (s.llmCalls?.length ?? 0), 0);
1804
+ const promptTokens = t.steps?.reduce((sum, s) => sum +
1805
+ (s.llmCalls?.reduce((s2, c) => s2 + (c.promptTokens ?? 0), 0) ?? 0), 0);
1806
+ const completionTokens = t.steps?.reduce((sum, s) => sum +
1807
+ (s.llmCalls?.reduce((s2, c) => s2 + (c.completionTokens ?? 0), 0) ??
1808
+ 0), 0);
1809
+ rows.push(`${t.trajectoryId},${t.agentId},${t.startTime},${t.endTime ?? ""},${t.metrics?.finalStatus ?? ""},${llmCount ?? 0},${promptTokens ?? 0},${completionTokens ?? 0}`);
1810
+ }
1811
+ return {
1812
+ filename: `trajectories-${Date.now()}.csv`,
1813
+ data: rows.join("\n"),
1814
+ mimeType: "text/csv",
1815
+ };
1816
+ }
1817
+ // Default to JSON for 'art' format
1818
+ return {
1819
+ filename: `trajectories-${Date.now()}.json`,
1820
+ data: JSON.stringify(trajectories, null, 2),
1821
+ mimeType: "application/json",
1822
+ };
1823
+ }
1824
+ }
1825
+ /**
1826
+ * Create and register a database-backed trajectory logger service on the runtime.
1827
+ * This replaces any existing trajectory_logger service with one that persists to the database.
1828
+ */
1829
+ export function createDatabaseTrajectoryLogger(runtime) {
1830
+ const logger = new DatabaseTrajectoryLogger(runtime);
1831
+ return logger;
1832
+ }
1833
+ export function shouldEnableTrajectoryLoggingByDefault() {
1834
+ return process.env.NODE_ENV !== "production";
1835
+ }