@resolveio/server-lib 22.3.57 → 22.3.59

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 (691) hide show
  1. package/ai/assistant-core-heuristics.d.ts +11 -0
  2. package/ai/assistant-core-heuristics.js +356 -0
  3. package/ai/assistant-core-heuristics.js.map +1 -0
  4. package/ai/resolveio-platform-intelligence-memory-corpus.d.ts +3 -0
  5. package/ai/resolveio-platform-intelligence-memory-corpus.js +214 -0
  6. package/ai/resolveio-platform-intelligence-memory-corpus.js.map +1 -0
  7. package/ai/resolveio-platform-intelligence-memory.d.ts +20 -0
  8. package/ai/resolveio-platform-intelligence-memory.js +341 -0
  9. package/ai/resolveio-platform-intelligence-memory.js.map +1 -0
  10. package/{src/ai/resolveio-platform-intelligence-types.ts → ai/resolveio-platform-intelligence-types.d.ts} +15 -20
  11. package/ai/resolveio-platform-intelligence-types.js +4 -0
  12. package/ai/resolveio-platform-intelligence-types.js.map +1 -0
  13. package/ai/resolveio-platform-intelligence.d.ts +6 -0
  14. package/ai/resolveio-platform-intelligence.js +463 -0
  15. package/ai/resolveio-platform-intelligence.js.map +1 -0
  16. package/client-server-app.d.ts +1 -0
  17. package/client-server-app.js +68 -0
  18. package/client-server-app.js.map +1 -0
  19. package/collections/ai-terminal-conversation.collection.d.ts +2 -0
  20. package/collections/ai-terminal-conversation.collection.js +140 -0
  21. package/collections/ai-terminal-conversation.collection.js.map +1 -0
  22. package/collections/ai-terminal-issue-report.collection.d.ts +2 -0
  23. package/collections/ai-terminal-issue-report.collection.js +148 -0
  24. package/collections/ai-terminal-issue-report.collection.js.map +1 -0
  25. package/collections/ai-terminal-message.collection.d.ts +2 -0
  26. package/collections/ai-terminal-message.collection.js +121 -0
  27. package/collections/ai-terminal-message.collection.js.map +1 -0
  28. package/collections/app-setting.collection.d.ts +3 -0
  29. package/collections/app-setting.collection.js +103 -0
  30. package/collections/app-setting.collection.js.map +1 -0
  31. package/collections/app-status.collection.d.ts +3 -0
  32. package/collections/app-status.collection.js +57 -0
  33. package/collections/app-status.collection.js.map +1 -0
  34. package/collections/communication-metric.collection.d.ts +2 -0
  35. package/collections/communication-metric.collection.js +133 -0
  36. package/collections/communication-metric.collection.js.map +1 -0
  37. package/collections/counter.collection.d.ts +3 -0
  38. package/collections/counter.collection.js +56 -0
  39. package/collections/counter.collection.js.map +1 -0
  40. package/collections/cron-job-history.collection.d.ts +3 -0
  41. package/collections/cron-job-history.collection.js +137 -0
  42. package/collections/cron-job-history.collection.js.map +1 -0
  43. package/collections/cron-job.collection.d.ts +3 -0
  44. package/collections/cron-job.collection.js +92 -0
  45. package/collections/cron-job.collection.js.map +1 -0
  46. package/collections/customer-notification.collection.d.ts +3 -0
  47. package/collections/customer-notification.collection.js +130 -0
  48. package/collections/customer-notification.collection.js.map +1 -0
  49. package/collections/customer-portal-password.collection.d.ts +3 -0
  50. package/collections/customer-portal-password.collection.js +75 -0
  51. package/collections/customer-portal-password.collection.js.map +1 -0
  52. package/collections/email-history.collection.d.ts +3 -0
  53. package/collections/email-history.collection.js +127 -0
  54. package/collections/email-history.collection.js.map +1 -0
  55. package/collections/email-verified.collection.d.ts +3 -0
  56. package/collections/email-verified.collection.js +62 -0
  57. package/collections/email-verified.collection.js.map +1 -0
  58. package/collections/file.collection.d.ts +3 -0
  59. package/collections/file.collection.js +74 -0
  60. package/collections/file.collection.js.map +1 -0
  61. package/collections/flag-update.collection.d.ts +3 -0
  62. package/collections/flag-update.collection.js +57 -0
  63. package/collections/flag-update.collection.js.map +1 -0
  64. package/collections/flag.collection.d.ts +3 -0
  65. package/collections/flag.collection.js +57 -0
  66. package/collections/flag.collection.js.map +1 -0
  67. package/collections/log-method-latency.collection.d.ts +3 -0
  68. package/collections/log-method-latency.collection.js +77 -0
  69. package/collections/log-method-latency.collection.js.map +1 -0
  70. package/collections/log-subscription.collection.d.ts +3 -0
  71. package/collections/log-subscription.collection.js +80 -0
  72. package/collections/log-subscription.collection.js.map +1 -0
  73. package/collections/log.collection.d.ts +3 -0
  74. package/collections/log.collection.js +93 -0
  75. package/collections/log.collection.js.map +1 -0
  76. package/collections/logged-in-users.collection.d.ts +3 -0
  77. package/collections/logged-in-users.collection.js +67 -0
  78. package/collections/logged-in-users.collection.js.map +1 -0
  79. package/collections/monitor-cpu.collection.d.ts +3 -0
  80. package/collections/monitor-cpu.collection.js +65 -0
  81. package/collections/monitor-cpu.collection.js.map +1 -0
  82. package/collections/monitor-function.collection.d.ts +3 -0
  83. package/collections/monitor-function.collection.js +74 -0
  84. package/collections/monitor-function.collection.js.map +1 -0
  85. package/collections/monitor-memory.collection.d.ts +3 -0
  86. package/collections/monitor-memory.collection.js +77 -0
  87. package/collections/monitor-memory.collection.js.map +1 -0
  88. package/collections/monitor-mongo.collection.d.ts +3 -0
  89. package/collections/monitor-mongo.collection.js +71 -0
  90. package/collections/monitor-mongo.collection.js.map +1 -0
  91. package/collections/notification.collection.d.ts +3 -0
  92. package/collections/notification.collection.js +57 -0
  93. package/collections/notification.collection.js.map +1 -0
  94. package/collections/openai-usage-ledger.collection.d.ts +2 -0
  95. package/collections/openai-usage-ledger.collection.js +124 -0
  96. package/collections/openai-usage-ledger.collection.js.map +1 -0
  97. package/collections/report-builder-dashboard-builder.collection.d.ts +3 -0
  98. package/collections/report-builder-dashboard-builder.collection.js +109 -0
  99. package/collections/report-builder-dashboard-builder.collection.js.map +1 -0
  100. package/collections/report-builder-library.collection.d.ts +3 -0
  101. package/collections/report-builder-library.collection.js +87 -0
  102. package/collections/report-builder-library.collection.js.map +1 -0
  103. package/collections/report-builder-report.collection.d.ts +4 -0
  104. package/collections/report-builder-report.collection.js +184 -0
  105. package/collections/report-builder-report.collection.js.map +1 -0
  106. package/collections/user-group.collection.d.ts +4 -0
  107. package/collections/user-group.collection.js +89 -0
  108. package/collections/user-group.collection.js.map +1 -0
  109. package/collections/user-guide.collection.d.ts +3 -0
  110. package/collections/user-guide.collection.js +57 -0
  111. package/collections/user-guide.collection.js.map +1 -0
  112. package/collections/user.collection.d.ts +4 -0
  113. package/collections/user.collection.js +180 -0
  114. package/collections/user.collection.js.map +1 -0
  115. package/cron/cron.d.ts +14 -0
  116. package/cron/cron.js +216 -0
  117. package/cron/cron.js.map +1 -0
  118. package/fixtures/cron-jobs.d.ts +1 -0
  119. package/fixtures/cron-jobs.js +150 -0
  120. package/fixtures/cron-jobs.js.map +1 -0
  121. package/fixtures/init.d.ts +1 -0
  122. package/fixtures/init.js +91 -0
  123. package/fixtures/init.js.map +1 -0
  124. package/http/auth.d.ts +2 -0
  125. package/http/auth.js +906 -0
  126. package/http/auth.js.map +1 -0
  127. package/http/health.d.ts +1 -0
  128. package/http/health.js +11 -0
  129. package/http/health.js.map +1 -0
  130. package/http/home.d.ts +1 -0
  131. package/http/home.js +134 -0
  132. package/http/home.js.map +1 -0
  133. package/http/slow-query-publication.d.ts +2 -0
  134. package/http/slow-query-publication.js +99 -0
  135. package/http/slow-query-publication.js.map +1 -0
  136. package/index.d.ts +1 -0
  137. package/index.js +19 -0
  138. package/index.js.map +1 -0
  139. package/managers/ai-assistant-codex-manager.manager.d.ts +67 -0
  140. package/managers/ai-assistant-codex-manager.manager.js +1113 -0
  141. package/managers/ai-assistant-codex-manager.manager.js.map +1 -0
  142. package/managers/communication-metric.manager.d.ts +16 -0
  143. package/managers/communication-metric.manager.js +134 -0
  144. package/managers/communication-metric.manager.js.map +1 -0
  145. package/managers/cron.manager.d.ts +20 -0
  146. package/managers/cron.manager.js +534 -0
  147. package/managers/cron.manager.js.map +1 -0
  148. package/managers/customer-notification-content.manager.d.ts +55 -0
  149. package/managers/customer-notification-content.manager.js +158 -0
  150. package/managers/customer-notification-content.manager.js.map +1 -0
  151. package/managers/diagnostic-manager-bootstrap.d.ts +9 -0
  152. package/managers/diagnostic-manager-bootstrap.js +260 -0
  153. package/managers/diagnostic-manager-bootstrap.js.map +1 -0
  154. package/managers/error-auto-fix.manager.d.ts +149 -0
  155. package/managers/error-auto-fix.manager.js +3064 -0
  156. package/managers/error-auto-fix.manager.js.map +1 -0
  157. package/managers/local-log.manager.d.ts +18 -0
  158. package/managers/local-log.manager.js +88 -0
  159. package/managers/local-log.manager.js.map +1 -0
  160. package/managers/method.manager.d.ts +83 -0
  161. package/managers/method.manager.js +1941 -0
  162. package/managers/method.manager.js.map +1 -0
  163. package/managers/mongo.manager.d.ts +224 -0
  164. package/managers/mongo.manager.js +5000 -0
  165. package/managers/mongo.manager.js.map +1 -0
  166. package/managers/monitor.manager.d.ts +70 -0
  167. package/managers/monitor.manager.js +550 -0
  168. package/managers/monitor.manager.js.map +1 -0
  169. package/managers/openai-usage-ledger.manager.d.ts +15 -0
  170. package/managers/openai-usage-ledger.manager.js +144 -0
  171. package/managers/openai-usage-ledger.manager.js.map +1 -0
  172. package/managers/slow-query-verifier.manager.d.ts +144 -0
  173. package/managers/slow-query-verifier.manager.js +3857 -0
  174. package/managers/slow-query-verifier.manager.js.map +1 -0
  175. package/managers/slow-query.manager.d.ts +28 -0
  176. package/managers/slow-query.manager.js +468 -0
  177. package/managers/slow-query.manager.js.map +1 -0
  178. package/managers/subscription.manager.d.ts +169 -0
  179. package/managers/subscription.manager.js +3434 -0
  180. package/managers/subscription.manager.js.map +1 -0
  181. package/managers/websocket.manager.d.ts +73 -0
  182. package/managers/websocket.manager.js +673 -0
  183. package/managers/websocket.manager.js.map +1 -0
  184. package/managers/worker-dispatcher.manager.d.ts +120 -0
  185. package/managers/worker-dispatcher.manager.js +1266 -0
  186. package/managers/worker-dispatcher.manager.js.map +1 -0
  187. package/managers/worker-server.manager.d.ts +35 -0
  188. package/managers/worker-server.manager.js +582 -0
  189. package/managers/worker-server.manager.js.map +1 -0
  190. package/methods/accounts.d.ts +2 -0
  191. package/methods/accounts.js +624 -0
  192. package/methods/accounts.js.map +1 -0
  193. package/methods/ai-terminal.d.ts +337 -0
  194. package/methods/ai-terminal.js +23166 -0
  195. package/methods/ai-terminal.js.map +1 -0
  196. package/methods/app-settings.d.ts +2 -0
  197. package/methods/app-settings.js +169 -0
  198. package/methods/app-settings.js.map +1 -0
  199. package/methods/aws.d.ts +2 -0
  200. package/methods/aws.js +877 -0
  201. package/methods/aws.js.map +1 -0
  202. package/methods/collections.d.ts +2 -0
  203. package/methods/collections.js +719 -0
  204. package/methods/collections.js.map +1 -0
  205. package/methods/counters.d.ts +2 -0
  206. package/methods/counters.js +113 -0
  207. package/methods/counters.js.map +1 -0
  208. package/methods/cron-jobs.d.ts +2 -0
  209. package/methods/cron-jobs.js +2475 -0
  210. package/methods/cron-jobs.js.map +1 -0
  211. package/methods/customer-notifications.d.ts +2 -0
  212. package/methods/customer-notifications.js +528 -0
  213. package/methods/customer-notifications.js.map +1 -0
  214. package/methods/diagnostics.d.ts +2 -0
  215. package/methods/diagnostics.js +703 -0
  216. package/methods/diagnostics.js.map +1 -0
  217. package/methods/flag-updates.d.ts +2 -0
  218. package/methods/flag-updates.js +8 -0
  219. package/methods/flag-updates.js.map +1 -0
  220. package/methods/flags.d.ts +2 -0
  221. package/methods/flags.js +8 -0
  222. package/methods/flags.js.map +1 -0
  223. package/methods/logs.d.ts +2 -0
  224. package/methods/logs.js +751 -0
  225. package/methods/logs.js.map +1 -0
  226. package/methods/mongo-explorer.d.ts +2 -0
  227. package/methods/mongo-explorer.js +1808 -0
  228. package/methods/mongo-explorer.js.map +1 -0
  229. package/methods/monitor.d.ts +2 -0
  230. package/methods/monitor.js +543 -0
  231. package/methods/monitor.js.map +1 -0
  232. package/methods/pdf.d.ts +2 -0
  233. package/methods/pdf.js +1216 -0
  234. package/methods/pdf.js.map +1 -0
  235. package/methods/publications.d.ts +1 -0
  236. package/methods/publications.js +183 -0
  237. package/methods/publications.js.map +1 -0
  238. package/methods/report-builder.d.ts +2 -0
  239. package/methods/report-builder.js +3094 -0
  240. package/methods/report-builder.js.map +1 -0
  241. package/methods/support.d.ts +2 -0
  242. package/methods/support.js +430 -0
  243. package/methods/support.js.map +1 -0
  244. package/models/ai-terminal-conversation.model.d.ts +17 -0
  245. package/models/ai-terminal-conversation.model.js +4 -0
  246. package/models/ai-terminal-conversation.model.js.map +1 -0
  247. package/models/ai-terminal-issue-report.model.d.ts +19 -0
  248. package/models/ai-terminal-issue-report.model.js +4 -0
  249. package/models/ai-terminal-issue-report.model.js.map +1 -0
  250. package/models/ai-terminal-message.model.d.ts +22 -0
  251. package/models/ai-terminal-message.model.js +4 -0
  252. package/models/ai-terminal-message.model.js.map +1 -0
  253. package/models/app-setting.model.d.ts +16 -0
  254. package/models/app-setting.model.js +4 -0
  255. package/models/app-setting.model.js.map +1 -0
  256. package/{src/models/app-status.model.ts → models/app-status.model.d.ts} +2 -3
  257. package/models/app-status.model.js +4 -0
  258. package/models/app-status.model.js.map +1 -0
  259. package/{src/models/billing-logged-in-users.model.ts → models/billing-logged-in-users.model.d.ts} +4 -5
  260. package/models/billing-logged-in-users.model.js +4 -0
  261. package/models/billing-logged-in-users.model.js.map +1 -0
  262. package/models/collection-document.model.d.ts +21 -0
  263. package/models/collection-document.model.js +4 -0
  264. package/models/collection-document.model.js.map +1 -0
  265. package/models/communication-metric.model.d.ts +20 -0
  266. package/models/communication-metric.model.js +4 -0
  267. package/models/communication-metric.model.js.map +1 -0
  268. package/{src/models/counter.model.ts → models/counter.model.d.ts} +3 -4
  269. package/models/counter.model.js +4 -0
  270. package/models/counter.model.js.map +1 -0
  271. package/models/cron-job-history.model.d.ts +15 -0
  272. package/models/cron-job-history.model.js +4 -0
  273. package/models/cron-job-history.model.js.map +1 -0
  274. package/models/cron-job.model.d.ts +14 -0
  275. package/models/cron-job.model.js +4 -0
  276. package/models/cron-job.model.js.map +1 -0
  277. package/models/customer-notification.model.d.ts +26 -0
  278. package/models/customer-notification.model.js +4 -0
  279. package/models/customer-notification.model.js.map +1 -0
  280. package/models/customer-portal-password.model.d.ts +11 -0
  281. package/models/customer-portal-password.model.js +4 -0
  282. package/models/customer-portal-password.model.js.map +1 -0
  283. package/models/dialog.model.d.ts +23 -0
  284. package/models/dialog.model.js +4 -0
  285. package/models/dialog.model.js.map +1 -0
  286. package/models/email-history.model.d.ts +31 -0
  287. package/{src/models/email-history.model.ts → models/email-history.model.js} +4 -35
  288. package/models/email-history.model.js.map +1 -0
  289. package/{src/models/email-verified.model.ts → models/email-verified.model.d.ts} +5 -6
  290. package/models/email-verified.model.js +4 -0
  291. package/models/email-verified.model.js.map +1 -0
  292. package/{src/models/file.model.ts → models/file.model.d.ts} +7 -8
  293. package/models/file.model.js +4 -0
  294. package/models/file.model.js.map +1 -0
  295. package/{src/models/flag-update.model.ts → models/flag-update.model.d.ts} +3 -4
  296. package/models/flag-update.model.js +4 -0
  297. package/models/flag-update.model.js.map +1 -0
  298. package/{src/models/flag.model.ts → models/flag.model.d.ts} +3 -4
  299. package/models/flag.model.js +4 -0
  300. package/models/flag.model.js.map +1 -0
  301. package/models/log-method-latency.model.d.ts +10 -0
  302. package/models/log-method-latency.model.js +4 -0
  303. package/models/log-method-latency.model.js.map +1 -0
  304. package/{src/models/log-subscription.model.ts → models/log-subscription.model.d.ts} +9 -11
  305. package/models/log-subscription.model.js +4 -0
  306. package/models/log-subscription.model.js.map +1 -0
  307. package/models/log.model.d.ts +17 -0
  308. package/models/log.model.js +4 -0
  309. package/models/log.model.js.map +1 -0
  310. package/{src/models/logged-in-users.model.ts → models/logged-in-users.model.d.ts} +5 -6
  311. package/models/logged-in-users.model.js +4 -0
  312. package/models/logged-in-users.model.js.map +1 -0
  313. package/{src/models/method-response.model.ts → models/method-response.model.d.ts} +6 -7
  314. package/models/method-response.model.js +4 -0
  315. package/models/method-response.model.js.map +1 -0
  316. package/models/method.model.d.ts +26 -0
  317. package/models/method.model.js +4 -0
  318. package/models/method.model.js.map +1 -0
  319. package/{src/models/monitor-cpu.model.ts → models/monitor-cpu.model.d.ts} +7 -9
  320. package/models/monitor-cpu.model.js +4 -0
  321. package/models/monitor-cpu.model.js.map +1 -0
  322. package/models/monitor-function.model.d.ts +14 -0
  323. package/models/monitor-function.model.js +4 -0
  324. package/models/monitor-function.model.js.map +1 -0
  325. package/models/monitor-memory.model.d.ts +15 -0
  326. package/models/monitor-memory.model.js +4 -0
  327. package/models/monitor-memory.model.js.map +1 -0
  328. package/models/monitor-mongo.model.d.ts +13 -0
  329. package/models/monitor-mongo.model.js +4 -0
  330. package/models/monitor-mongo.model.js.map +1 -0
  331. package/{src/models/notification.model.ts → models/notification.model.d.ts} +4 -6
  332. package/models/notification.model.js +4 -0
  333. package/models/notification.model.js.map +1 -0
  334. package/models/openai-usage-ledger.model.d.ts +15 -0
  335. package/models/openai-usage-ledger.model.js +4 -0
  336. package/models/openai-usage-ledger.model.js.map +1 -0
  337. package/models/pagination.model.d.ts +11 -0
  338. package/models/pagination.model.js +28 -0
  339. package/models/pagination.model.js.map +1 -0
  340. package/models/permission.model.d.ts +12 -0
  341. package/models/permission.model.js +4 -0
  342. package/models/permission.model.js.map +1 -0
  343. package/models/report-builder-dashboard-builder.model.d.ts +25 -0
  344. package/models/report-builder-dashboard-builder.model.js +4 -0
  345. package/models/report-builder-dashboard-builder.model.js.map +1 -0
  346. package/models/report-builder-library.model.d.ts +17 -0
  347. package/models/report-builder-library.model.js +4 -0
  348. package/models/report-builder-library.model.js.map +1 -0
  349. package/models/report-builder-report.model.d.ts +121 -0
  350. package/models/report-builder-report.model.js +4 -0
  351. package/models/report-builder-report.model.js.map +1 -0
  352. package/models/report-builder.model.d.ts +61 -0
  353. package/models/report-builder.model.js +4 -0
  354. package/models/report-builder.model.js.map +1 -0
  355. package/models/select-data-label.model.d.ts +9 -0
  356. package/models/select-data-label.model.js +4 -0
  357. package/models/select-data-label.model.js.map +1 -0
  358. package/models/server-message.model.d.ts +32 -0
  359. package/models/server-message.model.js +4 -0
  360. package/models/server-message.model.js.map +1 -0
  361. package/models/slow-query-report.model.d.ts +23 -0
  362. package/models/slow-query-report.model.js +4 -0
  363. package/models/slow-query-report.model.js.map +1 -0
  364. package/models/subscription.model.d.ts +31 -0
  365. package/models/subscription.model.js +4 -0
  366. package/models/subscription.model.js.map +1 -0
  367. package/models/support-ticket.model.d.ts +87 -0
  368. package/models/support-ticket.model.js +4 -0
  369. package/models/support-ticket.model.js.map +1 -0
  370. package/models/user-group.model.d.ts +20 -0
  371. package/models/user-group.model.js +4 -0
  372. package/models/user-group.model.js.map +1 -0
  373. package/{src/models/user-guide.model.ts → models/user-guide.model.d.ts} +4 -5
  374. package/models/user-guide.model.js +4 -0
  375. package/models/user-guide.model.js.map +1 -0
  376. package/models/user.model.d.ts +84 -0
  377. package/models/user.model.js +4 -0
  378. package/models/user.model.js.map +1 -0
  379. package/package.json +1 -1
  380. package/private/images/ResolveIO.png +0 -0
  381. package/public_api.js +116 -0
  382. package/public_api.js.map +1 -0
  383. package/publications/ai-terminal.d.ts +1 -0
  384. package/publications/ai-terminal.js +122 -0
  385. package/publications/ai-terminal.js.map +1 -0
  386. package/publications/app-settings.d.ts +2 -0
  387. package/publications/app-settings.js +28 -0
  388. package/publications/app-settings.js.map +1 -0
  389. package/publications/app-status.d.ts +2 -0
  390. package/publications/app-status.js +16 -0
  391. package/publications/app-status.js.map +1 -0
  392. package/publications/cron-jobs.d.ts +2 -0
  393. package/publications/cron-jobs.js +88 -0
  394. package/publications/cron-jobs.js.map +1 -0
  395. package/publications/customer-notifications.d.ts +2 -0
  396. package/publications/customer-notifications.js +161 -0
  397. package/publications/customer-notifications.js.map +1 -0
  398. package/publications/files.d.ts +2 -0
  399. package/publications/files.js +36 -0
  400. package/publications/files.js.map +1 -0
  401. package/publications/flags-update.d.ts +2 -0
  402. package/publications/flags-update.js +22 -0
  403. package/publications/flags-update.js.map +1 -0
  404. package/publications/flags.d.ts +2 -0
  405. package/publications/flags.js +22 -0
  406. package/publications/flags.js.map +1 -0
  407. package/publications/logs.d.ts +2 -0
  408. package/publications/logs.js +164 -0
  409. package/publications/logs.js.map +1 -0
  410. package/publications/notifications.d.ts +2 -0
  411. package/publications/notifications.js +16 -0
  412. package/publications/notifications.js.map +1 -0
  413. package/publications/report-builder-dashboard-builders.d.ts +2 -0
  414. package/publications/report-builder-dashboard-builders.js +42 -0
  415. package/publications/report-builder-dashboard-builders.js.map +1 -0
  416. package/publications/report-builder-libraries.d.ts +2 -0
  417. package/publications/report-builder-libraries.js +90 -0
  418. package/publications/report-builder-libraries.js.map +1 -0
  419. package/publications/report-builder-reports.d.ts +2 -0
  420. package/publications/report-builder-reports.js +50 -0
  421. package/publications/report-builder-reports.js.map +1 -0
  422. package/publications/super-admin.d.ts +2 -0
  423. package/publications/super-admin.js +16 -0
  424. package/publications/super-admin.js.map +1 -0
  425. package/publications/user-groups.d.ts +1 -0
  426. package/publications/user-groups.js +16 -0
  427. package/publications/user-groups.js.map +1 -0
  428. package/publications/user-guides.d.ts +1 -0
  429. package/publications/user-guides.js +16 -0
  430. package/publications/user-guides.js.map +1 -0
  431. package/resolveio-server-app.d.ts +70 -0
  432. package/resolveio-server-app.js +801 -0
  433. package/resolveio-server-app.js.map +1 -0
  434. package/server-app.d.ts +228 -0
  435. package/server-app.js +3566 -0
  436. package/server-app.js.map +1 -0
  437. package/services/codex-client.d.ts +126 -0
  438. package/services/codex-client.js +1622 -0
  439. package/services/codex-client.js.map +1 -0
  440. package/services/openai-client.d.ts +46 -0
  441. package/services/openai-client.js +318 -0
  442. package/services/openai-client.js.map +1 -0
  443. package/types/error-report.d.ts +25 -0
  444. package/types/error-report.js +4 -0
  445. package/types/error-report.js.map +1 -0
  446. package/types/slow-query-report.d.ts +27 -0
  447. package/types/slow-query-report.js +6 -0
  448. package/types/slow-query-report.js.map +1 -0
  449. package/util/ai-qa-policy.d.ts +124 -0
  450. package/util/ai-qa-policy.js +707 -0
  451. package/util/ai-qa-policy.js.map +1 -0
  452. package/util/ai-runner-artifacts.d.ts +74 -0
  453. package/util/ai-runner-artifacts.js +531 -0
  454. package/util/ai-runner-artifacts.js.map +1 -0
  455. package/util/ai-runner-qa-auth.d.ts +5 -0
  456. package/util/ai-runner-qa-auth.js +357 -0
  457. package/util/ai-runner-qa-auth.js.map +1 -0
  458. package/util/ai-runner-qa-tools.d.ts +19 -0
  459. package/util/ai-runner-qa-tools.js +777 -0
  460. package/util/ai-runner-qa-tools.js.map +1 -0
  461. package/util/common.d.ts +31 -0
  462. package/util/common.js +683 -0
  463. package/util/common.js.map +1 -0
  464. package/util/customer-portal-password.d.ts +13 -0
  465. package/util/customer-portal-password.js +209 -0
  466. package/util/customer-portal-password.js.map +1 -0
  467. package/util/error-reporter.d.ts +52 -0
  468. package/util/error-reporter.js +326 -0
  469. package/util/error-reporter.js.map +1 -0
  470. package/util/error-tracking.d.ts +13 -0
  471. package/util/error-tracking.js +120 -0
  472. package/util/error-tracking.js.map +1 -0
  473. package/util/report-builder-unwinds.d.ts +15 -0
  474. package/util/report-builder-unwinds.js +156 -0
  475. package/util/report-builder-unwinds.js.map +1 -0
  476. package/util/runner-process-janitor.d.ts +25 -0
  477. package/util/runner-process-janitor.js +199 -0
  478. package/util/runner-process-janitor.js.map +1 -0
  479. package/util/schema-report-builder.d.ts +6 -0
  480. package/util/schema-report-builder.js +481 -0
  481. package/util/schema-report-builder.js.map +1 -0
  482. package/util/slow-query-reporter.d.ts +28 -0
  483. package/util/slow-query-reporter.js +226 -0
  484. package/util/slow-query-reporter.js.map +1 -0
  485. package/util/subscription-dependency-context.d.ts +34 -0
  486. package/util/subscription-dependency-context.js +1283 -0
  487. package/util/subscription-dependency-context.js.map +1 -0
  488. package/util/tokenizer.d.ts +5 -0
  489. package/util/tokenizer.js +41 -0
  490. package/util/tokenizer.js.map +1 -0
  491. package/workers/codex-runner.worker.d.ts +1 -0
  492. package/workers/codex-runner.worker.js +192 -0
  493. package/workers/codex-runner.worker.js.map +1 -0
  494. package/.nodemon.json +0 -5
  495. package/.vscode/settings.json +0 -21
  496. package/AGENTS.md +0 -189
  497. package/README.md +0 -22
  498. package/build_package.sh +0 -5
  499. package/compileDTS.pl +0 -64
  500. package/docs/ai-assistant-nightly-eval.md +0 -65
  501. package/docs/ai-assistant-preflight-checklist.md +0 -23
  502. package/docs/ai-assistant-report-builder-bridge-playbook.md +0 -115
  503. package/eslint-plugin-custom/index.js +0 -7
  504. package/eslint-plugin-custom/rules/no-filter-zero-index.js +0 -44
  505. package/eslint.config.js +0 -103
  506. package/gulpfile.js +0 -216
  507. package/methodAndPublicationListGenerator.py +0 -375
  508. package/mongodbensurers.js +0 -2
  509. package/mongostop.js +0 -3
  510. package/scripts/cleanup-bypassed-callmethod-logs.js +0 -616
  511. package/settings.development.json +0 -25
  512. package/settings.development.redacted.json +0 -25
  513. package/src/.env +0 -12
  514. package/src/ai/assistant-core-heuristics.ts +0 -379
  515. package/src/ai/resolveio-platform-intelligence-memory-corpus.ts +0 -185
  516. package/src/ai/resolveio-platform-intelligence-memory.ts +0 -325
  517. package/src/ai/resolveio-platform-intelligence.ts +0 -462
  518. package/src/client-server-app.ts +0 -12
  519. package/src/collections/ai-terminal-conversation.collection.ts +0 -91
  520. package/src/collections/ai-terminal-issue-report.collection.ts +0 -99
  521. package/src/collections/ai-terminal-message.collection.ts +0 -77
  522. package/src/collections/app-setting.collection.ts +0 -104
  523. package/src/collections/app-status.collection.ts +0 -58
  524. package/src/collections/communication-metric.collection.ts +0 -84
  525. package/src/collections/counter.collection.ts +0 -56
  526. package/src/collections/cron-job-history.collection.ts +0 -94
  527. package/src/collections/cron-job.collection.ts +0 -92
  528. package/src/collections/customer-notification.collection.ts +0 -131
  529. package/src/collections/customer-portal-password.collection.ts +0 -76
  530. package/src/collections/email-history.collection.ts +0 -127
  531. package/src/collections/email-verified.collection.ts +0 -62
  532. package/src/collections/file.collection.ts +0 -74
  533. package/src/collections/flag-update.collection.ts +0 -57
  534. package/src/collections/flag.collection.ts +0 -57
  535. package/src/collections/log-method-latency.collection.ts +0 -77
  536. package/src/collections/log-subscription.collection.ts +0 -80
  537. package/src/collections/log.collection.ts +0 -93
  538. package/src/collections/logged-in-users.collection.ts +0 -67
  539. package/src/collections/monitor-cpu.collection.ts +0 -65
  540. package/src/collections/monitor-function.collection.ts +0 -74
  541. package/src/collections/monitor-memory.collection.ts +0 -77
  542. package/src/collections/monitor-mongo.collection.ts +0 -71
  543. package/src/collections/notification.collection.ts +0 -57
  544. package/src/collections/openai-usage-ledger.collection.ts +0 -77
  545. package/src/collections/report-builder-dashboard-builder.collection.ts +0 -109
  546. package/src/collections/report-builder-library.collection.ts +0 -89
  547. package/src/collections/report-builder-report.collection.ts +0 -184
  548. package/src/collections/user-group.collection.ts +0 -89
  549. package/src/collections/user-guide.collection.ts +0 -57
  550. package/src/collections/user.collection.ts +0 -181
  551. package/src/cron/cron.ts +0 -117
  552. package/src/fixtures/cron-jobs.ts +0 -95
  553. package/src/fixtures/init.ts +0 -35
  554. package/src/http/auth.ts +0 -764
  555. package/src/http/health.ts +0 -7
  556. package/src/http/home.ts +0 -90
  557. package/src/http/slow-query-publication.ts +0 -49
  558. package/src/index.ts +0 -1
  559. package/src/managers/ai-assistant-codex-manager.manager.ts +0 -1131
  560. package/src/managers/communication-metric.manager.ts +0 -82
  561. package/src/managers/cron.manager.ts +0 -333
  562. package/src/managers/customer-notification-content.manager.ts +0 -236
  563. package/src/managers/diagnostic-manager-bootstrap.ts +0 -165
  564. package/src/managers/error-auto-fix.manager.ts +0 -2767
  565. package/src/managers/local-log.manager.ts +0 -113
  566. package/src/managers/method.manager.ts +0 -1827
  567. package/src/managers/mongo.manager.ts +0 -4575
  568. package/src/managers/monitor.manager.ts +0 -507
  569. package/src/managers/openai-usage-ledger.manager.ts +0 -116
  570. package/src/managers/slow-query-verifier.manager.ts +0 -3590
  571. package/src/managers/slow-query.manager.ts +0 -519
  572. package/src/managers/subscription.manager.ts +0 -3128
  573. package/src/managers/websocket.manager.ts +0 -746
  574. package/src/managers/worker-dispatcher.manager.ts +0 -1360
  575. package/src/managers/worker-server.manager.ts +0 -536
  576. package/src/methods/accounts.ts +0 -532
  577. package/src/methods/ai-terminal.ts +0 -23497
  578. package/src/methods/app-settings.ts +0 -114
  579. package/src/methods/aws.ts +0 -649
  580. package/src/methods/collections.ts +0 -641
  581. package/src/methods/counters.ts +0 -69
  582. package/src/methods/cron-jobs.ts +0 -2614
  583. package/src/methods/customer-notifications.ts +0 -458
  584. package/src/methods/diagnostics.ts +0 -616
  585. package/src/methods/flag-updates.ts +0 -7
  586. package/src/methods/flags.ts +0 -7
  587. package/src/methods/logs.ts +0 -657
  588. package/src/methods/mongo-explorer.ts +0 -1880
  589. package/src/methods/monitor.ts +0 -540
  590. package/src/methods/pdf.ts +0 -1236
  591. package/src/methods/publications.ts +0 -129
  592. package/src/methods/report-builder.ts +0 -3300
  593. package/src/methods/support.ts +0 -335
  594. package/src/models/ai-terminal-conversation.model.ts +0 -19
  595. package/src/models/ai-terminal-issue-report.model.ts +0 -21
  596. package/src/models/ai-terminal-message.model.ts +0 -24
  597. package/src/models/app-setting.model.ts +0 -17
  598. package/src/models/collection-document.model.ts +0 -24
  599. package/src/models/communication-metric.model.ts +0 -23
  600. package/src/models/cron-job-history.model.ts +0 -16
  601. package/src/models/cron-job.model.ts +0 -15
  602. package/src/models/customer-notification.model.ts +0 -28
  603. package/src/models/customer-portal-password.model.ts +0 -12
  604. package/src/models/dialog.model.ts +0 -25
  605. package/src/models/log-method-latency.model.ts +0 -11
  606. package/src/models/log.model.ts +0 -19
  607. package/src/models/method.model.ts +0 -25
  608. package/src/models/monitor-function.model.ts +0 -16
  609. package/src/models/monitor-memory.model.ts +0 -17
  610. package/src/models/monitor-mongo.model.ts +0 -15
  611. package/src/models/openai-usage-ledger.model.ts +0 -16
  612. package/src/models/pagination.model.ts +0 -35
  613. package/src/models/permission.model.ts +0 -14
  614. package/src/models/report-builder-dashboard-builder.model.ts +0 -29
  615. package/src/models/report-builder-library.model.ts +0 -20
  616. package/src/models/report-builder-report.model.ts +0 -136
  617. package/src/models/report-builder.model.ts +0 -68
  618. package/src/models/select-data-label.model.ts +0 -9
  619. package/src/models/server-message.model.ts +0 -31
  620. package/src/models/slow-query-report.model.ts +0 -23
  621. package/src/models/subscription.model.ts +0 -73
  622. package/src/models/support-ticket.model.ts +0 -104
  623. package/src/models/user-group.model.ts +0 -24
  624. package/src/models/user.model.ts +0 -96
  625. package/src/private/images/ResolveIO.png +0 -0
  626. package/src/publications/ai-terminal.ts +0 -73
  627. package/src/publications/app-settings.ts +0 -25
  628. package/src/publications/app-status.ts +0 -13
  629. package/src/publications/cron-jobs.ts +0 -40
  630. package/src/publications/customer-notifications.ts +0 -101
  631. package/src/publications/files.ts +0 -33
  632. package/src/publications/flags-update.ts +0 -19
  633. package/src/publications/flags.ts +0 -19
  634. package/src/publications/logs.ts +0 -163
  635. package/src/publications/notifications.ts +0 -13
  636. package/src/publications/report-builder-dashboard-builders.ts +0 -39
  637. package/src/publications/report-builder-libraries.ts +0 -41
  638. package/src/publications/report-builder-reports.ts +0 -47
  639. package/src/publications/super-admin.ts +0 -13
  640. package/src/publications/user-groups.ts +0 -12
  641. package/src/publications/user-guides.ts +0 -12
  642. package/src/resolveio-server-app.ts +0 -617
  643. package/src/server-app.ts +0 -3354
  644. package/src/services/codex-client.ts +0 -1223
  645. package/src/services/openai-client.ts +0 -265
  646. package/src/types/error-report.ts +0 -26
  647. package/src/types/js-tiktoken.d.ts +0 -11
  648. package/src/types/slow-query-report.ts +0 -28
  649. package/src/util/ai-qa-policy.ts +0 -879
  650. package/src/util/ai-runner-artifacts.ts +0 -430
  651. package/src/util/ai-runner-qa-auth.ts +0 -356
  652. package/src/util/ai-runner-qa-tools.ts +0 -719
  653. package/src/util/common.ts +0 -649
  654. package/src/util/customer-portal-password.ts +0 -183
  655. package/src/util/error-reporter.ts +0 -332
  656. package/src/util/error-tracking.ts +0 -79
  657. package/src/util/report-builder-unwinds.ts +0 -180
  658. package/src/util/runner-process-janitor.ts +0 -195
  659. package/src/util/schema-report-builder.ts +0 -448
  660. package/src/util/slow-query-reporter.ts +0 -216
  661. package/src/util/subscription-dependency-context.ts +0 -1096
  662. package/src/util/tokenizer.ts +0 -38
  663. package/src/workers/codex-runner.worker.ts +0 -142
  664. package/start_server.sh +0 -5
  665. package/tests/ai-assistant-corpus-build.ts +0 -484
  666. package/tests/ai-assistant-corpus-replay-e2e.ts +0 -774
  667. package/tests/ai-assistant-data-parity-e2e.ts +0 -1989
  668. package/tests/ai-assistant-eval-triage.ts +0 -831
  669. package/tests/ai-assistant-openai-e2e.ts +0 -1061
  670. package/tests/ai-assistant-openai-git-e2e.ts +0 -155
  671. package/tests/ai-assistant-preflight-matrix.ts +0 -215
  672. package/tests/ai-assistant-routing-eval.test.ts +0 -560
  673. package/tests/ai-assistant-snf-live-eval.ts +0 -975
  674. package/tests/ai-assistant-utils.test.ts +0 -2968
  675. package/tests/ai-runner-contract.test.ts +0 -287
  676. package/tests/error-reporter.test.ts +0 -145
  677. package/tests/method-publication-generator.test.ts +0 -46
  678. package/tests/report-builder-linking.test.ts +0 -79
  679. package/tests/resolveio-platform-intelligence.test.ts +0 -352
  680. package/tests/server-app-cron-owner.test.ts +0 -127
  681. package/tests/subscription-connect-race.test.ts +0 -158
  682. package/tests/subscription-dependency-context.test.ts +0 -324
  683. package/tests/subscription-manager-collection-tracking.test.ts +0 -86
  684. package/tests/subscription-manager-invalidation.test.ts +0 -86
  685. package/tsconfig.json +0 -34
  686. /package/{src/private → private}/email-templates/enrollment.html +0 -0
  687. /package/{src/private → private}/email-templates/forgot-password.html +0 -0
  688. /package/{src/private → private}/email-templates/support-ticket-deleted.html +0 -0
  689. /package/{src/private → private}/email-templates/support-ticket-modified.html +0 -0
  690. /package/{src/private → private}/email-templates/support-ticket.html +0 -0
  691. /package/{src/public_api.ts → public_api.d.ts} +0 -0
