@elizaos/plugin-elizacloud 2.0.0-alpha.7 → 2.0.0-beta.1

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 (378) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +220 -0
  3. package/auto-enable.ts +17 -0
  4. package/dist/browser/index.browser.js +2 -21
  5. package/dist/browser/index.browser.js.map +5 -37
  6. package/dist/cjs/index.d.ts +2 -2
  7. package/dist/cjs/index.node.cjs +12173 -2271
  8. package/dist/cjs/index.node.js.map +135 -27
  9. package/dist/cloud/auth.d.ts +19 -0
  10. package/dist/cloud/auth.d.ts.map +1 -0
  11. package/dist/cloud/auth.js +330 -0
  12. package/dist/cloud/auth.js.map +12 -0
  13. package/dist/cloud/backup.d.ts +18 -0
  14. package/dist/cloud/backup.d.ts.map +1 -0
  15. package/dist/cloud/backup.js +63 -0
  16. package/dist/cloud/backup.js.map +10 -0
  17. package/dist/cloud/base-url.d.ts +3 -0
  18. package/dist/cloud/base-url.d.ts.map +1 -0
  19. package/dist/cloud/base-url.js +77 -0
  20. package/dist/cloud/base-url.js.map +10 -0
  21. package/dist/cloud/bridge-client.d.ts +126 -0
  22. package/dist/cloud/bridge-client.d.ts.map +1 -0
  23. package/dist/cloud/bridge-client.js +432 -0
  24. package/dist/cloud/bridge-client.js.map +11 -0
  25. package/dist/cloud/cloud-api-key.d.ts +26 -0
  26. package/dist/cloud/cloud-api-key.d.ts.map +1 -0
  27. package/dist/cloud/cloud-api-key.js +60 -0
  28. package/dist/cloud/cloud-api-key.js.map +10 -0
  29. package/dist/cloud/cloud-manager.d.ts +33 -0
  30. package/dist/cloud/cloud-manager.d.ts.map +1 -0
  31. package/dist/cloud/cloud-manager.js +853 -0
  32. package/dist/cloud/cloud-manager.js.map +16 -0
  33. package/dist/cloud/cloud-proxy.d.ts +20 -0
  34. package/dist/cloud/cloud-proxy.d.ts.map +1 -0
  35. package/dist/cloud/cloud-proxy.js +54 -0
  36. package/dist/cloud/cloud-proxy.js.map +10 -0
  37. package/dist/cloud/cloud-wallet.d.ts +94 -0
  38. package/dist/cloud/cloud-wallet.d.ts.map +1 -0
  39. package/dist/cloud/cloud-wallet.js +5195 -0
  40. package/dist/cloud/cloud-wallet.js.map +92 -0
  41. package/dist/cloud/index.d.ts +9 -0
  42. package/dist/cloud/index.d.ts.map +1 -0
  43. package/dist/cloud/index.js +30 -0
  44. package/dist/cloud/index.js.map +9 -0
  45. package/dist/cloud/reconnect.d.ts +26 -0
  46. package/dist/cloud/reconnect.d.ts.map +1 -0
  47. package/dist/cloud/reconnect.js +104 -0
  48. package/dist/cloud/reconnect.js.map +10 -0
  49. package/dist/cloud/validate-url.d.ts +2 -0
  50. package/dist/cloud/validate-url.d.ts.map +1 -0
  51. package/dist/cloud/validate-url.js +174 -0
  52. package/dist/cloud/validate-url.js.map +10 -0
  53. package/dist/cloud-providers/cloud-status.d.ts.map +1 -1
  54. package/dist/cloud-providers/cloud-status.js +78 -0
  55. package/dist/cloud-providers/cloud-status.js.map +10 -0
  56. package/dist/cloud-providers/container-health.d.ts.map +1 -1
  57. package/dist/cloud-providers/container-health.js +74 -0
  58. package/dist/cloud-providers/container-health.js.map +10 -0
  59. package/dist/cloud-providers/credit-balance.d.ts.map +1 -1
  60. package/dist/cloud-providers/credit-balance.js +85 -0
  61. package/dist/cloud-providers/credit-balance.js.map +10 -0
  62. package/dist/cloud-providers/index.d.ts.map +1 -1
  63. package/dist/cloud-providers/index.js +24 -0
  64. package/dist/cloud-providers/index.js.map +9 -0
  65. package/dist/cloud-providers/model-registry.d.ts.map +1 -1
  66. package/dist/cloud-providers/model-registry.js +71 -0
  67. package/dist/cloud-providers/model-registry.js.map +10 -0
  68. package/dist/index.browser.d.ts +4 -2
  69. package/dist/index.browser.d.ts.map +1 -1
  70. package/dist/index.d.ts +18 -0
  71. package/dist/index.d.ts.map +1 -1
  72. package/dist/index.js +12851 -0
  73. package/dist/index.js.map +145 -0
  74. package/dist/index.node.d.ts +15 -2
  75. package/dist/index.node.d.ts.map +1 -1
  76. package/dist/init.d.ts.map +1 -1
  77. package/dist/init.js +169 -0
  78. package/dist/init.js.map +12 -0
  79. package/dist/lib/cloud-connection.d.ts +78 -0
  80. package/dist/lib/cloud-connection.d.ts.map +1 -0
  81. package/dist/lib/cloud-connection.js +731 -0
  82. package/dist/lib/cloud-connection.js.map +14 -0
  83. package/dist/lib/cloud-secrets.d.ts +23 -0
  84. package/dist/lib/cloud-secrets.d.ts.map +1 -0
  85. package/dist/lib/cloud-secrets.js +64 -0
  86. package/dist/lib/cloud-secrets.js.map +10 -0
  87. package/dist/lib/config-env.d.ts +5 -0
  88. package/dist/lib/config-env.d.ts.map +1 -0
  89. package/dist/lib/config-env.js +191 -0
  90. package/dist/lib/config-env.js.map +11 -0
  91. package/dist/lib/config-like.d.ts +40 -0
  92. package/dist/lib/config-like.d.ts.map +1 -0
  93. package/dist/lib/config-like.js +103 -0
  94. package/dist/lib/config-like.js.map +10 -0
  95. package/dist/lib/credential-type-map.d.ts +53 -0
  96. package/dist/lib/credential-type-map.d.ts.map +1 -0
  97. package/dist/lib/credential-type-map.js +88 -0
  98. package/dist/lib/credential-type-map.js.map +10 -0
  99. package/dist/lib/feature-flags.d.ts +2 -0
  100. package/dist/lib/feature-flags.d.ts.map +1 -0
  101. package/dist/lib/feature-flags.js +40 -0
  102. package/dist/lib/feature-flags.js.map +10 -0
  103. package/dist/lib/http.d.ts +22 -0
  104. package/dist/lib/http.d.ts.map +1 -0
  105. package/dist/lib/http.js +107 -0
  106. package/dist/lib/http.js.map +10 -0
  107. package/dist/lib/server-cloud-tts.d.ts +34 -0
  108. package/dist/lib/server-cloud-tts.d.ts.map +1 -0
  109. package/dist/lib/server-cloud-tts.js +549 -0
  110. package/dist/lib/server-cloud-tts.js.map +13 -0
  111. package/dist/lib/state-paths.d.ts +4 -0
  112. package/dist/lib/state-paths.d.ts.map +1 -0
  113. package/dist/lib/state-paths.js +52 -0
  114. package/dist/lib/state-paths.js.map +10 -0
  115. package/dist/lib/tts-debug.d.ts +4 -0
  116. package/dist/lib/tts-debug.d.ts.map +1 -0
  117. package/dist/lib/tts-debug.js +57 -0
  118. package/dist/lib/tts-debug.js.map +10 -0
  119. package/dist/models/embeddings.d.ts.map +1 -1
  120. package/dist/models/embeddings.js +319 -0
  121. package/dist/models/embeddings.js.map +13 -0
  122. package/dist/models/image.d.ts.map +1 -1
  123. package/dist/models/image.js +374 -0
  124. package/dist/models/image.js.map +14 -0
  125. package/dist/models/index.d.ts +1 -2
  126. package/dist/models/index.d.ts.map +1 -1
  127. package/dist/models/index.js +1386 -0
  128. package/dist/models/index.js.map +20 -0
  129. package/dist/models/research.d.ts.map +1 -1
  130. package/dist/models/research.js +324 -0
  131. package/dist/models/research.js.map +13 -0
  132. package/dist/models/speech.d.ts.map +1 -1
  133. package/dist/models/speech.js +273 -0
  134. package/dist/models/speech.js.map +13 -0
  135. package/dist/models/text.d.ts +5 -2
  136. package/dist/models/text.d.ts.map +1 -1
  137. package/dist/models/text.js +803 -0
  138. package/dist/models/text.js.map +15 -0
  139. package/dist/models/tokenization.d.ts.map +1 -1
  140. package/dist/models/tokenization.js +65 -0
  141. package/dist/models/tokenization.js.map +10 -0
  142. package/dist/models/transcription.d.ts.map +1 -1
  143. package/dist/models/transcription.js +283 -0
  144. package/dist/models/transcription.js.map +13 -0
  145. package/dist/node/index.d.ts +2 -2
  146. package/dist/node/index.node.js +12171 -2266
  147. package/dist/node/index.node.js.map +135 -27
  148. package/dist/onboarding.d.ts +35 -0
  149. package/dist/onboarding.d.ts.map +1 -0
  150. package/dist/onboarding.js +883 -0
  151. package/dist/onboarding.js.map +14 -0
  152. package/dist/plugin.d.ts +20 -0
  153. package/dist/plugin.d.ts.map +1 -0
  154. package/dist/plugin.js +7611 -0
  155. package/dist/plugin.js.map +104 -0
  156. package/dist/providers/openai.d.ts.map +1 -1
  157. package/dist/providers/openai.js +127 -0
  158. package/dist/providers/openai.js.map +11 -0
  159. package/dist/register-routes.d.ts +2 -0
  160. package/dist/register-routes.d.ts.map +1 -0
  161. package/dist/register-routes.js +7612 -0
  162. package/dist/register-routes.js.map +105 -0
  163. package/dist/routes/cloud-billing-routes.d.ts +9 -0
  164. package/dist/routes/cloud-billing-routes.d.ts.map +1 -0
  165. package/dist/routes/cloud-billing-routes.js +807 -0
  166. package/dist/routes/cloud-billing-routes.js.map +14 -0
  167. package/dist/routes/cloud-compat-routes.d.ts +10 -0
  168. package/dist/routes/cloud-compat-routes.d.ts.map +1 -0
  169. package/dist/routes/cloud-compat-routes.js +538 -0
  170. package/dist/routes/cloud-compat-routes.js.map +14 -0
  171. package/dist/routes/cloud-features-routes.d.ts +9 -0
  172. package/dist/routes/cloud-features-routes.d.ts.map +1 -0
  173. package/dist/routes/cloud-features-routes.js +124 -0
  174. package/dist/routes/cloud-features-routes.js.map +11 -0
  175. package/dist/routes/cloud-provisioning.d.ts +14 -0
  176. package/dist/routes/cloud-provisioning.d.ts.map +1 -0
  177. package/dist/routes/cloud-provisioning.js +37 -0
  178. package/dist/routes/cloud-provisioning.js.map +10 -0
  179. package/dist/routes/cloud-relay-routes.d.ts +22 -0
  180. package/dist/routes/cloud-relay-routes.d.ts.map +1 -0
  181. package/dist/routes/cloud-relay-routes.js +60 -0
  182. package/dist/routes/cloud-relay-routes.js.map +10 -0
  183. package/dist/routes/cloud-routes-autonomous.d.ts +83 -0
  184. package/dist/routes/cloud-routes-autonomous.d.ts.map +1 -0
  185. package/dist/routes/cloud-routes-autonomous.js +6134 -0
  186. package/dist/routes/cloud-routes-autonomous.js.map +97 -0
  187. package/dist/routes/cloud-routes.d.ts +35 -0
  188. package/dist/routes/cloud-routes.d.ts.map +1 -0
  189. package/dist/routes/cloud-routes.js +6888 -0
  190. package/dist/routes/cloud-routes.js.map +100 -0
  191. package/dist/routes/cloud-status-routes-autonomous.d.ts +15 -0
  192. package/dist/routes/cloud-status-routes-autonomous.d.ts.map +1 -0
  193. package/dist/routes/cloud-status-routes-autonomous.js +396 -0
  194. package/dist/routes/cloud-status-routes-autonomous.js.map +13 -0
  195. package/dist/routes/cloud-status-routes.d.ts +4 -0
  196. package/dist/routes/cloud-status-routes.d.ts.map +1 -0
  197. package/dist/routes/cloud-status-routes.js +771 -0
  198. package/dist/routes/cloud-status-routes.js.map +15 -0
  199. package/dist/services/cloud-auth.d.ts +140 -5
  200. package/dist/services/cloud-auth.d.ts.map +1 -1
  201. package/dist/services/cloud-auth.js +363 -0
  202. package/dist/services/cloud-auth.js.map +12 -0
  203. package/dist/services/cloud-backup.d.ts.map +1 -1
  204. package/dist/services/cloud-backup.js +176 -0
  205. package/dist/services/cloud-backup.js.map +11 -0
  206. package/dist/services/cloud-bootstrap.d.ts +38 -0
  207. package/dist/services/cloud-bootstrap.d.ts.map +1 -0
  208. package/dist/services/cloud-bootstrap.js +84 -0
  209. package/dist/services/cloud-bootstrap.js.map +10 -0
  210. package/dist/services/cloud-bridge.d.ts +1 -1
  211. package/dist/services/cloud-bridge.d.ts.map +1 -1
  212. package/dist/services/cloud-bridge.js +308 -0
  213. package/dist/services/cloud-bridge.js.map +11 -0
  214. package/dist/services/cloud-container.d.ts.map +1 -1
  215. package/dist/services/cloud-container.js +241 -0
  216. package/dist/services/cloud-container.js.map +11 -0
  217. package/dist/services/cloud-credential-provider.d.ts +55 -0
  218. package/dist/services/cloud-credential-provider.d.ts.map +1 -0
  219. package/dist/services/cloud-credential-provider.js +190 -0
  220. package/dist/services/cloud-credential-provider.js.map +11 -0
  221. package/dist/services/cloud-managed-gateway-relay.d.ts +38 -0
  222. package/dist/services/cloud-managed-gateway-relay.d.ts.map +1 -0
  223. package/dist/services/cloud-managed-gateway-relay.js +479 -0
  224. package/dist/services/cloud-managed-gateway-relay.js.map +10 -0
  225. package/dist/services/cloud-model-registry.d.ts.map +1 -1
  226. package/dist/services/cloud-model-registry.js +175 -0
  227. package/dist/services/cloud-model-registry.js.map +10 -0
  228. package/dist/services/index.d.ts +3 -1
  229. package/dist/services/index.d.ts.map +1 -1
  230. package/dist/services/index.js +29 -0
  231. package/dist/services/index.js.map +9 -0
  232. package/dist/types/cloud.d.ts +41 -19
  233. package/dist/types/cloud.d.ts.map +1 -1
  234. package/dist/types/cloud.js +52 -0
  235. package/dist/types/cloud.js.map +10 -0
  236. package/dist/types/index.d.ts +1 -1
  237. package/dist/types/index.d.ts.map +1 -1
  238. package/dist/types/index.js +24 -0
  239. package/dist/types/index.js.map +9 -0
  240. package/dist/utils/cloud-api.d.ts +2 -27
  241. package/dist/utils/cloud-api.d.ts.map +1 -1
  242. package/dist/utils/cloud-api.js +33 -0
  243. package/dist/utils/cloud-api.js.map +10 -0
  244. package/dist/utils/cloud-sdk/client.d.ts +133 -0
  245. package/dist/utils/cloud-sdk/client.d.ts.map +1 -0
  246. package/dist/utils/cloud-sdk/client.js +3561 -0
  247. package/dist/utils/cloud-sdk/client.js.map +13 -0
  248. package/dist/utils/cloud-sdk/http.d.ts +37 -0
  249. package/dist/utils/cloud-sdk/http.d.ts.map +1 -0
  250. package/dist/utils/cloud-sdk/http.js +237 -0
  251. package/dist/utils/cloud-sdk/http.js.map +11 -0
  252. package/dist/utils/cloud-sdk/index.d.ts +6 -0
  253. package/dist/utils/cloud-sdk/index.d.ts.map +1 -0
  254. package/dist/utils/cloud-sdk/index.js +29 -0
  255. package/dist/utils/cloud-sdk/index.js.map +9 -0
  256. package/dist/utils/cloud-sdk/public-routes.d.ts +5377 -0
  257. package/dist/utils/cloud-sdk/public-routes.d.ts.map +1 -0
  258. package/dist/utils/cloud-sdk/public-routes.js +2950 -0
  259. package/dist/utils/cloud-sdk/public-routes.js.map +10 -0
  260. package/dist/utils/cloud-sdk/types.cloud-api.d.ts +101 -0
  261. package/dist/utils/cloud-sdk/types.cloud-api.d.ts.map +1 -0
  262. package/dist/utils/cloud-sdk/types.cloud-api.js +2 -0
  263. package/dist/utils/cloud-sdk/types.cloud-api.js.map +9 -0
  264. package/dist/utils/cloud-sdk/types.d.ts +655 -0
  265. package/dist/utils/cloud-sdk/types.d.ts.map +1 -0
  266. package/dist/utils/cloud-sdk/types.js +29 -0
  267. package/dist/utils/cloud-sdk/types.js.map +10 -0
  268. package/dist/utils/config.d.ts +7 -3
  269. package/dist/utils/config.d.ts.map +1 -1
  270. package/dist/utils/config.js +137 -0
  271. package/dist/utils/config.js.map +10 -0
  272. package/dist/utils/events.d.ts.map +1 -1
  273. package/dist/utils/events.js +43 -0
  274. package/dist/utils/events.js.map +10 -0
  275. package/dist/utils/helpers.d.ts.map +1 -1
  276. package/dist/utils/helpers.js +103 -0
  277. package/dist/utils/helpers.js.map +10 -0
  278. package/dist/utils/responses-output.d.ts +13 -0
  279. package/dist/utils/responses-output.d.ts.map +1 -0
  280. package/dist/utils/responses-output.js +102 -0
  281. package/dist/utils/responses-output.js.map +10 -0
  282. package/dist/utils/sdk-client.d.ts +5 -0
  283. package/dist/utils/sdk-client.d.ts.map +1 -0
  284. package/dist/utils/sdk-client.js +144 -0
  285. package/dist/utils/sdk-client.js.map +11 -0
  286. package/package.json +108 -19
  287. package/src/cloud/auth.ts +175 -0
  288. package/src/cloud/backup.ts +46 -0
  289. package/src/cloud/base-url.ts +62 -0
  290. package/src/cloud/bridge-client.ts +602 -0
  291. package/src/cloud/cloud-api-key.ts +80 -0
  292. package/src/cloud/cloud-manager.ts +163 -0
  293. package/src/cloud/cloud-proxy.ts +52 -0
  294. package/src/cloud/cloud-wallet.ts +341 -0
  295. package/src/cloud/index.ts +28 -0
  296. package/src/cloud/reconnect.ts +111 -0
  297. package/src/cloud/validate-url.ts +181 -0
  298. package/src/cloud-providers/cloud-status.ts +75 -0
  299. package/src/cloud-providers/container-health.ts +68 -0
  300. package/src/cloud-providers/credit-balance.ts +70 -0
  301. package/src/cloud-providers/index.ts +3 -0
  302. package/src/cloud-providers/model-registry.ts +74 -0
  303. package/src/index.browser.ts +10 -0
  304. package/src/index.node.ts +39 -0
  305. package/src/index.ts +347 -0
  306. package/src/init.ts +39 -0
  307. package/src/lib/cloud-connection.ts +663 -0
  308. package/src/lib/cloud-secrets.ts +58 -0
  309. package/src/lib/config-env.ts +168 -0
  310. package/src/lib/config-like.ts +149 -0
  311. package/src/lib/credential-type-map.ts +130 -0
  312. package/src/lib/feature-flags.ts +26 -0
  313. package/src/lib/http.ts +139 -0
  314. package/src/lib/server-cloud-tts.ts +609 -0
  315. package/src/lib/state-paths.ts +28 -0
  316. package/src/lib/tts-debug.ts +34 -0
  317. package/src/models/embeddings.ts +234 -0
  318. package/src/models/image.ts +219 -0
  319. package/src/models/index.ts +16 -0
  320. package/src/models/research.ts +265 -0
  321. package/src/models/speech.ts +78 -0
  322. package/src/models/text.ts +899 -0
  323. package/src/models/tokenization.ts +67 -0
  324. package/src/models/transcription.ts +97 -0
  325. package/src/onboarding.ts +396 -0
  326. package/src/plugin.ts +243 -0
  327. package/src/providers/openai.ts +16 -0
  328. package/src/register-routes.ts +6 -0
  329. package/src/routes/cloud-billing-routes.ts +754 -0
  330. package/src/routes/cloud-compat-routes.ts +314 -0
  331. package/src/routes/cloud-features-routes.ts +57 -0
  332. package/src/routes/cloud-provisioning.ts +37 -0
  333. package/src/routes/cloud-relay-routes.ts +89 -0
  334. package/src/routes/cloud-routes-autonomous.ts +996 -0
  335. package/src/routes/cloud-routes.ts +576 -0
  336. package/src/routes/cloud-status-routes-autonomous.ts +234 -0
  337. package/src/routes/cloud-status-routes.ts +73 -0
  338. package/src/services/cloud-auth.ts +567 -0
  339. package/src/services/cloud-backup.ts +208 -0
  340. package/src/services/cloud-bootstrap.ts +108 -0
  341. package/src/services/cloud-bridge.ts +386 -0
  342. package/src/services/cloud-container.ts +297 -0
  343. package/src/services/cloud-credential-provider.ts +210 -0
  344. package/src/services/cloud-managed-gateway-relay.ts +663 -0
  345. package/src/services/cloud-model-registry.ts +202 -0
  346. package/src/services/index.ts +17 -0
  347. package/{types → src/types}/cloud.ts +52 -29
  348. package/{types → src/types}/index.ts +6 -0
  349. package/src/utils/cloud-api.ts +10 -0
  350. package/src/utils/cloud-sdk/client.ts +735 -0
  351. package/src/utils/cloud-sdk/http.ts +291 -0
  352. package/src/utils/cloud-sdk/index.ts +23 -0
  353. package/src/utils/cloud-sdk/public-routes.ts +5070 -0
  354. package/src/utils/cloud-sdk/types.cloud-api.ts +120 -0
  355. package/src/utils/cloud-sdk/types.ts +762 -0
  356. package/src/utils/config.ts +174 -0
  357. package/src/utils/events.ts +37 -0
  358. package/src/utils/helpers.ts +107 -0
  359. package/src/utils/responses-output.ts +115 -0
  360. package/src/utils/sdk-client.ts +37 -0
  361. package/dist/actions/check-credits.d.ts +0 -6
  362. package/dist/actions/check-credits.d.ts.map +0 -1
  363. package/dist/actions/freeze-agent.d.ts +0 -9
  364. package/dist/actions/freeze-agent.d.ts.map +0 -1
  365. package/dist/actions/index.d.ts +0 -5
  366. package/dist/actions/index.d.ts.map +0 -1
  367. package/dist/actions/provision-agent.d.ts +0 -8
  368. package/dist/actions/provision-agent.d.ts.map +0 -1
  369. package/dist/actions/resume-agent.d.ts +0 -9
  370. package/dist/actions/resume-agent.d.ts.map +0 -1
  371. package/dist/build.d.ts +0 -3
  372. package/dist/build.d.ts.map +0 -1
  373. package/dist/generated/specs/specs.d.ts +0 -55
  374. package/dist/generated/specs/specs.d.ts.map +0 -1
  375. package/dist/models/object.d.ts +0 -4
  376. package/dist/models/object.d.ts.map +0 -1
  377. package/dist/utils/forwarded-settings.d.ts +0 -8
  378. package/dist/utils/forwarded-settings.d.ts.map +0 -1