@@ -1,1223 +0,0 @@
1
- import { promises as fs } from 'fs';
2
- import * as os from 'os';
3
- import * as path from 'path';
4
- import { setTimeout as sleepTimeout } from 'timers/promises';
5
- export interface CodexConfig {
6
- apiKey?: string;
7
- baseUrl?: string;
8
- model?: string;
9
- fallbackModel?: string;
10
- fallbackModels?: string[];
11
- maxRetries?: number;
12
- retryDelayMs?: number;
13
- }
14
-
15
- /* eslint-disable no-unused-vars -- Function type params are required for clarity. */
16
- type StreamEventHandler = (event: any) => void | Promise<void>;
17
- type StreamTextHandler = (delta: string, fullText: string) => void | Promise<void>;
18
- type AgentMessageHandler = (text: string) => void | Promise<void>;
19
- type UsageHandler = (usage: CodexUsageSummary | null) => void | Promise<void>;
20
- type DynamicImport = (specifier: string) => Promise<any>;
21
- /* eslint-enable no-unused-vars */
22
-
23
- type CodexModelFallbackPreference = {
24
- fallbackModel: string;
25
- expiresAt: number;
26
- updatedAt: number;
27
- };
28
-
29
- export interface CodexRunOptions {
30
- timeoutMs?: number;
31
- streamIdleTimeoutMs?: number;
32
- processWorkingDirectory?: string;
33
- threadOptions?: CodexThreadOptions;
34
- threadKey?: string;
35
- reuseThread?: boolean;
36
- fallbackModels?: string[];
37
- onStreamEvent?: StreamEventHandler;
38
- onStreamText?: StreamTextHandler;
39
- onUsage?: UsageHandler;
40
- }
41
-
42
- export interface CodexUsageSummary {
43
- inputTokens: number;
44
- cachedInputTokens: number;
45
- outputTokens: number;
46
- }
47
-
48
- export type CodexThreadOptions = {
49
- model?: string;
50
- sandboxMode?: 'read-only' | 'workspace-write' | 'danger-full-access';
51
- workingDirectory?: string;
52
- skipGitRepoCheck?: boolean;
53
- modelReasoningEffort?: 'minimal' | 'none' | 'low' | 'medium' | 'high' | 'xhigh';
54
- networkAccessEnabled?: boolean;
55
- webSearchMode?: 'disabled' | 'cached' | 'live';
56
- webSearchEnabled?: boolean;
57
- approvalPolicy?: 'never' | 'on-request' | 'on-failure' | 'untrusted';
58
- additionalDirectories?: string[];
59
- };
60
-
61
- export class CodexClient {
62
- private static readonly PING_PROMPT = "Say 'pong'";
63
- private static readonly MODEL_UNAVAILABLE_FALLBACK_FILE = path.join(os.tmpdir(), 'resolveio-codex-model-fallbacks.json');
64
- private static readonly DEFAULT_MODEL_UNAVAILABLE_TTL_MS = 6 * 60 * 60 * 1000;
65
- private static readonly MIN_MODEL_UNAVAILABLE_TTL_MS = 60 * 1000;
66
- private static readonly modelFallbackPreferences = new Map<string, CodexModelFallbackPreference>();
67
- private static modelFallbackPreferencesLoaded = false;
68
- private static modelFallbackPreferencesLoadPromise: Promise<void> | null = null;
69
- private static cwdFallbackRunning = false;
70
- private codex: any | null = null;
71
- private codexInit: Promise<void> | null = null;
72
- private readonly threadCache = new Map<string, { thread: any; optionsKey: string; modelKey: string }>();
73
- private readonly debugEnabled = (process.env.AI_DASHBOARD_DEBUG || '').trim().toLowerCase() === 'true';
74
- private readonly streamEnabled = this.resolveStreamEnabled();
75
- private readonly cleanZdotdirEnabled = this.resolveCleanZdotdirEnabled();
76
- private zDotDir: string | null = null;
77
- private readonly defaultTimeoutMs = this.resolveDefaultTimeoutMs();
78
- private readonly pingEnabled = this.resolvePingEnabled();
79
- private readonly pingTimeoutMs = this.resolvePingTimeoutMs();
80
- private readonly modelUnavailableTtlMs = this.resolveModelUnavailableTtlMs();
81
- private readonly config: CodexConfig;
82
- private readonly defaultThreadOptions: CodexThreadOptions;
83
-
84
- constructor(config: CodexConfig) {
85
- this.config = config;
86
- if (!this.config.apiKey) {
87
- throw new Error('AI API key is required for AI client');
88
- }
89
- this.defaultThreadOptions = this.resolveDefaultThreadOptions();
90
- }
91
-
92
- async run(prompt: string, options?: CodexRunOptions): Promise<string> {
93
- await this.ensureModelFallbackPreferencesLoaded();
94
- const maxRetries = this.normalizeRetryCount(this.config.maxRetries);
95
- const retryDelayMs = this.normalizeRetryDelay(this.config.retryDelayMs);
96
- let lastError: unknown = null;
97
- const modelSequence = this.resolveModelSequence(options);
98
- for (let modelIndex = 0; modelIndex < modelSequence.length; modelIndex += 1) {
99
- const model = modelSequence[modelIndex];
100
- const nextModel = modelSequence[modelIndex + 1];
101
- const modelOptions = this.applyModelOverride(options, model);
102
- let processCwdFallbackApplied = false;
103
- let attempt = 0;
104
- while (attempt <= maxRetries) {
105
- try {
106
- this.log(`run model=${model || this.config.model || 'default'} attempt ${attempt + 1}/${maxRetries + 1}`);
107
- if (this.pingEnabled && !this.isPingPrompt(prompt)) {
108
- await this.runPing(modelOptions?.threadOptions);
109
- }
110
- if (this.streamEnabled && !this.isPingPrompt(prompt)) {
111
- const result = await this.runStreamedOnce(prompt, modelOptions);
112
- await this.clearModelFallbackPreference(model);
113
- return result;
114
- }
115
- const result = await this.runOnce(prompt, modelOptions);
116
- await this.clearModelFallbackPreference(model);
117
- return result;
118
- }
119
- catch (error) {
120
- lastError = error;
121
- const message = error instanceof Error ? error.message : String(error || 'Unknown error');
122
- this.log(`run model=${model || this.config.model || 'default'} attempt ${attempt + 1} failed: ${message}`);
123
- if (!processCwdFallbackApplied && this.shouldApplyProcessCwdFallback(error, modelOptions)) {
124
- processCwdFallbackApplied = true;
125
- const workingDirectory = this.resolveProcessWorkingDirectory(modelOptions);
126
- const fallbackOptions = this.applyProcessCwdFallback(modelOptions);
127
- this.log('codex workingDirectory launch failed with os error 2; retrying from process cwd without CLI workingDirectory.');
128
- return await this.withProcessWorkingDirectoryFallback(workingDirectory, async () => {
129
- if (this.streamEnabled && !this.isPingPrompt(prompt)) {
130
- const fallbackResult = await this.runStreamedOnce(prompt, fallbackOptions);
131
- await this.clearModelFallbackPreference(model);
132
- return fallbackResult;
133
- }
134
- const fallbackResult = await this.runOnce(prompt, fallbackOptions);
135
- await this.clearModelFallbackPreference(model);
136
- return fallbackResult;
137
- });
138
- }
139
- if (nextModel && this.isModelAvailabilityError(error)) {
140
- await this.rememberModelFallbackPreference(model, nextModel);
141
- this.log(`model unavailable; retrying with fallback model ${nextModel}`);
142
- break;
143
- }
144
- if (this.isCodexEnvironmentError(error)) {
145
- this.recoverCodexEnvironment(error);
146
- }
147
- if (attempt >= maxRetries || !this.isRetryableError(error)) {
148
- throw lastError;
149
- }
150
- const delay = retryDelayMs * Math.pow(2, attempt);
151
- await this.sleep(delay);
152
- attempt += 1;
153
- }
154
- }
155
- }
156
- throw lastError;
157
- }
158
-
159
- private async runStreamedOnce(prompt: string, options?: CodexRunOptions): Promise<string> {
160
- const startedAt = Date.now();
161
- this.log(`runStreamed start (promptLength=${prompt.length})`);
162
- const thread = await this.startThread(options?.threadOptions, options?.threadKey, options?.reuseThread);
163
- const timeoutMs = options?.timeoutMs ?? this.defaultTimeoutMs;
164
- const streamIdleTimeoutMs = this.normalizeStreamIdleTimeoutMs(options?.streamIdleTimeoutMs);
165
- const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
166
- const timeoutId = controller
167
- ? setTimeout(() => controller.abort(), timeoutMs)
168
- : null;
169
- let lastStreamActivityAt = Date.now();
170
- const idleTimeoutId = controller && streamIdleTimeoutMs > 0
171
- ? setInterval(() => {
172
- if (Date.now() - lastStreamActivityAt >= streamIdleTimeoutMs) {
173
- controller.abort();
174
- }
175
- }, Math.max(15_000, Math.min(60_000, Math.floor(streamIdleTimeoutMs / 4))))
176
- : null;
177
- let finalResponse = '';
178
- let lastText = '';
179
- let usageSummary: CodexUsageSummary | null = null;
180
- try {
181
- const { events } = await thread.runStreamed(prompt, controller ? { signal: controller.signal } : undefined);
182
- for await (const event of events) {
183
- lastStreamActivityAt = Date.now();
184
- if (event?.type === 'turn.completed') {
185
- usageSummary = this.normalizeUsageSummary(event?.usage);
186
- }
187
- if (options?.onStreamEvent) {
188
- try {
189
- await options.onStreamEvent(event);
190
- }
191
- catch (error) {
192
- const message = error instanceof Error ? error.message : String(error || 'Unknown error');
193
- this.log(`onStreamEvent failed: ${message}`);
194
- }
195
- }
196
- await this.handleStreamEvent(event, async (text: string) => {
197
- const next = text || '';
198
- if (!next) {
199
- return;
200
- }
201
- const delta = next.startsWith(lastText) ? next.slice(lastText.length) : next;
202
- if (delta) {
203
- this.logStreamText(delta);
204
- if (options?.onStreamText) {
205
- try {
206
- await options.onStreamText(delta, next);
207
- }
208
- catch (error) {
209
- const message = error instanceof Error ? error.message : String(error || 'Unknown error');
210
- this.log(`onStreamText failed: ${message}`);
211
- }
212
- }
213
- }
214
- lastText = next;
215
- finalResponse = next;
216
- });
217
- if (event?.type === 'turn.failed') {
218
- throw new Error(event.error?.message || 'AI run failed.');
219
- }
220
- if (event?.type === 'error') {
221
- throw new Error(event.message || 'AI stream error.');
222
- }
223
- }
224
- }
225
- catch (error) {
226
- if (controller?.signal?.aborted) {
227
- const idleForMs = Date.now() - lastStreamActivityAt;
228
- if (streamIdleTimeoutMs > 0 && idleForMs >= streamIdleTimeoutMs) {
229
- this.log(`runStreamed idle timed out (durationMs=${Date.now() - startedAt}, idleForMs=${idleForMs})`);
230
- throw new Error(`AI stream stalled with no activity for ${idleForMs}ms.`);
231
- }
232
- this.log(`runStreamed timed out (durationMs=${Date.now() - startedAt})`);
233
- throw new Error('AI request timed out.');
234
- }
235
- const message = error instanceof Error ? error.message : String(error || 'Unknown error');
236
- this.log(`runStreamed failed (durationMs=${Date.now() - startedAt}): ${message}`);
237
- throw error;
238
- }
239
- finally {
240
- if (timeoutId) {
241
- clearTimeout(timeoutId);
242
- }
243
- if (idleTimeoutId) {
244
- clearInterval(idleTimeoutId);
245
- }
246
- }
247
- if (!finalResponse) {
248
- throw new Error('AI returned no completion content.');
249
- }
250
- await this.emitUsageSummary(options, usageSummary);
251
- this.log(`runStreamed complete (contentLength=${finalResponse.length}, durationMs=${Date.now() - startedAt})`);
252
- return finalResponse.trim();
253
- }
254
-
255
- private normalizeStreamIdleTimeoutMs(value: any): number {
256
- const parsed = Number(value || 0);
257
- if (!Number.isFinite(parsed) || parsed < 60_000) {
258
- return 0;
259
- }
260
- return Math.floor(parsed);
261
- }
262
-
263
- private async runOnce(prompt: string, options?: CodexRunOptions): Promise<string> {
264
- const startedAt = Date.now();
265
- this.log(`runOnce start (promptLength=${prompt.length})`);
266
- try {
267
- const thread = await this.startThread(options?.threadOptions, options?.threadKey, options?.reuseThread);
268
- const runPromise = thread.run(prompt);
269
- const timeoutMs = options?.timeoutMs ?? this.defaultTimeoutMs;
270
- this.log(`runOnce awaiting result (timeoutMs=${timeoutMs})`);
271
- const result: any = await this.withTimeout(runPromise, timeoutMs);
272
- const content = this.extractContent(result);
273
- if (!content) {
274
- throw new Error('AI returned no completion content.');
275
- }
276
- await this.emitUsageSummary(options, this.normalizeUsageSummary(result?.usage));
277
- this.log(`runOnce complete (contentLength=${content.length}, durationMs=${Date.now() - startedAt})`);
278
- return content;
279
- }
280
- catch (error) {
281
- const message = error instanceof Error ? error.message : String(error || 'Unknown error');
282
- this.log(`runOnce failed (durationMs=${Date.now() - startedAt}): ${message}`);
283
- throw error;
284
- }
285
- }
286
-
287
- private async startThread(threadOptions?: CodexThreadOptions, threadKey?: string, reuseThread = true): Promise<any> {
288
- await this.ensureCodex();
289
- const mergedOptions = this.mergeThreadOptions(threadOptions);
290
- const optionsKey = this.buildThreadOptionsKey(mergedOptions);
291
- const effectiveModel = mergedOptions?.model || this.config.model || 'default';
292
- const modelKey = this.normalizeOptionalString(effectiveModel).toLowerCase() || 'default';
293
- const cacheKey = this.buildThreadCacheKey(threadKey, mergedOptions);
294
- const explicitThreadKey = (threadKey || '').trim();
295
- const hasExplicitThreadKey = explicitThreadKey.length > 0;
296
- if (reuseThread && cacheKey) {
297
- const existing = this.threadCache.get(cacheKey);
298
- if (existing) {
299
- const sameOptions = existing.optionsKey === optionsKey;
300
- const sameModel = existing.modelKey === modelKey;
301
- if (sameOptions || (hasExplicitThreadKey && sameModel)) {
302
- if (hasExplicitThreadKey && existing.optionsKey !== optionsKey) {
303
- this.log(`startThread reuse explicit key (${cacheKey}) despite option change`);
304
- }
305
- else {
306
- this.log(`startThread reuse (${cacheKey})`);
307
- }
308
- return existing.thread;
309
- }
310
- if (hasExplicitThreadKey && !sameModel) {
311
- this.log(`startThread explicit key (${cacheKey}) model changed (${existing.modelKey} -> ${modelKey}); creating new thread`);
312
- }
313
- }
314
- }
315
- this.log(`startThread (model=${effectiveModel})`);
316
- if (mergedOptions?.model) {
317
- this.log(`startThread options: ${this.formatThreadOptions(mergedOptions)}`);
318
- const thread = this.codex.startThread(mergedOptions);
319
- this.log('startThread created with model override');
320
- if (cacheKey) {
321
- this.threadCache.set(cacheKey, { thread, optionsKey, modelKey });
322
- }
323
- return thread;
324
- }
325
- if (mergedOptions && Object.keys(mergedOptions).length) {
326
- this.log(`startThread options: ${this.formatThreadOptions(mergedOptions)}`);
327
- }
328
- const thread = this.codex.startThread(mergedOptions);
329
- this.log('startThread created');
330
- if (cacheKey) {
331
- this.threadCache.set(cacheKey, { thread, optionsKey, modelKey });
332
- }
333
- return thread;
334
- }
335
-
336
- private extractContent(result: any): string {
337
- if (!result) {
338
- return '';
339
- }
340
- if (typeof result.finalResponse === 'string') {
341
- return result.finalResponse.trim();
342
- }
343
- if (typeof result === 'string') {
344
- return result.trim();
345
- }
346
- if (Array.isArray(result.items)) {
347
- const lastMessage = [...result.items].reverse().find((item: any) => item?.type === 'agent_message' && typeof item.text === 'string');
348
- if (lastMessage?.text) {
349
- return lastMessage.text.trim();
350
- }
351
- }
352
- if (typeof result.output_text === 'string') {
353
- return result.output_text.trim();
354
- }
355
- if (typeof result.outputText === 'string') {
356
- return result.outputText.trim();
357
- }
358
- if (typeof result.content === 'string') {
359
- return result.content.trim();
360
- }
361
- if (typeof result.text === 'string') {
362
- return result.text.trim();
363
- }
364
- if (Array.isArray(result.content)) {
365
- const text = result.content
366
- .map((part: any) => this.extractPartText(part))
367
- .join('')
368
- .trim();
369
- if (text) {
370
- return text;
371
- }
372
- }
373
- if (Array.isArray(result.output)) {
374
- const text = result.output
375
- .map((item: any) => {
376
- if (!item) {
377
- return '';
378
- }
379
- if (typeof item === 'string') {
380
- return item;
381
- }
382
- if (typeof item.text === 'string') {
383
- return item.text;
384
- }
385
- if (typeof item.content === 'string') {
386
- return item.content;
387
- }
388
- if (Array.isArray(item.content)) {
389
- return item.content.map((part: any) => this.extractPartText(part)).join('');
390
- }
391
- return '';
392
- })
393
- .join('')
394
- .trim();
395
- if (text) {
396
- return text;
397
- }
398
- }
399
- return '';
400
- }
401
-
402
- private async handleStreamEvent(event: any, onAgentMessage: AgentMessageHandler): Promise<void> {
403
- if (!event || !event.type) {
404
- return;
405
- }
406
- switch (event.type) {
407
- case 'thread.started':
408
- this.log(`stream thread.started (id=${event.thread_id || 'unknown'})`);
409
- break;
410
- case 'turn.started':
411
- this.log('stream turn.started');
412
- break;
413
- case 'turn.completed':
414
- this.log('stream turn.completed');
415
- break;
416
- case 'item.started':
417
- case 'item.updated':
418
- case 'item.completed':
419
- await this.handleStreamItem(event.item, onAgentMessage);
420
- break;
421
- default:
422
- break;
423
- }
424
- }
425
-
426
- private normalizeUsageSummary(raw: any): CodexUsageSummary | null {
427
- if (!raw || typeof raw !== 'object') {
428
- return null;
429
- }
430
- const inputTokens = this.normalizeUsageToken(raw.input_tokens ?? raw.inputTokens);
431
- const cachedInputTokens = this.normalizeUsageToken(raw.cached_input_tokens ?? raw.cachedInputTokens);
432
- const outputTokens = this.normalizeUsageToken(raw.output_tokens ?? raw.outputTokens);
433
- if (inputTokens <= 0 && cachedInputTokens <= 0 && outputTokens <= 0) {
434
- return null;
435
- }
436
- return {
437
- inputTokens,
438
- cachedInputTokens,
439
- outputTokens
440
- };
441
- }
442
-
443
- private normalizeUsageToken(value: any): number {
444
- const parsed = Number(value);
445
- if (!Number.isFinite(parsed) || parsed <= 0) {
446
- return 0;
447
- }
448
- return Math.floor(parsed);
449
- }
450
-
451
- private async emitUsageSummary(options: CodexRunOptions | undefined, usage: CodexUsageSummary | null): Promise<void> {
452
- if (!options?.onUsage) {
453
- return;
454
- }
455
- try {
456
- await options.onUsage(usage);
457
- }
458
- catch (error) {
459
- const message = error instanceof Error ? error.message : String(error || 'Unknown error');
460
- this.log(`onUsage failed: ${message}`);
461
- }
462
- }
463
-
464
- private async handleStreamItem(item: any, onAgentMessage: AgentMessageHandler): Promise<void> {
465
- if (!item || !item.type) {
466
- return;
467
- }
468
- switch (item.type) {
469
- case 'agent_message':
470
- await onAgentMessage(item.text || '');
471
- break;
472
- case 'command_execution':
473
- if (item.command) {
474
- this.log(`stream command: ${item.command} (${item.status || 'unknown'})`);
475
- }
476
- if (item.aggregated_output) {
477
- const output = item.aggregated_output.length > 800
478
- ? `${item.aggregated_output.slice(0, 800)}...`
479
- : item.aggregated_output;
480
- this.log(`stream command output: ${output}`);
481
- }
482
- break;
483
- case 'file_change':
484
- if (Array.isArray(item.changes) && item.changes.length) {
485
- const summary = item.changes.map((change: any) => `${change.kind}:${change.path}`).join(', ');
486
- this.log(`stream file_change (${item.status || 'unknown'}): ${summary}`);
487
- }
488
- break;
489
- case 'mcp_tool_call':
490
- if (item.tool) {
491
- this.log(`stream tool_call: ${item.tool} (${item.status || 'unknown'})`);
492
- }
493
- if (item.error?.message) {
494
- this.log(`stream tool_call error: ${item.error.message}`);
495
- }
496
- break;
497
- case 'web_search':
498
- if (item.query) {
499
- this.log(`stream web_search: ${item.query}`);
500
- }
501
- break;
502
- case 'todo_list':
503
- if (Array.isArray(item.items)) {
504
- const total = item.items.length;
505
- const done = item.items.filter((entry: any) => entry?.completed).length;
506
- this.log(`stream todo_list: ${done}/${total} completed`);
507
- }
508
- break;
509
- case 'reasoning':
510
- if (item.text) {
511
- const snippet = item.text.length > 200 ? `${item.text.slice(0, 200)}...` : item.text;
512
- this.log(`stream reasoning: ${snippet}`);
513
- }
514
- break;
515
- case 'error':
516
- if (item.message) {
517
- this.log(`stream error: ${item.message}`);
518
- }
519
- break;
520
- default:
521
- break;
522
- }
523
- }
524
-
525
- private logStreamText(text: string): void {
526
- if (!this.debugEnabled) {
527
- return;
528
- }
529
- const lines = text.split(/\r?\n/);
530
- for (const line of lines) {
531
- this.log(`stream: ${line}`);
532
- }
533
- }
534
-
535
- private extractPartText(part: any): string {
536
- if (!part) {
537
- return '';
538
- }
539
- if (typeof part === 'string') {
540
- return part;
541
- }
542
- if (typeof part.text === 'string') {
543
- return part.text;
544
- }
545
- if (typeof part.content === 'string') {
546
- return part.content;
547
- }
548
- return '';
549
- }
550
-
551
- private async withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
552
- let done = false;
553
- const startedAt = Date.now();
554
- const heartbeatMs = Math.max(10000, Math.min(30000, Math.floor(timeoutMs / 4)));
555
- const timeoutPromise = (async (): Promise<T> => {
556
- while (!done) {
557
- const elapsed = Date.now() - startedAt;
558
- if (elapsed >= timeoutMs) {
559
- throw new Error('AI request timed out.');
560
- }
561
- const remaining = timeoutMs - elapsed;
562
- await sleepTimeout(Math.min(heartbeatMs, remaining));
563
- if (done) {
564
- return await promise;
565
- }
566
- const currentElapsed = Date.now() - startedAt;
567
- if (currentElapsed >= timeoutMs) {
568
- throw new Error('AI request timed out.');
569
- }
570
- const currentRemaining = Math.max(0, timeoutMs - currentElapsed);
571
- this.log(`runOnce waiting (elapsedMs=${currentElapsed}, remainingMs=${currentRemaining})`);
572
- }
573
- return await promise;
574
- })();
575
- try {
576
- return await Promise.race([promise, timeoutPromise]);
577
- }
578
- finally {
579
- done = true;
580
- }
581
- }
582
-
583
- private normalizeRetryCount(value?: number): number {
584
- if (typeof value !== 'number' || Number.isNaN(value)) {
585
- return 2;
586
- }
587
- return Math.max(0, Math.floor(value));
588
- }
589
-
590
- private normalizeRetryDelay(value?: number): number {
591
- if (typeof value !== 'number' || Number.isNaN(value)) {
592
- return 500;
593
- }
594
- return Math.max(100, Math.floor(value));
595
- }
596
-
597
- private resolveModelSequence(options?: CodexRunOptions): string[] {
598
- const primary = this.normalizeOptionalString(options?.threadOptions?.model || this.config.model);
599
- const fallbackModels = this.collectFallbackModels(options?.fallbackModels);
600
- const sequence: string[] = [];
601
- const push = (value: any) => {
602
- const normalized = this.normalizeOptionalString(value);
603
- if (!normalized || sequence.includes(normalized)) {
604
- return;
605
- }
606
- sequence.push(normalized);
607
- };
608
- const preferredFallback = this.getModelFallbackPreference(primary);
609
- if (preferredFallback) {
610
- push(preferredFallback);
611
- this.log(`sticky model fallback active: ${primary} -> ${preferredFallback}`);
612
- }
613
- push(primary);
614
- fallbackModels.forEach(push);
615
- if (!sequence.length) {
616
- sequence.push('');
617
- }
618
- return sequence;
619
- }
620
-
621
- private collectFallbackModels(runFallbackModels?: string[]): string[] {
622
- const models: string[] = [];
623
- const push = (value: any) => {
624
- const normalized = this.normalizeOptionalString(value);
625
- if (!normalized || models.includes(normalized)) {
626
- return;
627
- }
628
- models.push(normalized);
629
- };
630
- this.normalizeModelList(runFallbackModels).forEach(push);
631
- this.normalizeModelList(this.config.fallbackModels).forEach(push);
632
- push(this.config.fallbackModel);
633
- this.normalizeModelList(process.env.AI_ASSISTANT_CODEX_FALLBACK_MODELS).forEach(push);
634
- push(process.env.AI_ASSISTANT_CODEX_FALLBACK_MODEL);
635
- this.normalizeModelList(process.env.AI_TERMINAL_CODEX_FALLBACK_MODELS).forEach(push);
636
- push(process.env.AI_TERMINAL_CODEX_FALLBACK_MODEL);
637
- this.normalizeModelList(process.env.AI_DASHBOARD_CODEX_FALLBACK_MODELS).forEach(push);
638
- push(process.env.AI_DASHBOARD_CODEX_FALLBACK_MODEL);
639
- const primaryModel = this.normalizeOptionalString(
640
- this.config.model
641
- || runFallbackModels?.[0]
642
- || ''
643
- );
644
- if (/^gpt-5(?:\.\d+)?-codex$/i.test(primaryModel)) {
645
- push('gpt-5-codex');
646
- }
647
- if (/^gpt-5(?:-codex|\.\d+-codex)$/i.test(primaryModel)) {
648
- push('gpt-5.5');
649
- }
650
- return models;
651
- }
652
-
653
- private normalizeModelList(value: any): string[] {
654
- if (Array.isArray(value)) {
655
- return value
656
- .map(entry => this.normalizeOptionalString(entry))
657
- .filter(Boolean);
658
- }
659
- const raw = this.normalizeOptionalString(value);
660
- if (!raw) {
661
- return [];
662
- }
663
- return raw
664
- .split(',')
665
- .map(entry => this.normalizeOptionalString(entry))
666
- .filter(Boolean);
667
- }
668
-
669
- private applyModelOverride(options: CodexRunOptions | undefined, model: string): CodexRunOptions {
670
- const nextThreadOptions: CodexThreadOptions = {
671
- ...(options?.threadOptions || {})
672
- };
673
- if (model) {
674
- nextThreadOptions.model = model;
675
- }
676
- else {
677
- delete nextThreadOptions.model;
678
- }
679
- return {
680
- ...(options || {}),
681
- threadOptions: nextThreadOptions
682
- };
683
- }
684
-
685
- private isModelAvailabilityError(error: unknown): boolean {
686
- const message = error instanceof Error ? error.message : String(error || '');
687
- const normalized = message.toLowerCase();
688
- if (!normalized.includes('model')) {
689
- return false;
690
- }
691
- if (/does not exist|not found|unknown model|invalid model|unsupported model|model_not_found|no such model/.test(normalized)) {
692
- return true;
693
- }
694
- if (/not available|unavailable|not enabled|not allowed|do not have access|don't have access|insufficient permissions/.test(normalized)) {
695
- return true;
696
- }
697
- return /404/.test(normalized) && /model/.test(normalized);
698
- }
699
-
700
- private isRetryableError(error: unknown): boolean {
701
- const message = error instanceof Error ? error.message : String(error || '');
702
- if (/AI returned no completion content|Codex returned no completion content/i.test(message)) {
703
- return true;
704
- }
705
- if (this.isCodexEnvironmentError(error)) {
706
- return true;
707
- }
708
- const statusMatch = message.match(/\\b(429|5\\d{2})\\b/);
709
- if (statusMatch) {
710
- return true;
711
- }
712
- return /ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|fetch failed|timed out|timeout/i.test(message);
713
- }
714
-
715
- private isCodexEnvironmentError(error: unknown): boolean {
716
- const message = error instanceof Error ? error.message : String(error || '');
717
- return /error finding codex home|could not update path: no such file or directory/i.test(message);
718
- }
719
-
720
- private recoverCodexEnvironment(error: unknown): void {
721
- const message = error instanceof Error ? error.message : String(error || 'Unknown error');
722
- this.log(`recovering codex environment after error: ${message}`);
723
- this.threadCache.clear();
724
- this.codex = null;
725
- this.codexInit = null;
726
- this.zDotDir = null;
727
- }
728
-
729
- private shouldApplyProcessCwdFallback(error: unknown, options?: CodexRunOptions): boolean {
730
- const workingDirectory = this.resolveProcessWorkingDirectory(options);
731
- if (!workingDirectory) {
732
- return false;
733
- }
734
- const message = error instanceof Error ? error.message : String(error || '');
735
- return /no such file or directory \(os error 2\)/i.test(message);
736
- }
737
-
738
- private resolveProcessWorkingDirectory(options?: CodexRunOptions): string {
739
- return this.normalizeOptionalString(options?.processWorkingDirectory || options?.threadOptions?.workingDirectory);
740
- }
741
-
742
- private applyProcessCwdFallback(options?: CodexRunOptions): CodexRunOptions {
743
- const nextThreadOptions: CodexThreadOptions = {
744
- ...(options?.threadOptions || {})
745
- };
746
- delete nextThreadOptions.workingDirectory;
747
- return {
748
- ...(options || {}),
749
- threadOptions: nextThreadOptions
750
- };
751
- }
752
-
753
- private async withProcessWorkingDirectoryFallback<T>(workingDirectory: string, runner: () => Promise<T>): Promise<T> {
754
- const normalizedWorkingDirectory = this.normalizeOptionalString(workingDirectory);
755
- if (!normalizedWorkingDirectory) {
756
- return await runner();
757
- }
758
-
759
- while (CodexClient.cwdFallbackRunning) {
760
- await this.sleep(50);
761
- }
762
- CodexClient.cwdFallbackRunning = true;
763
-
764
- const originalCwd = process.cwd();
765
- try {
766
- process.chdir(normalizedWorkingDirectory);
767
- this.log(`running Codex fallback from process cwd ${normalizedWorkingDirectory}`);
768
- return await runner();
769
- }
770
- finally {
771
- try {
772
- process.chdir(originalCwd);
773
- }
774
- catch (error) {
775
- const message = error instanceof Error ? error.message : String(error || 'Unknown error');
776
- this.log(`failed to restore process cwd to ${originalCwd}: ${message}`);
777
- }
778
- CodexClient.cwdFallbackRunning = false;
779
- }
780
- }
781
-
782
- private normalizeOptionalString(value: any): string {
783
- return typeof value === 'string' ? value.trim() : '';
784
- }
785
-
786
- private resolveModelUnavailableTtlMs(): number {
787
- const raw = Number(
788
- process.env.AI_DASHBOARD_CODEX_MODEL_UNAVAILABLE_TTL_MS
789
- || process.env.AI_ASSISTANT_CODEX_MODEL_UNAVAILABLE_TTL_MS
790
- );
791
- if (Number.isFinite(raw) && raw >= CodexClient.MIN_MODEL_UNAVAILABLE_TTL_MS) {
792
- return Math.floor(raw);
793
- }
794
- return CodexClient.DEFAULT_MODEL_UNAVAILABLE_TTL_MS;
795
- }
796
-
797
- private async ensureModelFallbackPreferencesLoaded(): Promise<void> {
798
- if (CodexClient.modelFallbackPreferencesLoaded) {
799
- this.pruneModelFallbackPreferences();
800
- return;
801
- }
802
- if (CodexClient.modelFallbackPreferencesLoadPromise !== null) {
803
- await CodexClient.modelFallbackPreferencesLoadPromise;
804
- this.pruneModelFallbackPreferences();
805
- return;
806
- }
807
- CodexClient.modelFallbackPreferencesLoadPromise = (async () => {
808
- try {
809
- const raw = await fs.readFile(CodexClient.MODEL_UNAVAILABLE_FALLBACK_FILE, 'utf8');
810
- const parsed = JSON.parse(raw);
811
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
812
- return;
813
- }
814
- Object.entries(parsed).forEach(([model, entry]) => {
815
- const key = this.normalizeOptionalString(model);
816
- if (!key) {
817
- return;
818
- }
819
- const fallbackModel = this.normalizeOptionalString((entry as any)?.fallbackModel);
820
- const expiresAt = Number((entry as any)?.expiresAt);
821
- const updatedAt = Number((entry as any)?.updatedAt);
822
- if (!fallbackModel || !Number.isFinite(expiresAt) || expiresAt <= Date.now()) {
823
- return;
824
- }
825
- CodexClient.modelFallbackPreferences.set(key, {
826
- fallbackModel,
827
- expiresAt: Math.floor(expiresAt),
828
- updatedAt: Number.isFinite(updatedAt) ? Math.floor(updatedAt) : Date.now()
829
- });
830
- });
831
- }
832
- catch {
833
- // Ignore cache load errors.
834
- }
835
- finally {
836
- CodexClient.modelFallbackPreferencesLoaded = true;
837
- CodexClient.modelFallbackPreferencesLoadPromise = null;
838
- }
839
- })();
840
- await CodexClient.modelFallbackPreferencesLoadPromise;
841
- this.pruneModelFallbackPreferences();
842
- }
843
-
844
- private pruneModelFallbackPreferences(now = Date.now()): void {
845
- Array.from(CodexClient.modelFallbackPreferences.entries()).forEach(([model, entry]) => {
846
- if (!entry || !Number.isFinite(entry.expiresAt) || entry.expiresAt <= now) {
847
- CodexClient.modelFallbackPreferences.delete(model);
848
- }
849
- });
850
- }
851
-
852
- private getModelFallbackPreference(model: string): string {
853
- const normalizedModel = this.normalizeOptionalString(model);
854
- if (!normalizedModel) {
855
- return '';
856
- }
857
- this.pruneModelFallbackPreferences();
858
- const entry = CodexClient.modelFallbackPreferences.get(normalizedModel);
859
- if (!entry || entry.expiresAt <= Date.now()) {
860
- if (entry) {
861
- CodexClient.modelFallbackPreferences.delete(normalizedModel);
862
- }
863
- return '';
864
- }
865
- return entry.fallbackModel;
866
- }
867
-
868
- private async rememberModelFallbackPreference(model: string, fallbackModel: string): Promise<void> {
869
- const normalizedModel = this.normalizeOptionalString(model);
870
- const normalizedFallback = this.normalizeOptionalString(fallbackModel);
871
- if (!normalizedModel || !normalizedFallback || normalizedModel === normalizedFallback) {
872
- return;
873
- }
874
- const now = Date.now();
875
- CodexClient.modelFallbackPreferences.set(normalizedModel, {
876
- fallbackModel: normalizedFallback,
877
- expiresAt: now + this.modelUnavailableTtlMs,
878
- updatedAt: now
879
- });
880
- this.pruneModelFallbackPreferences(now);
881
- await this.persistModelFallbackPreferences();
882
- }
883
-
884
- private async clearModelFallbackPreference(model: string): Promise<void> {
885
- const normalizedModel = this.normalizeOptionalString(model);
886
- if (!normalizedModel) {
887
- return;
888
- }
889
- if (!CodexClient.modelFallbackPreferences.has(normalizedModel)) {
890
- return;
891
- }
892
- CodexClient.modelFallbackPreferences.delete(normalizedModel);
893
- await this.persistModelFallbackPreferences();
894
- }
895
-
896
- private async persistModelFallbackPreferences(): Promise<void> {
897
- this.pruneModelFallbackPreferences();
898
- if (!CodexClient.modelFallbackPreferences.size) {
899
- try {
900
- await fs.unlink(CodexClient.MODEL_UNAVAILABLE_FALLBACK_FILE);
901
- }
902
- catch {
903
- // Ignore file cleanup errors.
904
- }
905
- return;
906
- }
907
- const serialized: Record<string, CodexModelFallbackPreference> = {};
908
- CodexClient.modelFallbackPreferences.forEach((entry, model) => {
909
- serialized[model] = entry;
910
- });
911
- try {
912
- await fs.writeFile(CodexClient.MODEL_UNAVAILABLE_FALLBACK_FILE, JSON.stringify(serialized), 'utf8');
913
- }
914
- catch {
915
- // Ignore cache persistence errors.
916
- }
917
- }
918
-
919
- private async sleep(ms: number): Promise<void> {
920
- await sleepTimeout(ms);
921
- }
922
-
923
- private async ensureCodex(): Promise<void> {
924
- if (this.codex) {
925
- return;
926
- }
927
- if (this.codexInit !== null) {
928
- await this.codexInit;
929
- return;
930
- }
931
- this.codexInit = (async () => {
932
- this.log('Loading AI SDK module...');
933
- const importer = new Function('specifier', 'return import(specifier)') as DynamicImport;
934
- const mod = await importer('@openai/codex-sdk');
935
- const CodexCtor = mod?.Codex || mod?.default?.Codex || mod?.default || mod;
936
- if (!CodexCtor) {
937
- throw new Error('AI SDK export not found.');
938
- }
939
- this.log('AI SDK module loaded.');
940
- const env = await this.buildCodexEnv();
941
- this.codex = new CodexCtor({
942
- apiKey: this.config.apiKey,
943
- baseUrl: this.config.baseUrl,
944
- model: this.config.model,
945
- env
946
- });
947
- this.log('AI client initialized.');
948
- })();
949
- await this.codexInit;
950
- }
951
-
952
- private log(message: string): void {
953
- if (!this.debugEnabled) {
954
- return;
955
- }
956
- console.log(`[AI-Dashboard][AI] ${message}`);
957
- }
958
-
959
- private resolveDefaultTimeoutMs(): number {
960
- const raw = Number(process.env.AI_DASHBOARD_CODEX_TIMEOUT_MS || process.env.AI_DASHBOARD_AGENT_TIMEOUT_MS);
961
- if (Number.isFinite(raw) && raw > 0) {
962
- return Math.floor(raw);
963
- }
964
- return 600000;
965
- }
966
-
967
- private resolveStreamEnabled(): boolean {
968
- const raw = (process.env.AI_DASHBOARD_CODEX_STREAM || '').trim().toLowerCase();
969
- if (!raw) {
970
- return this.debugEnabled;
971
- }
972
- if (['true', '1', 'yes', 'y', 'on'].includes(raw)) {
973
- return true;
974
- }
975
- if (['false', '0', 'no', 'n', 'off'].includes(raw)) {
976
- return false;
977
- }
978
- return this.debugEnabled;
979
- }
980
-
981
- private resolveCleanZdotdirEnabled(): boolean {
982
- const raw = (process.env.AI_DASHBOARD_CODEX_CLEAN_ZDOTDIR ?? '').trim().toLowerCase();
983
- if (!raw) {
984
- return true;
985
- }
986
- if (['false', '0', 'no', 'n', 'off'].includes(raw)) {
987
- return false;
988
- }
989
- if (['true', '1', 'yes', 'y', 'on'].includes(raw)) {
990
- return true;
991
- }
992
- return true;
993
- }
994
-
995
- private async buildCodexEnv(): Promise<Record<string, string>> {
996
- const env: Record<string, string> = {};
997
- for (const [key, value] of Object.entries(process.env)) {
998
- if (typeof value === 'string') {
999
- env[key] = value;
1000
- }
1001
- }
1002
- if (!this.normalizeOptionalString(env.HOME)) {
1003
- const fallbackHome = this.normalizeOptionalString(process.env.HOME || os.homedir());
1004
- if (fallbackHome) {
1005
- env.HOME = fallbackHome;
1006
- }
1007
- }
1008
- await this.ensureCodexHome(env);
1009
- if (this.cleanZdotdirEnabled) {
1010
- env.ZDOTDIR = await this.ensureZdotdir();
1011
- }
1012
- return env;
1013
- }
1014
-
1015
- private async ensureCodexHome(env: Record<string, string>): Promise<void> {
1016
- const current = this.normalizeOptionalString(env.CODEX_HOME || process.env.CODEX_HOME);
1017
- const homeRoot = this.normalizeOptionalString(env.HOME || process.env.HOME || os.homedir());
1018
- const primary = current || (homeRoot ? path.join(homeRoot, '.codex') : path.join(os.tmpdir(), 'resolveio-codex-home'));
1019
- try {
1020
- await fs.mkdir(path.join(primary, 'sessions'), { recursive: true });
1021
- env.CODEX_HOME = primary;
1022
- process.env.CODEX_HOME = primary;
1023
- return;
1024
- }
1025
- catch {
1026
- const fallback = path.join(os.tmpdir(), 'resolveio-codex-home');
1027
- await fs.mkdir(path.join(fallback, 'sessions'), { recursive: true });
1028
- env.CODEX_HOME = fallback;
1029
- process.env.CODEX_HOME = fallback;
1030
- }
1031
- }
1032
-
1033
- private async ensureZdotdir(): Promise<string> {
1034
- if (this.zDotDir) {
1035
- return this.zDotDir;
1036
- }
1037
- const override = (process.env.AI_DASHBOARD_CODEX_ZDOTDIR || '').trim();
1038
- const dir = override || path.join(os.tmpdir(), 'codex-zdotdir');
1039
- await fs.mkdir(dir, { recursive: true });
1040
- await Promise.allSettled([
1041
- fs.writeFile(path.join(dir, '.zshrc'), '', { flag: 'a' }),
1042
- fs.writeFile(path.join(dir, '.zprofile'), '', { flag: 'a' })
1043
- ]);
1044
- this.zDotDir = dir;
1045
- return dir;
1046
- }
1047
-
1048
- private resolvePingEnabled(): boolean {
1049
- return this.normalizeBoolean(process.env.AI_DASHBOARD_CODEX_PING, false);
1050
- }
1051
-
1052
- private resolvePingTimeoutMs(): number {
1053
- const raw = Number(process.env.AI_DASHBOARD_CODEX_PING_TIMEOUT_MS);
1054
- if (Number.isFinite(raw) && raw > 0) {
1055
- return Math.floor(raw);
1056
- }
1057
- return 10000;
1058
- }
1059
-
1060
- private resolveDefaultThreadOptions(): CodexThreadOptions {
1061
- const approvalPolicy = this.normalizeApprovalPolicy(process.env.AI_DASHBOARD_CODEX_APPROVAL_POLICY);
1062
- const sandboxMode = this.normalizeSandboxMode(process.env.AI_DASHBOARD_CODEX_SANDBOX_MODE, 'workspace-write');
1063
- const skipGitRepoCheck = this.normalizeBoolean(process.env.AI_DASHBOARD_CODEX_SKIP_GIT_CHECK, true);
1064
- const webSearchMode = this.normalizeWebSearchMode(process.env.AI_DASHBOARD_CODEX_WEB_SEARCH_MODE);
1065
- const webSearchEnabled = this.normalizeBoolean(process.env.AI_DASHBOARD_CODEX_WEB_SEARCH_ENABLED, false);
1066
- const networkAccessEnabled = this.normalizeBoolean(process.env.AI_DASHBOARD_CODEX_NETWORK_ACCESS_ENABLED, false);
1067
- const modelReasoningEffort = this.normalizeModelReasoningEffort(process.env.AI_DASHBOARD_CODEX_REASONING_EFFORT);
1068
- return {
1069
- model: this.config.model,
1070
- approvalPolicy,
1071
- sandboxMode,
1072
- skipGitRepoCheck,
1073
- webSearchMode,
1074
- webSearchEnabled,
1075
- networkAccessEnabled,
1076
- modelReasoningEffort
1077
- };
1078
- }
1079
-
1080
- private mergeThreadOptions(overrides?: CodexThreadOptions): CodexThreadOptions | undefined {
1081
- const merged: CodexThreadOptions = {
1082
- ...this.defaultThreadOptions,
1083
- ...(overrides || {})
1084
- };
1085
- const effectiveModel = this.normalizeOptionalString(merged.model || this.config.model);
1086
- const normalizedEffort = this.normalizeModelReasoningEffortForModel(effectiveModel, merged.modelReasoningEffort);
1087
- if (normalizedEffort && normalizedEffort !== merged.modelReasoningEffort) {
1088
- this.log(`normalized reasoning effort for model=${effectiveModel || 'default'}: ${merged.modelReasoningEffort} -> ${normalizedEffort}`);
1089
- merged.modelReasoningEffort = normalizedEffort;
1090
- }
1091
- const cleaned = Object.entries(merged).reduce((acc, [key, value]) => {
1092
- if (value === undefined || value === null || value === '') {
1093
- return acc;
1094
- }
1095
- (acc as any)[key] = value;
1096
- return acc;
1097
- }, {} as CodexThreadOptions);
1098
- return Object.keys(cleaned).length ? cleaned : undefined;
1099
- }
1100
-
1101
- private normalizeApprovalPolicy(value?: string): CodexThreadOptions['approvalPolicy'] {
1102
- const normalized = (value || '').trim().toLowerCase();
1103
- if (normalized === 'never' || normalized === 'on-request' || normalized === 'on-failure' || normalized === 'untrusted') {
1104
- return normalized as CodexThreadOptions['approvalPolicy'];
1105
- }
1106
- return 'never';
1107
- }
1108
-
1109
- private normalizeSandboxMode(value?: string, fallback: CodexThreadOptions['sandboxMode'] = 'read-only'): CodexThreadOptions['sandboxMode'] {
1110
- const normalized = (value || '').trim().toLowerCase();
1111
- if (normalized === 'read-only' || normalized === 'workspace-write' || normalized === 'danger-full-access') {
1112
- return normalized as CodexThreadOptions['sandboxMode'];
1113
- }
1114
- return fallback;
1115
- }
1116
-
1117
- private normalizeWebSearchMode(value?: string): CodexThreadOptions['webSearchMode'] | undefined {
1118
- const normalized = (value || '').trim().toLowerCase();
1119
- if (normalized === 'disabled' || normalized === 'cached' || normalized === 'live') {
1120
- return normalized as CodexThreadOptions['webSearchMode'];
1121
- }
1122
- return undefined;
1123
- }
1124
-
1125
- private normalizeModelReasoningEffort(value?: string): CodexThreadOptions['modelReasoningEffort'] | undefined {
1126
- const normalized = (value || '').trim().toLowerCase();
1127
- if (normalized === 'minimal' || normalized === 'none' || normalized === 'low' || normalized === 'medium' || normalized === 'high' || normalized === 'xhigh') {
1128
- return normalized as CodexThreadOptions['modelReasoningEffort'];
1129
- }
1130
- return undefined;
1131
- }
1132
-
1133
- private normalizeModelReasoningEffortForModel(
1134
- model: string,
1135
- effort?: CodexThreadOptions['modelReasoningEffort']
1136
- ): CodexThreadOptions['modelReasoningEffort'] | undefined {
1137
- if (!effort) {
1138
- return effort;
1139
- }
1140
- const normalizedModel = this.normalizeOptionalString(model).toLowerCase();
1141
- if (effort === 'minimal' && (!normalizedModel || normalizedModel.startsWith('gpt-5') || normalizedModel.includes('codex'))) {
1142
- return 'low';
1143
- }
1144
- return effort;
1145
- }
1146
-
1147
- private normalizeBoolean(value: string | undefined, fallback: boolean): boolean {
1148
- if (!value) {
1149
- return fallback;
1150
- }
1151
- const normalized = value.trim().toLowerCase();
1152
- if (['true', '1', 'yes', 'y', 'on'].includes(normalized)) {
1153
- return true;
1154
- }
1155
- if (['false', '0', 'no', 'n', 'off'].includes(normalized)) {
1156
- return false;
1157
- }
1158
- return fallback;
1159
- }
1160
-
1161
- private formatThreadOptions(options: CodexThreadOptions): string {
1162
- const summary: Record<string, string> = {};
1163
- Object.entries(options).forEach(([key, value]) => {
1164
- if (value === undefined || value === null) {
1165
- return;
1166
- }
1167
- summary[key] = String(value);
1168
- });
1169
- return JSON.stringify(summary);
1170
- }
1171
-
1172
- private buildThreadOptionsKey(options?: CodexThreadOptions): string {
1173
- if (!options) {
1174
- return '';
1175
- }
1176
- const ordered: Record<string, string> = {};
1177
- Object.keys(options)
1178
- .sort()
1179
- .forEach((key) => {
1180
- const value = (options as Record<string, unknown>)[key];
1181
- if (value === undefined || value === null) {
1182
- return;
1183
- }
1184
- ordered[key] = Array.isArray(value) ? JSON.stringify(value) : String(value);
1185
- });
1186
- return JSON.stringify(ordered);
1187
- }
1188
-
1189
- private buildThreadCacheKey(threadKey: string | undefined, options?: CodexThreadOptions): string | null {
1190
- if (threadKey) {
1191
- return `thread:${threadKey}`;
1192
- }
1193
- const model = options?.model || this.config.model;
1194
- const workingDirectory = options?.workingDirectory;
1195
- if (!model && !workingDirectory) {
1196
- return null;
1197
- }
1198
- return `thread:auto:${model || 'default'}:${workingDirectory || 'root'}`;
1199
- }
1200
-
1201
- private isPingPrompt(prompt: string): boolean {
1202
- return prompt.trim() === CodexClient.PING_PROMPT;
1203
- }
1204
-
1205
- private async runPing(threadOptions?: CodexThreadOptions): Promise<void> {
1206
- this.log(`runPing start (timeoutMs=${this.pingTimeoutMs})`);
1207
- try {
1208
- const content = await this.runOnce(CodexClient.PING_PROMPT, {
1209
- timeoutMs: this.pingTimeoutMs,
1210
- threadOptions,
1211
- reuseThread: false
1212
- });
1213
- const trimmed = content.trim();
1214
- const preview = trimmed.length > 80 ? `${trimmed.slice(0, 80)}…` : trimmed;
1215
- this.log(`runPing response: ${preview}`);
1216
- }
1217
- catch (error) {
1218
- const message = error instanceof Error ? error.message : String(error || 'Unknown error');
1219
- this.log(`runPing failed: ${message}`);
1220
- throw error;
1221
- }
1222
- }
1223
- }