@@ -0,0 +1,899 @@
1
+ import type {
2
+ GenerateTextParams,
3
+ IAgentRuntime,
4
+ ModelTypeName,
5
+ TextStreamResult,
6
+ } from "@elizaos/core";
7
+ import {
8
+ buildCanonicalSystemPrompt,
9
+ logger,
10
+ ModelType,
11
+ renderChatMessagesForPrompt,
12
+ resolveEffectiveSystemPrompt,
13
+ } from "@elizaos/core";
14
+ import type { LanguageModel } from "ai";
15
+ import { createOpenAIClient } from "../providers/openai";
16
+ import {
17
+ getActionPlannerModel,
18
+ getExperimentalTelemetry,
19
+ getLargeModel,
20
+ getMediumModel,
21
+ getMegaModel,
22
+ getNanoModel,
23
+ getResponseHandlerModel,
24
+ getSmallModel,
25
+ } from "../utils/config";
26
+ import { emitModelUsageEvent } from "../utils/events";
27
+ import { extractResponsesOutputText } from "../utils/responses-output";
28
+ import { createCloudApiClient } from "../utils/sdk-client";
29
+
30
+ const TEXT_NANO_MODEL_TYPE = (ModelType.TEXT_NANO ?? "TEXT_NANO") as ModelTypeName;
31
+ const TEXT_MEDIUM_MODEL_TYPE = (ModelType.TEXT_MEDIUM ?? "TEXT_MEDIUM") as ModelTypeName;
32
+ const TEXT_SMALL_MODEL_TYPE = ModelType.TEXT_SMALL;
33
+ const TEXT_LARGE_MODEL_TYPE = ModelType.TEXT_LARGE;
34
+ const TEXT_MEGA_MODEL_TYPE = (ModelType.TEXT_MEGA ?? "TEXT_MEGA") as ModelTypeName;
35
+ const RESPONSE_HANDLER_MODEL_TYPE = (ModelType.RESPONSE_HANDLER ??
36
+ "RESPONSE_HANDLER") as ModelTypeName;
37
+ const ACTION_PLANNER_MODEL_TYPE = (ModelType.ACTION_PLANNER ?? "ACTION_PLANNER") as ModelTypeName;
38
+
39
+ type ResponsesApiResponse = Record<string, unknown> & {
40
+ error?: {
41
+ message?: string;
42
+ };
43
+ usage?: {
44
+ input_tokens?: number;
45
+ output_tokens?: number;
46
+ total_tokens?: number;
47
+ } & Record<string, unknown>;
48
+ };
49
+
50
+ /**
51
+ * Models that are known to be reasoning-class and don't support temperature.
52
+ * These are models that use chain-of-thought internally and reject
53
+ */
54
+ const REASONING_MODEL_PATTERNS = [
55
+ "o1",
56
+ "o3",
57
+ "o4",
58
+ "deepseek-r1",
59
+ "deepseek-reasoner",
60
+ "claude-opus-4.7",
61
+ "claude-opus-4-7",
62
+ "gpt-5",
63
+ ] as const;
64
+ const RESPONSES_ROUTED_PREFIXES = ["openai/", "anthropic/"] as const;
65
+ type ChatAttachment = {
66
+ data: string | Uint8Array | URL;
67
+ mediaType: string;
68
+ filename?: string;
69
+ };
70
+
71
+ type GenerateTextParamsWithAttachments = GenerateTextParams & {
72
+ attachments?: ChatAttachment[];
73
+ };
74
+
75
+ type GenerateTextParamsWithNativeOptions = GenerateTextParamsWithAttachments & {
76
+ messages?: unknown[];
77
+ tools?: unknown;
78
+ toolChoice?: unknown;
79
+ responseSchema?: unknown;
80
+ providerOptions?: Record<string, unknown>;
81
+ };
82
+
83
+ type NativeTokenUsage = {
84
+ promptTokens: number;
85
+ completionTokens: number;
86
+ totalTokens: number;
87
+ cachedPromptTokens?: number;
88
+ cacheReadInputTokens?: number;
89
+ cacheCreationInputTokens?: number;
90
+ };
91
+
92
+ type NativeGenerateTextResult = {
93
+ text: string;
94
+ toolCalls: unknown[];
95
+ finishReason?: string;
96
+ usage?: NativeTokenUsage;
97
+ providerMetadata?: unknown;
98
+ };
99
+
100
+ type NativeGenerateTextModelResult = NativeGenerateTextResult & string;
101
+
102
+ type NativeToolCall = {
103
+ type: "tool-call";
104
+ toolCallId: string;
105
+ toolName: string;
106
+ input: unknown;
107
+ };
108
+
109
+ type ChatCompletionsResponse = Record<string, unknown> & {
110
+ error?: {
111
+ message?: string;
112
+ };
113
+ choices?: Array<{
114
+ text?: string;
115
+ finish_reason?: string;
116
+ message?: {
117
+ content?: unknown;
118
+ tool_calls?: unknown[];
119
+ };
120
+ }>;
121
+ usage?: Record<string, unknown>;
122
+ };
123
+
124
+ function buildUserContent(params: GenerateTextParamsWithAttachments) {
125
+ const content: Array<
126
+ | { type: "text"; text: string }
127
+ | {
128
+ type: "file";
129
+ data: string | Uint8Array | URL;
130
+ mediaType: string;
131
+ filename?: string;
132
+ }
133
+ > = [{ type: "text", text: params.prompt ?? "" }];
134
+
135
+ for (const attachment of params.attachments ?? []) {
136
+ content.push({
137
+ type: "file",
138
+ data: attachment.data,
139
+ mediaType: attachment.mediaType,
140
+ ...(attachment.filename ? { filename: attachment.filename } : {}),
141
+ });
142
+ }
143
+
144
+ return content;
145
+ }
146
+
147
+ function isReasoningModel(modelName: string): boolean {
148
+ const lower = modelName.toLowerCase();
149
+ return REASONING_MODEL_PATTERNS.some((pattern) => lower.includes(pattern));
150
+ }
151
+
152
+ function supportsStopSequences(modelName: string): boolean {
153
+ const lower = modelName.toLowerCase();
154
+ return !RESPONSES_ROUTED_PREFIXES.some((prefix) => lower.startsWith(prefix));
155
+ }
156
+
157
+ function isRecord(value: unknown): value is Record<string, unknown> {
158
+ return typeof value === "object" && value !== null && !Array.isArray(value);
159
+ }
160
+
161
+ function asRecord(value: unknown): Record<string, unknown> {
162
+ return isRecord(value) ? value : {};
163
+ }
164
+
165
+ function recordAt(value: Record<string, unknown>, key: string): Record<string, unknown> {
166
+ return asRecord(value[key]);
167
+ }
168
+
169
+ function firstString(...values: unknown[]): string | undefined {
170
+ for (const value of values) {
171
+ if (typeof value === "string" && value.trim().length > 0) {
172
+ return value.trim();
173
+ }
174
+ }
175
+ return undefined;
176
+ }
177
+
178
+ function firstNumber(...values: unknown[]): number | undefined {
179
+ for (const value of values) {
180
+ if (typeof value === "number" && Number.isFinite(value)) {
181
+ return value;
182
+ }
183
+ if (typeof value === "string" && value.trim().length > 0) {
184
+ const parsed = Number(value);
185
+ if (Number.isFinite(parsed)) {
186
+ return parsed;
187
+ }
188
+ }
189
+ }
190
+ return undefined;
191
+ }
192
+
193
+ function parseJsonIfPossible(value: unknown): unknown {
194
+ if (typeof value !== "string") {
195
+ return value ?? {};
196
+ }
197
+ try {
198
+ return JSON.parse(value) as unknown;
199
+ } catch {
200
+ return value;
201
+ }
202
+ }
203
+
204
+ function stringifyMessageContent(content: unknown): string {
205
+ if (typeof content === "string") {
206
+ return content;
207
+ }
208
+ if (content == null) {
209
+ return "";
210
+ }
211
+ return typeof content === "object" ? JSON.stringify(content) : String(content);
212
+ }
213
+
214
+ function hasNativeTransportOptions(params: GenerateTextParamsWithNativeOptions): boolean {
215
+ return Boolean(
216
+ params.messages ||
217
+ params.tools ||
218
+ params.toolChoice ||
219
+ params.responseSchema ||
220
+ params.providerOptions
221
+ );
222
+ }
223
+
224
+ function shouldReturnNativeResult(params: GenerateTextParamsWithNativeOptions): boolean {
225
+ return Boolean(params.messages || params.tools || params.toolChoice || params.responseSchema);
226
+ }
227
+
228
+ function buildNativeMessages(
229
+ params: GenerateTextParamsWithNativeOptions,
230
+ promptText: string,
231
+ systemPrompt?: string
232
+ ): Array<Record<string, unknown>> {
233
+ if (Array.isArray(params.messages) && params.messages.length > 0) {
234
+ const messages = params.messages.map((message) =>
235
+ isRecord(message)
236
+ ? { ...message }
237
+ : { role: "user", content: stringifyMessageContent(message) }
238
+ );
239
+ const first = asRecord(messages[0]);
240
+ if (systemPrompt && first.role !== "system") {
241
+ return [{ role: "system", content: systemPrompt }, ...messages];
242
+ }
243
+ return messages;
244
+ }
245
+
246
+ const messages: Array<Record<string, unknown>> = [];
247
+ if (systemPrompt) {
248
+ messages.push({ role: "system", content: systemPrompt });
249
+ }
250
+ messages.push({ role: "user", content: promptText });
251
+ return messages;
252
+ }
253
+
254
+ function unwrapJsonSchema(value: unknown): unknown {
255
+ const record = asRecord(value);
256
+ return record.schema ?? record.jsonSchema ?? value;
257
+ }
258
+
259
+ function normalizeNativeTools(tools: unknown): unknown[] | undefined {
260
+ if (!tools) {
261
+ return undefined;
262
+ }
263
+
264
+ if (Array.isArray(tools)) {
265
+ return tools;
266
+ }
267
+
268
+ const toolSet = asRecord(tools);
269
+ const normalized: unknown[] = [];
270
+ for (const [name, rawTool] of Object.entries(toolSet)) {
271
+ const tool = asRecord(rawTool);
272
+ const inputSchema = unwrapJsonSchema(
273
+ tool.inputSchema ?? tool.parameters ?? tool.schema ?? { type: "object" }
274
+ );
275
+ normalized.push({
276
+ type: "function",
277
+ function: {
278
+ name,
279
+ ...(typeof tool.description === "string" ? { description: tool.description } : {}),
280
+ parameters: inputSchema,
281
+ },
282
+ });
283
+ }
284
+
285
+ return normalized.length > 0 ? normalized : undefined;
286
+ }
287
+
288
+ function normalizeNativeToolChoice(toolChoice: unknown): unknown {
289
+ if (!toolChoice) {
290
+ return undefined;
291
+ }
292
+
293
+ if (
294
+ typeof toolChoice === "string" &&
295
+ (toolChoice === "auto" || toolChoice === "none" || toolChoice === "required")
296
+ ) {
297
+ return toolChoice;
298
+ }
299
+
300
+ const choice = asRecord(toolChoice);
301
+ if (choice.type === "function") {
302
+ return toolChoice;
303
+ }
304
+ if (choice.type === "tool") {
305
+ const toolName = firstString(choice.toolName, choice.name);
306
+ return toolName ? { type: "function", function: { name: toolName } } : toolChoice;
307
+ }
308
+
309
+ const functionChoice = asRecord(choice.function);
310
+ const toolName = firstString(choice.toolName, choice.name, functionChoice.name);
311
+ return toolName ? { type: "function", function: { name: toolName } } : toolChoice;
312
+ }
313
+
314
+ function buildNativeResponseFormat(responseSchema: unknown): unknown {
315
+ if (!responseSchema) {
316
+ return undefined;
317
+ }
318
+
319
+ const schemaRecord = asRecord(responseSchema);
320
+ if (schemaRecord.responseFormat) {
321
+ return schemaRecord.responseFormat;
322
+ }
323
+
324
+ const schemaOptions =
325
+ "schema" in schemaRecord
326
+ ? {
327
+ schema: schemaRecord.schema,
328
+ name: firstString(schemaRecord.name) ?? "structured_response",
329
+ description: firstString(schemaRecord.description),
330
+ }
331
+ : { schema: responseSchema, name: "structured_response", description: undefined };
332
+
333
+ return {
334
+ type: "json_schema",
335
+ json_schema: {
336
+ name: schemaOptions.name,
337
+ ...(schemaOptions.description ? { description: schemaOptions.description } : {}),
338
+ schema: schemaOptions.schema,
339
+ },
340
+ };
341
+ }
342
+
343
+ function resolvePromptCacheKey(providerOptions: Record<string, unknown>): string | undefined {
344
+ const eliza = recordAt(providerOptions, "eliza");
345
+ const openrouter = recordAt(providerOptions, "openrouter");
346
+ const openai = recordAt(providerOptions, "openai");
347
+ const cerebras = recordAt(providerOptions, "cerebras");
348
+
349
+ return firstString(
350
+ providerOptions.promptCacheKey,
351
+ providerOptions.prompt_cache_key,
352
+ eliza.promptCacheKey,
353
+ eliza.prompt_cache_key,
354
+ openrouter.promptCacheKey,
355
+ openrouter.prompt_cache_key,
356
+ openai.promptCacheKey,
357
+ openai.prompt_cache_key,
358
+ cerebras.promptCacheKey,
359
+ cerebras.prompt_cache_key
360
+ );
361
+ }
362
+
363
+ function resolveNativeProviderOptions(
364
+ params: GenerateTextParamsWithNativeOptions
365
+ ): Record<string, unknown> | undefined {
366
+ const raw = asRecord(params.providerOptions);
367
+ if (Object.keys(raw).length === 0) {
368
+ return undefined;
369
+ }
370
+
371
+ const { agentName: _agentName, eliza: _eliza, ...rest } = raw;
372
+ const providerOptions: Record<string, unknown> = { ...rest };
373
+ const promptCacheKey = resolvePromptCacheKey(raw);
374
+
375
+ if (promptCacheKey) {
376
+ providerOptions.openai = {
377
+ ...recordAt(providerOptions, "openai"),
378
+ promptCacheKey,
379
+ prompt_cache_key: promptCacheKey,
380
+ };
381
+ providerOptions.openrouter = {
382
+ ...recordAt(providerOptions, "openrouter"),
383
+ promptCacheKey,
384
+ prompt_cache_key: promptCacheKey,
385
+ };
386
+ providerOptions.cerebras = {
387
+ ...recordAt(providerOptions, "cerebras"),
388
+ prompt_cache_key: promptCacheKey,
389
+ };
390
+ }
391
+
392
+ return Object.keys(providerOptions).length > 0 ? providerOptions : undefined;
393
+ }
394
+
395
+ function applyOpenRouterPassthroughFields(
396
+ requestBody: Record<string, unknown>,
397
+ providerOptions: Record<string, unknown> | undefined
398
+ ): void {
399
+ if (!providerOptions) {
400
+ return;
401
+ }
402
+
403
+ const openrouter = recordAt(providerOptions, "openrouter");
404
+ if (Object.keys(openrouter).length > 0) {
405
+ const provider = openrouter.provider;
406
+ if (provider !== undefined) {
407
+ requestBody.provider = provider;
408
+ }
409
+ for (const key of ["models", "route", "transforms", "reasoning"] as const) {
410
+ if (openrouter[key] !== undefined) {
411
+ requestBody[key] = openrouter[key];
412
+ }
413
+ }
414
+ }
415
+
416
+ const gateway = providerOptions.gateway;
417
+ if (gateway !== undefined) {
418
+ requestBody.gateway = gateway;
419
+ }
420
+ }
421
+
422
+ function buildNativeRequestBody(
423
+ params: GenerateTextParamsWithNativeOptions,
424
+ modelName: string,
425
+ promptText: string,
426
+ systemPrompt?: string
427
+ ): Record<string, unknown> {
428
+ const providerOptions = resolveNativeProviderOptions(params);
429
+ const promptCacheKey = providerOptions ? resolvePromptCacheKey(providerOptions) : undefined;
430
+ const tools = normalizeNativeTools(params.tools);
431
+ const toolChoice = normalizeNativeToolChoice(params.toolChoice);
432
+ const responseFormat = buildNativeResponseFormat(params.responseSchema);
433
+ const requestBody: Record<string, unknown> = {
434
+ model: modelName,
435
+ messages: buildNativeMessages(params, promptText, systemPrompt),
436
+ max_tokens: params.maxTokens ?? 8192,
437
+ };
438
+
439
+ if (!isReasoningModel(modelName) && typeof params.temperature === "number") {
440
+ requestBody.temperature = params.temperature;
441
+ }
442
+ if (tools) {
443
+ requestBody.tools = tools;
444
+ }
445
+ if (toolChoice) {
446
+ requestBody.tool_choice = toolChoice;
447
+ }
448
+ if (responseFormat) {
449
+ requestBody.response_format = responseFormat;
450
+ }
451
+ if (providerOptions) {
452
+ requestBody.providerOptions = providerOptions;
453
+ requestBody.provider_options = providerOptions;
454
+ }
455
+ if (promptCacheKey) {
456
+ requestBody.promptCacheKey = promptCacheKey;
457
+ requestBody.prompt_cache_key = promptCacheKey;
458
+ }
459
+
460
+ applyOpenRouterPassthroughFields(requestBody, providerOptions);
461
+ return requestBody;
462
+ }
463
+
464
+ function extractTextFromContent(content: unknown): string {
465
+ if (typeof content === "string") {
466
+ return content;
467
+ }
468
+ if (!Array.isArray(content)) {
469
+ return "";
470
+ }
471
+ return content
472
+ .map((item) => {
473
+ if (typeof item === "string") return item;
474
+ const record = asRecord(item);
475
+ return firstString(record.text, record.output_text, record.content) ?? "";
476
+ })
477
+ .join("");
478
+ }
479
+
480
+ function extractChatCompletionText(data: ChatCompletionsResponse): string {
481
+ const firstChoice = data.choices?.[0];
482
+ if (!firstChoice) {
483
+ return "";
484
+ }
485
+ return firstString(firstChoice.text, extractTextFromContent(firstChoice.message?.content)) ?? "";
486
+ }
487
+
488
+ function extractNativeToolCalls(data: ChatCompletionsResponse): NativeToolCall[] {
489
+ const rawCalls = data.choices?.[0]?.message?.tool_calls ?? [];
490
+ if (!Array.isArray(rawCalls)) {
491
+ return [];
492
+ }
493
+
494
+ return rawCalls
495
+ .map<NativeToolCall | undefined>((rawCall) => {
496
+ const call = asRecord(rawCall);
497
+ const fn = recordAt(call, "function");
498
+ const toolName = firstString(call.name, call.toolName, fn.name);
499
+ if (!toolName) {
500
+ return undefined;
501
+ }
502
+ return {
503
+ type: "tool-call",
504
+ toolCallId: firstString(call.id, call.toolCallId) ?? `call_${toolName}`,
505
+ toolName,
506
+ input: parseJsonIfPossible(call.input ?? call.arguments ?? fn.arguments ?? {}),
507
+ };
508
+ })
509
+ .filter((call): call is NativeToolCall => call !== undefined);
510
+ }
511
+
512
+ function convertNativeUsage(usage: unknown): NativeTokenUsage | undefined {
513
+ const root = asRecord(usage);
514
+ if (Object.keys(root).length === 0) {
515
+ return undefined;
516
+ }
517
+
518
+ const inputTokenDetails = recordAt(root, "inputTokenDetails");
519
+ const promptTokenDetails = recordAt(root, "prompt_tokens_details");
520
+ const inputTokenDetailsSnake = recordAt(root, "input_tokens_details");
521
+ const promptTokens =
522
+ firstNumber(root.inputTokens, root.input_tokens, root.promptTokens, root.prompt_tokens) ?? 0;
523
+ const completionTokens =
524
+ firstNumber(
525
+ root.outputTokens,
526
+ root.output_tokens,
527
+ root.completionTokens,
528
+ root.completion_tokens
529
+ ) ?? 0;
530
+ const cacheReadInputTokens = firstNumber(
531
+ root.cacheReadInputTokens,
532
+ root.cache_read_input_tokens,
533
+ root.cachedInputTokens,
534
+ root.cached_input_tokens,
535
+ root.cachedTokens,
536
+ root.cached_tokens,
537
+ inputTokenDetails.cacheReadTokens,
538
+ inputTokenDetails.cachedInputTokens,
539
+ inputTokenDetails.cachedTokens,
540
+ promptTokenDetails.cached_tokens,
541
+ inputTokenDetailsSnake.cache_read_input_tokens,
542
+ inputTokenDetailsSnake.cached_tokens
543
+ );
544
+ const cacheCreationInputTokens = firstNumber(
545
+ root.cacheCreationInputTokens,
546
+ root.cache_creation_input_tokens,
547
+ root.cacheWriteInputTokens,
548
+ root.cache_write_input_tokens,
549
+ inputTokenDetails.cacheCreationInputTokens,
550
+ inputTokenDetails.cacheCreationTokens,
551
+ inputTokenDetails.cacheWriteTokens,
552
+ inputTokenDetailsSnake.cache_creation_input_tokens
553
+ );
554
+
555
+ return {
556
+ promptTokens,
557
+ completionTokens,
558
+ totalTokens:
559
+ firstNumber(root.totalTokens, root.total_tokens) ?? promptTokens + completionTokens,
560
+ cachedPromptTokens: cacheReadInputTokens,
561
+ cacheReadInputTokens,
562
+ cacheCreationInputTokens,
563
+ };
564
+ }
565
+
566
+ type TextModelType =
567
+ | typeof TEXT_NANO_MODEL_TYPE
568
+ | typeof TEXT_MEDIUM_MODEL_TYPE
569
+ | typeof TEXT_SMALL_MODEL_TYPE
570
+ | typeof TEXT_LARGE_MODEL_TYPE
571
+ | typeof TEXT_MEGA_MODEL_TYPE
572
+ | typeof RESPONSE_HANDLER_MODEL_TYPE
573
+ | typeof ACTION_PLANNER_MODEL_TYPE;
574
+
575
+ function getPurposeForModelType(modelType: TextModelType): string {
576
+ switch (modelType) {
577
+ case RESPONSE_HANDLER_MODEL_TYPE:
578
+ return "should_respond";
579
+ case ACTION_PLANNER_MODEL_TYPE:
580
+ return "action_planner";
581
+ default:
582
+ return "response";
583
+ }
584
+ }
585
+
586
+ function getModelNameForType(runtime: IAgentRuntime, modelType: TextModelType): string {
587
+ switch (modelType) {
588
+ case TEXT_NANO_MODEL_TYPE:
589
+ return getNanoModel(runtime);
590
+ case TEXT_MEDIUM_MODEL_TYPE:
591
+ return getMediumModel(runtime);
592
+ case TEXT_SMALL_MODEL_TYPE:
593
+ return getSmallModel(runtime);
594
+ case TEXT_LARGE_MODEL_TYPE:
595
+ return getLargeModel(runtime);
596
+ case TEXT_MEGA_MODEL_TYPE:
597
+ return getMegaModel(runtime);
598
+ case RESPONSE_HANDLER_MODEL_TYPE:
599
+ return getResponseHandlerModel(runtime);
600
+ case ACTION_PLANNER_MODEL_TYPE:
601
+ return getActionPlannerModel(runtime);
602
+ default:
603
+ return getLargeModel(runtime);
604
+ }
605
+ }
606
+
607
+ function buildGenerateParams(
608
+ runtime: IAgentRuntime,
609
+ modelType: TextModelType,
610
+ params: GenerateTextParams
611
+ ) {
612
+ const paramsWithAttachments = params as GenerateTextParamsWithAttachments;
613
+ const prompt = params.prompt ?? "";
614
+ const maxTokens = params.maxTokens ?? 8192;
615
+
616
+ const openai = createOpenAIClient(runtime);
617
+ const modelName = getModelNameForType(runtime, modelType);
618
+ const experimentalTelemetry = getExperimentalTelemetry(runtime);
619
+ const userContent =
620
+ (paramsWithAttachments.attachments?.length ?? 0) > 0
621
+ ? buildUserContent(paramsWithAttachments)
622
+ : undefined;
623
+
624
+ // Use openai.chat() (Chat Completions API) instead of openai.languageModel()
625
+ // (Responses API). The Responses API unconditionally rejects presencePenalty,
626
+ // frequencyPenalty, and stopSequences for ALL models, emitting noisy warnings.
627
+ // The Chat Completions API supports these features natively and handles
628
+ // reasoning models gracefully when the params are omitted.
629
+ const model = openai.chat(modelName) as LanguageModel;
630
+
631
+ // Reasoning models don't support temperature, frequency/presence penalties,
632
+ // or stopSequences. Detect via model name patterns.
633
+ const reasoning = isReasoningModel(modelName);
634
+ const stopSequences =
635
+ !reasoning &&
636
+ supportsStopSequences(modelName) &&
637
+ Array.isArray(params.stopSequences) &&
638
+ params.stopSequences.length > 0
639
+ ? params.stopSequences
640
+ : undefined;
641
+ const systemPrompt = resolveEffectiveSystemPrompt({
642
+ params,
643
+ fallback: buildCanonicalSystemPrompt({ character: runtime.character }),
644
+ });
645
+ const promptText =
646
+ renderChatMessagesForPrompt(params.messages, {
647
+ omitDuplicateSystem: systemPrompt,
648
+ }) ?? prompt;
649
+
650
+ const generateParams = {
651
+ model,
652
+ ...(userContent
653
+ ? { messages: [{ role: "user" as const, content: userContent }] }
654
+ : { prompt: promptText }),
655
+ system: systemPrompt,
656
+ ...(stopSequences ? { stopSequences } : {}),
657
+ maxOutputTokens: maxTokens,
658
+ experimental_telemetry: {
659
+ isEnabled: experimentalTelemetry,
660
+ },
661
+ };
662
+
663
+ return { generateParams, modelName, modelType, prompt: promptText, systemPrompt };
664
+ }
665
+
666
+ async function generateTextWithModel(
667
+ runtime: IAgentRuntime,
668
+ modelType: TextModelType,
669
+ params: GenerateTextParams
670
+ ): Promise<string | TextStreamResult> {
671
+ const { modelName, prompt, systemPrompt } = buildGenerateParams(runtime, modelType, params);
672
+ const paramsWithNative = params as GenerateTextParamsWithNativeOptions;
673
+
674
+ logger.debug(`[ELIZAOS_CLOUD] Generating text with ${modelType} model: ${modelName}`);
675
+
676
+ if (params.stream) {
677
+ logger.debug(
678
+ "[ELIZAOS_CLOUD] Streaming text disabled for responses compatibility; falling back to buffered response."
679
+ );
680
+ }
681
+
682
+ logger.log(`[ELIZAOS_CLOUD] Using ${modelType} model: ${modelName}`);
683
+ logger.log(prompt);
684
+
685
+ if (hasNativeTransportOptions(paramsWithNative)) {
686
+ const nativeResult = await generateNativeChatCompletion(runtime, modelType, paramsWithNative, {
687
+ modelName,
688
+ prompt,
689
+ systemPrompt,
690
+ });
691
+ return shouldReturnNativeResult(paramsWithNative)
692
+ ? (nativeResult as NativeGenerateTextModelResult)
693
+ : nativeResult.text;
694
+ }
695
+
696
+ const reasoning = isReasoningModel(modelName);
697
+ const input: Array<{
698
+ role: "system" | "user";
699
+ content: Array<{ type: "input_text"; text: string }>;
700
+ }> = [];
701
+ if (systemPrompt) {
702
+ input.push({
703
+ role: "system",
704
+ content: [{ type: "input_text", text: systemPrompt }],
705
+ });
706
+ }
707
+ input.push({
708
+ role: "user",
709
+ content: [{ type: "input_text", text: prompt }],
710
+ });
711
+
712
+ const requestBody: Record<string, unknown> = {
713
+ model: modelName,
714
+ input,
715
+ max_output_tokens: params.maxTokens ?? 8192,
716
+ };
717
+ if (!reasoning && typeof params.temperature === "number") {
718
+ requestBody.temperature = params.temperature;
719
+ }
720
+
721
+ const response = await createCloudApiClient(runtime).requestRaw("POST", "/responses", {
722
+ headers: {
723
+ "X-Eliza-Llm-Purpose": getPurposeForModelType(modelType),
724
+ "X-Eliza-Model-Type": modelType,
725
+ },
726
+ json: requestBody,
727
+ });
728
+ const responseText = await response.text();
729
+ let data: ResponsesApiResponse = {};
730
+ if (responseText) {
731
+ try {
732
+ data = JSON.parse(responseText) as ResponsesApiResponse;
733
+ } catch (parseErr) {
734
+ logger.error(
735
+ `[ELIZAOS_CLOUD] Failed to parse responses JSON: ${
736
+ parseErr instanceof Error ? parseErr.message : String(parseErr)
737
+ }`
738
+ );
739
+ }
740
+ }
741
+
742
+ if (!response.ok) {
743
+ const errorBody = typeof data === "object" && data ? data.error : undefined;
744
+ const errorMessage =
745
+ typeof errorBody?.message === "string" && errorBody.message.trim()
746
+ ? errorBody.message.trim()
747
+ : `elizaOS Cloud error ${response.status}`;
748
+ const requestError = new Error(errorMessage) as Error & {
749
+ status?: number;
750
+ error?: unknown;
751
+ };
752
+ requestError.status = response.status;
753
+ if (errorBody) {
754
+ requestError.error = errorBody;
755
+ }
756
+ throw requestError;
757
+ }
758
+
759
+ if (data.usage) {
760
+ emitModelUsageEvent(runtime, modelType, prompt, {
761
+ inputTokens: data.usage.input_tokens ?? 0,
762
+ outputTokens: data.usage.output_tokens ?? 0,
763
+ totalTokens: data.usage.total_tokens ?? 0,
764
+ });
765
+ }
766
+
767
+ const text = extractResponsesOutputText(data);
768
+ if (!text.trim()) {
769
+ throw new Error("elizaOS Cloud returned no text response");
770
+ }
771
+
772
+ return text;
773
+ }
774
+
775
+ async function generateNativeChatCompletion(
776
+ runtime: IAgentRuntime,
777
+ modelType: TextModelType,
778
+ params: GenerateTextParamsWithNativeOptions,
779
+ context: {
780
+ modelName: string;
781
+ prompt: string;
782
+ systemPrompt?: string;
783
+ }
784
+ ): Promise<NativeGenerateTextResult> {
785
+ const requestBody = buildNativeRequestBody(
786
+ params,
787
+ context.modelName,
788
+ context.prompt,
789
+ context.systemPrompt
790
+ );
791
+ const response = await createCloudApiClient(runtime).requestRaw("POST", "/chat/completions", {
792
+ headers: {
793
+ "X-Eliza-Llm-Purpose": getPurposeForModelType(modelType),
794
+ "X-Eliza-Model-Type": modelType,
795
+ },
796
+ json: requestBody,
797
+ });
798
+ const responseText = await response.text();
799
+ let data: ChatCompletionsResponse = {};
800
+ if (responseText) {
801
+ try {
802
+ data = JSON.parse(responseText) as ChatCompletionsResponse;
803
+ } catch (parseErr) {
804
+ logger.error(
805
+ `[ELIZAOS_CLOUD] Failed to parse chat completions JSON: ${
806
+ parseErr instanceof Error ? parseErr.message : String(parseErr)
807
+ }`
808
+ );
809
+ }
810
+ }
811
+
812
+ if (!response.ok) {
813
+ const errorBody = typeof data === "object" && data ? data.error : undefined;
814
+ const errorMessage =
815
+ typeof errorBody?.message === "string" && errorBody.message.trim()
816
+ ? errorBody.message.trim()
817
+ : `elizaOS Cloud error ${response.status}`;
818
+ const requestError = new Error(errorMessage) as Error & {
819
+ status?: number;
820
+ error?: unknown;
821
+ };
822
+ requestError.status = response.status;
823
+ if (errorBody) {
824
+ requestError.error = errorBody;
825
+ }
826
+ throw requestError;
827
+ }
828
+
829
+ const usage = convertNativeUsage(data.usage);
830
+ if (usage) {
831
+ emitModelUsageEvent(runtime, modelType, context.prompt, usage);
832
+ }
833
+
834
+ const text = extractChatCompletionText(data);
835
+ const toolCalls = extractNativeToolCalls(data);
836
+ if (!text.trim() && toolCalls.length === 0) {
837
+ throw new Error("elizaOS Cloud returned no text or tool calls");
838
+ }
839
+
840
+ return {
841
+ text,
842
+ toolCalls,
843
+ finishReason: data.choices?.[0]?.finish_reason,
844
+ usage,
845
+ providerMetadata: {
846
+ modelName: context.modelName,
847
+ usage: data.usage,
848
+ },
849
+ };
850
+ }
851
+
852
+ export async function handleTextSmall(
853
+ runtime: IAgentRuntime,
854
+ params: GenerateTextParams
855
+ ): Promise<string | TextStreamResult> {
856
+ return generateTextWithModel(runtime, TEXT_SMALL_MODEL_TYPE, params);
857
+ }
858
+
859
+ export async function handleTextNano(
860
+ runtime: IAgentRuntime,
861
+ params: GenerateTextParams
862
+ ): Promise<string | TextStreamResult> {
863
+ return generateTextWithModel(runtime, TEXT_NANO_MODEL_TYPE, params);
864
+ }
865
+
866
+ export async function handleTextMedium(
867
+ runtime: IAgentRuntime,
868
+ params: GenerateTextParams
869
+ ): Promise<string | TextStreamResult> {
870
+ return generateTextWithModel(runtime, TEXT_MEDIUM_MODEL_TYPE, params);
871
+ }
872
+
873
+ export async function handleTextLarge(
874
+ runtime: IAgentRuntime,
875
+ params: GenerateTextParams
876
+ ): Promise<string | TextStreamResult> {
877
+ return generateTextWithModel(runtime, TEXT_LARGE_MODEL_TYPE, params);
878
+ }
879
+
880
+ export async function handleTextMega(
881
+ runtime: IAgentRuntime,
882
+ params: GenerateTextParams
883
+ ): Promise<string | TextStreamResult> {
884
+ return generateTextWithModel(runtime, TEXT_MEGA_MODEL_TYPE, params);
885
+ }
886
+
887
+ export async function handleResponseHandler(
888
+ runtime: IAgentRuntime,
889
+ params: GenerateTextParams
890
+ ): Promise<string | TextStreamResult> {
891
+ return generateTextWithModel(runtime, RESPONSE_HANDLER_MODEL_TYPE, params);
892
+ }
893
+
894
+ export async function handleActionPlanner(
895
+ runtime: IAgentRuntime,
896
+ params: GenerateTextParams
897
+ ): Promise<string | TextStreamResult> {
898
+ return generateTextWithModel(runtime, ACTION_PLANNER_MODEL_TYPE, params);
899
+ }